blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b49100d826e29d6b8e3d71d0847b6a41772dd06d | Akash-Rokade/Python | /29-Jan/drink excercise1.py | 1,173 | 3.59375 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
df=pd.read_csv("drinks_data.csv")
print(df)
beer_servings=df.beer_servings
spirit_servings=df.spirit_servings
wine_servings=df.wine_servings
total_litresof_pure_alcohol=df.total_litresof_pure_alcohol
#filling blank spaces using mean
df["beer_servings"]=df["beer_servings"].fillna(df["beer_servings"].mean())
df["spirit_servings"]=df["spirit_servings"].fillna(df["spirit_servings"].mean())
df["wine_servings"]=df["wine_servings"].fillna(df["wine_servings"].mean())
df["total_litresof_pure_alcohol"]=df["total_litresof_pure_alcohol"].fillna(df["total_litresof_pure_alcohol"].mean())
print(beer_servings)
print(spirit_servings)
print(wine_servings)
print(total_litresof_pure_alcohol)
data={"x":[1,2,3,4,5,6],"y":[5,6,7,8,9,3]}
df=pd.DataFrame(data)
x=df["x"]
y=df["y"]
print(x)
print(y)
xtrain,xtest,ytrain,ytest=train_test_split(x,y)
linearRegressor=LinearRegression()
linearRegressor.fit(xtrain,ytrain)
ypred=linearRegressor.predict(xtest)
print(ypred)
|
ab7eefda4b7c572b8d411d1b37c76b3b5bd2c915 | wan-catherine/Leetcode | /problems/N517_Super_Washing_Machines.py | 1,228 | 3.5 | 4 | from typing import List
"""
left[i] : the number of dress for i index get from left
right[i]: the number of dress for i index get from right
left[i] and right[i] can be positive and negative.
positive : get dress, negative : give dress
left[i] + right[i] = machines[i] - val (in order to get val, it much get/throw left[i] + right[i] dresses)
left[i+1] = - right[i]
then we can find the largest give times (not max(left[i] + right[i]), because one of them might be negative.
We only need to the largest GIVE times.
"""
class Solution:
def findMinMoves(self, machines: List[int]) -> int:
length, total = len(machines), sum(machines)
if total % length:
return -1
val = total // length
left, right = [0] * length, [0] * length
right[0] = machines[0] - val
left[length-1] = machines[length-1] -val
for i in range(1, length - 1):
left[i] = -right[i-1]
right[i] = machines[i] - val - left[i]
res = 0
for i in range(length):
cur = 0
if left[i] > 0:
cur += left[i]
if right[i] > 0:
cur += right[i]
res = max(res, cur)
return res
|
1cc59b93ab7aabf8734968d4931c1c6b1af0dcae | AMHlocal/Python-Challenge | /PyBank/main.py | 2,737 | 3.96875 | 4 | #Dependencies
import os
import csv
csvpath = os.path.join('Resources', 'budget_data.csv')
#Variables/lists to hold data
month = 0
cash = 0
previous = 0
diff_list = []
month_list = []
#open the csv file, read headers
with open(csvpath, newline='') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=",")
csv_header = next(csv_reader)
#print(f"Header: {csv_header}")
#Loop Through data
for row in csv_reader:
month += 1 #adds up all the months
current = int(row[1])
cash += current #sums the cash
month_list.append(row[0]) #add a new month to the end of the months_list
#calculate the difference in profit/loss bewteen each month
if previous != 0: # if the pervious month is not equal to 0
difference = current - previous #then calculate the difference by taking the current difference subtracting the pervious
previous = current #the previous difference is the current differnce, this will give us the change for each month
else:
difference = 0 #if the difference is 0 then the pervious is 0 the previous difference is the current amount
previous = current
diff_list.append(difference) #add the differences from each month to the end of the diff_list
#find the average change of profit/lost between each month
average = round(sum(diff_list) / (month - 1),2)
#locate greatest increase/decrease in profits
greatest_increase = max(diff_list)
greatest_decrease = min(diff_list)
#locate months of greatest increase/decrease in profits
greatest_month_inc = diff_list.index(greatest_increase)
greatest_month_dec = diff_list.index(greatest_decrease)
#get month from index values
month_greatest = month_list[greatest_month_inc]
month_lowest = month_list[greatest_month_dec]
#Summary table to terminal
print("")
print("Financial Analysis")
print("-----------------------")
print(f"Total Months: {month}")
print(f"Total: ${cash}")
print(f"Average Change: $ {average} ")
print(f"Greatest Increase in Profits: {month_greatest} (${greatest_increase})")
print(f"Greatest Decrease in Profits: {month_lowest} (${greatest_decrease})")
print()
#export to a text file
analysis = os.path.join("Analysis", "PyBank_anaylsis.txt") #sets path & names file
with open(analysis, "w") as output:
output.write("Financial Analysis\n")
output.write("-----------------------\n")
output.write(f"Total Months: {month}\n")
output.write(f"Total: ${cash}\n")
output.write(f"Average Change: $ {average}\n")
output.write(f"Greatest Increase in Profits: {month_greatest} (${greatest_increase})\n")
output.write(f"Greatest Decrease in Profits: {month_lowest} (${greatest_decrease})\n")
|
66274167af58f857896c21383d83fc622e6bf701 | bara-dankova/Exercise14 | /rockpaperscissors.py | 1,718 | 4.4375 | 4 | # import modules
from random import randint
# define function with no parameters
def rps():
# ask user for input and make sure they enter one of the three options
human = input("Please enter R for ROCK, P for PAPER or S for SCISSORS: ")
while not human in ["R", "P", "S"]:
human = input("Please enter R for ROCK, P for PAPER or S for SCISSORS: ")
# initialize a variable for the computer's choice
computer = ""
# generate a random number between 0 and 2 (both limits are inclusive)
n = randint(0,2)
# translate generated number into a string to correspond to human choices
if n == 0:
computer = "R"
if n == 1:
computer = "P"
if n == 2:
computer = "S"
# use if-statements to define when user wins or loses according to the logic of the game
if computer == "R" and human == "P":
print("The computer chose ROCK, you WIN!")
if computer == "R" and human == "S":
print("The computer chose ROCK, you LOSE!")
if computer == "P" and human == "S":
print("The computer chose PAPER, you WIN!")
if computer == "P" and human == "R":
print("The computer chose PAPER, you LOSE!")
if computer == "S" and human == "R":
print("The computer chose SCISSORS, you WIN!")
if computer == "S" and human == "P":
print("The computer chose SCISSORS, you LOSE!")
# if both the user and the computer pick the same option, it is a draw
if computer == human:
print("Both you and the computer chose the same, it's a draw!")
# call the function
rps()
# this is just to make sure that the program doesn't close immediately when run in a proper command line (not PyCharm)
input()
|
9d84f115ed4d2d594fe408457daa21efba11225d | behrouzmadahian/python | /IntroToNumpyScipy/01-numyIntro.py | 2,289 | 4.4375 | 4 | import numpy as np
'''
numpy provides functionality to manipulate arrays and matrices!!
arrays: are similar to lists except that every element of an array must be
of the same type, typically a numeric type.
are more efficient than lists and make operations with large amount of data very fast.
'''
a = np.array([1, 2, 3, 4], float)
print(a, a[2:])
# multi-dimensional arrays:
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a, a[0, 0])
print(a[1:, :]) # second row
print(a[:, 1]) # second column
print(a[:, 1:3]) # columns 2 and 3
# array dimensions:
print(a.shape)
# type of values in an array:
print(a.dtype)
# len returns length of the first axis: number of rows!
print(len(a))
print(2 in a)
# reshaping array to have new dimensions:
a = np.array(range(10), float)
print(a)
a = a.reshape((5, 2))
print(a)
a = np.array(range(3))
print(a)
# making all elements zero:
a.fill(0)
print(a)
#######Transposing an array:
a = np.array(range(12))
a = a.reshape((3, 4))
print(a)
a = a.transpose()
print(a)
##############
# one dimensional versions of multi-dimensional array:
a= a.flatten()
print(a)
#########
# concatenating to arrays:
a = np.array([1, 1, 1])
b = np.array([2, 2, 2])
c = np.concatenate((a, b))
print(c)
# we can specify along which axis to concatenate if multidimensional
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
c = np.concatenate((a, b), 0) #rbind
print(c)
c = np.concatenate((a, b), 1)#cbind
print(c)
######################
# the dimensionality of an array can be increased using the newaxis constant in bracket notation:
print('Increasing Dimensionality of an array:')
a = np.array([1, 2, 3])
print(a, a.shape)
a=a[:, np.newaxis]
print(a, a.shape)
a=np.array([1,2,3])
a=a[np.newaxis, :]
print(a, a.shape)
#######################################
# other ways to create arrays:
# arange() is similar to range function but returns an array:
a = np.arange(10)
print(a)
# making one/multi dimension arrays of ones and zeros:
a = np.ones(10)
b = np.zeros(10)
print(a, b)
a = np.ones((2, 5))
b = np.zeros((2, 5))
print(a)
print(b)
#######
# identity matrix:
a = np.identity(4)
print(a)
# eye function returns matrices with ones along kth diagonal:
a = np.eye(4, k=1)
print(a)
|
f0461d26769e9ab5560fed08d36f28aaebdb0c29 | Teaching-projects/SOE-ProgAlap1-HF-2020-illesgabor1126 | /200/my_time.py | 1,139 | 3.84375 | 4 | class Time:
def __init__(self, seconds:int=0):
self.seconds=seconds
def to_seconds(self) -> int:
return self.seconds
def _ss(self)->int:
return self.seconds % 60
def _mm(self) -> int:
return self.seconds % 3600 // 60
def _hh(self) -> int:
return self.seconds // 3600
def pretty_format(self) -> str:
return "'{0}:{1}:{2}'".format(self._hh(), self._mm(), self._ss())
def set_from_string(self, s) -> int:
x=s.split(":",3)
l=len(x)
if l==3:
self.seconds = int (x[0])*3600 + int (x[1])*60 + int (x[2])
elif 1==2:
self.seconds = int (x[0])*60 + int (x[1])
else:
self.seconds = int (x[0])
return self.seconds
t1 = Time(3600+1234)
print(t1.to_seconds())
print(t1._ss())
print(t1._mm())
print(t1._hh())
print(t1.pretty_format())
print(t1.set_from_string("1:2:3"))
print(t1.pretty_format())
print(t1.set_from_string("2:3"))
print(t1.pretty_format())
print(t1.set_from_string("15"))
|
1edcf47cb7a60da97af4b36777c2081b6a6b4a8b | zwelisha/animals_part1 | /home.py | 1,075 | 3.703125 | 4 | from animal import Animal
from cat import Cat
from dog import Dog
class Home:
def __init__(self, pets=[]):
self.__pets = pets
# Getter for pets array
@property
def pets(self):
return self.__pets
# Setter for pets
@pets.setter
def pets(self, pets):
self.__pets = pets
def adopt_pet(self, pet):
for each in self.__pets:
if each == pet:
raise Exception ("You can't adopt the same pet twice")
self.__pets.append(pet)
'''
According to the given instruction, this function
should be named 'makeAllSounds', however, that is
not pythonic. Hence I named it 'make_all_sounds'
'''
def make_all_sounds(self):
for animal in self.__pets:
#print(type(animal))
animal.sound()
def main():
home = Home()
dog1 = Dog()
dog2 = Dog()
cat = Cat()
home.adopt_pet(dog1)
home.adopt_pet(cat)
home.adopt_pet(dog2)
home.make_all_sounds()
home.adopt_pet(dog2)
if __name__ == '__main__':
main()
|
677a6b961b5eb818678313ea5a65d9adcca293a3 | ElyseV1N/ElyseV1N | /Les05/Oefening 4.py | 201 | 3.625 | 4 | getallenrij = [2, 4, 6, 8, 10, 9, 7]
aantal3 = 0
for getal in getallenrij :
if getal % 3 == 0 :
aantal3 = aantal3 + 1
print('Het aantal getallen dat deelbaar is door 3 is: ' + str(aantal3)) |
a0dab9615bd4f1b84481496bd68badb338a54f5a | Shunderpooch/AdventOfCode2016 | /Day 4/security_through_obscurity_1.py | 1,361 | 3.640625 | 4 | """
Arthur Dooner
Advent of Code Day 4
Challenge 1
"""
import sys
SUM_SECTOR_IDS = 0
def generate_checksum(word_array):
combined_array = ''.join(word_array)
letter_count = dict((letter, combined_array.count(letter)) for letter in set(combined_array))
#this is now a list, alphabetically, of tuples
sorted_letter_count = sorted(letter_count.items())
#Now by greatest count with ties decided by alphabetical
sorted_letter_count.sort(key=lambda x: x[1], reverse=True)
checksum = ""
counter = 0
for y in sorted_letter_count[:5]: #only want the first 5 letters
checksum += y[0]
return checksum
with open("realfakerooms.txt", "r") as filestream:
LINE_LIST = []
for line in filestream:
TEMP_LINE_INPUT = line.split('-') #split everything by the '-' delim to get each word
last_piece = TEMP_LINE_INPUT.pop() #pop off the last piece (the sectorID and checksum)
# Merge the array into one character set
generated_checksum = generate_checksum(TEMP_LINE_INPUT)
# Gather the actual checksum and compare it with the generated checksum
last_piece_list = last_piece.split('[')
if generated_checksum == (last_piece_list[1][:5]):
SUM_SECTOR_IDS += int(last_piece_list[0])
print("The Sum of Valid SectorIDs are: " + str(SUM_SECTOR_IDS))
sys.stdout.flush() |
e2e8d2620adda15a1e410b24b089a6abca37e76c | malek19-meet/meet2017y1lab5 | /fun2.py | 126 | 3.6875 | 4 |
def draw_1d(n,shape):
print(shape*n)
def draw_2d(n, m, char1):
for i in range(m):
draw_1d(n,char1)
|
94871b05d2b0a87f4b90bf1be3e5e351bfebf1a8 | Iamkartikey44/Python_Project | /Dobble game.py | 925 | 3.578125 | 4 | import string
import random
symbols =[]
symbols = list(string.ascii_letters)
card1 = [0]*5
card2= [0]*5
pos1 = random.randint(0,4)
pos2 = random.randint(0,4)
samesymbol = random.choice(symbols)
symbols.remove(samesymbol)
if(pos1==pos2):
card2[pos1]=samesymbol
card1[pos1]=samesymbol
else:
card2[pos1]=samesymbol
card1[pos2]=samesymbol
card1[pos2]=random.choice(symbols)
symbols.remove(card1[pos2])
card2[pos1]=random.choice(symbols)
symbols.remove(card2[pos1])
i=0
while(i<5):
if(i!=pos1 and i!=pos2):
alphabet1 = random.choice(symbols)
symbols.remove(alphabet1)
alphabet2 = random.choice(symbols)
symbols.remove(alphabet2)
card1[i]=alphabet1
card2[i] = alphabet2
i+=1
print(card1)
print(card2)
ch = input('Spot,the similar symbol: ')
if(ch== samesymbol):
print('Right')
else:
print('Wrong') |
cd67386d64cf0a876effa7aad168c03e5443a64d | SixuLi/Leetcode-Practice | /First Session(By Tag)/Tree/272.Cloest Binary Search Tree Value II.py | 1,446 | 3.6875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Solution 1: Inorder Traversal
# Time Complexity: O(N+K)
# Space Complexity: O(N)
class Solution:
def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]:
if not root:
return []
in_order = []
self.inorder(root, in_order)
distance = float('inf')
for i in range(len(in_order)):
if distance > abs(target - in_order[i]):
distance = abs(target - in_order[i])
idx = i
res = []
left, right = idx - 1, idx + 1
for i in range(k):
res.append(in_order[idx])
if left >= 0 and right < len(in_order):
if abs(target - in_order[left]) > abs(target - in_order[right]):
idx = right
right += 1
else:
idx = left
left -= 1
elif left >= 0:
idx = left
left -= 1
elif right < len(in_order):
idx = right
right += 1
return res
def inorder(self, root, in_order):
if not root:
return
self.inorder(root.left, in_order)
in_order.append(root.val)
self.inorder(root.right, in_order)
return |
06250b28190ea2a0fc6267410482598bb5a50c3f | J14032016/LeetCode-Python | /tests/algorithms/p0017_letter_combinations_of_a_phone_number_test.py | 487 | 3.5625 | 4 | import unittest
from leetcode.algorithms\
.p0017_letter_combinations_of_a_phone_number import Solution
class TestLetterCombinationsOfAPhoneNumber(unittest.TestCase):
def test_letter_combinations_of_a_phone_number(self):
solution = Solution()
expected_lists = ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
self.assertListEqual([], solution.letterCombinations(''))
self.assertListEqual(expected_lists, solution.letterCombinations('23'))
|
94aff208434e60de103b89609fbf4d2c6ded83b4 | tnawathe21/CS50-Projects | /dna.py | 2,749 | 3.921875 | 4 | from sys import argv, exit
import csv
### LOADING DNA DATABASE (CSV FILE) INTO MEMORY ###
# file name of csv
database = argv[1]
# prepare to read heading titles and rows into a list
titles = []
people = []
peoplenum = 0 # store number of people in the database
STRnum = 0 # store number of STRs to parse
with open(database, 'r') as csvfile:
# create a csv reader
csvreader = csv.reader(csvfile)
# get heading titles
titles = next(csvreader)
# load data into rows
for row in csvreader:
people.append(row)
# store number of people in the database
peoplenum = csvreader.line_num - 1
# determine number of STRs to parse
STRnum = len(titles) - 1
### LOADING DNA SEQUENCE (TXT FILE) INTO MEMORY ###
with open(argv[2], 'r') as txtfile:
# reads txt file, which contains DNA sequence, into a string
seq = txtfile.read()
# close txt file
txtfile.close()
### FILLING STR FREQUENCY LIST ARRAY (EACH ELEMENT IN EACH LIST ROW IS STR REPEAT NUMBER AT THAT POSITION) ###
repeatsarr = [] # multidimensional array: each STR and within it, number of repeats for each position
temp = [] # 1D array to temporarily keep track of repeats for each position, soon gets transferred to repeats multiD array
count = 0 # keeps track of the number of STR repeats for each position in the DNA sequence string
seqlength = len(seq) # length of DNA sequence
for STR in titles[1:]: # leave out first element since it's just 'name'
temp.clear()
for i in range(seqlength):
count = 0
j = i
while seq[j:j+(len(STR))] == STR: # counts number of STR repeats starting from i position in the DNA sequence
count+= 1
j += len(STR)
temp.append(count) # adds that number to end of temp integer array
tobeadded = temp.copy()
repeatsarr.append(tobeadded)
### FIND LARGEST REPEAT IN EACH NUMBER ARRAY WITHIN REPEATSARR ###
largest = 0 # keeps track of largest repeat for each STR
STRarr = [] # contains the largest repeat of the STRs
for array in range(STRnum): # iterates over each array (corresponding to each STR)
largest = repeatsarr[array][0] # first number in array that is in repeatsarr
for i in repeatsarr[array]: # finds the largest element in the array
if i > largest:
largest = i
STRarr.append(largest)
### FIND PERSON IN THE DATABASE WHO IS A MATCH FOR THE GIVEN DNA SEQUENCE ###
# we need STRarr and people
matchcount = 0
for i in range(len(people)):
matchcount = 0
for j in range(1, len(people[i])): # from 1st element to last element in STRs
if int(people[i][j]) == int(STRarr[j-1]):
matchcount += 1
if matchcount == STRnum:
print(people[i][0])
exit()
print('NO MATCH') |
14ec59391ff23a488b91971416a52ee5f7f75f40 | Vodka456/Save.dat-hider-by-Vodka456-9388 | /Python starter for beginners/Course12(functions) [GETTING HARDER].py | 437 | 3.765625 | 4 | #Creating a function
def saysomething(name, age):
print ("This is something right?, " + name + "so you " + str(age) + "right?")
#Call the function.//Include a name To pass the function to
saysomething("Yourname" , 80)
def very_basic(name, age):
print ("Your name is :" + name + "Your age is " + age + "right?")
#This time you need to use "" for the age other time we used 'str(age) before it
very_basic("vSync", "23") |
11fbdff4ca5150497ba696f92bbc2336ba37ee8e | bbung24/codingStudy | /leetcode/12.py | 1,279 | 3.703125 | 4 | """
12. Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
"""
class Solution(object):
def __init__(self):
self.mapping = { 1000:'M', 900:'CM', 500:'D', 400:'CD', 100:'C',
90:'XC', 50:'L', 40:'XL', 10:'X', 9:'IX', 5:'V', 4:'IV', 1:'I'}
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return "nulla"
output = ""
for div in sorted(self.mapping.keys(), reverse=True):
multiplier = num / div
num = num % div
output += multiplier * self.mapping[div]
return output
if __name__ == "__main__":
test = Solution()
# Should print nulla
result = test.intToRoman(0)
print result
# Should print I
result = test.intToRoman(1)
print result
# Should print IV
result = test.intToRoman(4)
print result
# Should print VI
result = test.intToRoman(6)
print result
# Should print XL
result = test.intToRoman(40)
print result
# Should print CD
result = test.intToRoman(400)
print result
# Should print MMMCMXCIX
result = test.intToRoman(3999)
print result |
10d4e651b284b8cfca7200db1c2b2320f15e6203 | sandeep-045/python-training | /udemy/milestone project-1/snakewatergun.py | 1,676 | 4.03125 | 4 | from time import sleep
import random
com=["snake","water","gun"]
print("Game begins in.....")
sleep(1)
print("3 ")
sleep(1)
print("2 ")
sleep(1)
print("1",)
p_score=0
c_score=0
while(p_score!=2 and c_score!=2):
p_choice=input("Enter your choice:")
number=random.randint(0,2)
c_choice=com[number]
if p_choice==c_choice:
print("Oops It's a tie Computer chose the same")
else:
if p_choice=="snake":
if c_choice=="water":
p_score+=1
sleep(1)
print("Player Wins the round Computer chose {}".format(c_choice))
elif c_choice=="gun":
c_score+=1
sleep(1)
print("Computer Wins the round Computer chose {}".format(c_choice))
elif p_choice=="water":
if c_choice=="gun":
p_score+=1
sleep(1)
print("Player Wins the round Computer chose {}".format(c_choice))
elif c_choice=="snake":
c_score+=1
sleep(1)
print("Computer Wins the round Computer chose {}".format(c_choice))
elif p_choice=="gun":
if c_choice=="snake":
p_score+=1
sleep(1)
print("Player Wins the round Computer chose {}".format(c_choice))
elif c_choice=="water":
c_score+=1
sleep(1)
print("Computer Wins the round Computer chode {}".format(c_choice))
sleep(0.4)
print(f"Player Score:{p_score} Computer Score:{c_score}")
sleep(0.4)
if p_score==2:
print("Player wins")
else:
print("COmputer wins") |
a33868ecfbf397b81663db48c5ea0d64750dbcf1 | fiso0/MxPython | /JTT808/inputToHexText.py | 942 | 3.578125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
def num2hex(int_num, digits, hasBlank = True):
format = '%%0%dX' % digits
int_num = int(int_num)
new_text = format % int_num
if hasBlank and digits > 2:
chr_str = [new_text[i:i + 2] for i in range(0, len(new_text), 2)]
new_text = ' '.join(chr_str)
return new_text
def string2hex(string, digits, hasBlank = True, rear0 = False):
string = string.strip().replace(' ','')
str_len = len(string)
if str_len <= digits:
if rear0:
new_text = string + '0'*(digits - str_len)
else:
new_text = '0'*(digits - str_len) + string
else:
new_text = string[0:digits]
if hasBlank and digits > 2:
chr_str = [new_text[i:i + 2] for i in range(0, len(new_text), 2)]
new_text = ' '.join(chr_str)
return new_text
if __name__ == '__main__':
print(string2hex('12345', 12))
print(num2hex(114000000, 8))
print(num2hex(114000000, 8, False))
print(num2hex(1, 4))
print(num2hex(1, 4, False)) |
aa034998d17daaa536f8bec2bbaaac248d6d4f71 | Sabrina-AP/python-curso_em_video | /Exercícios/ex063.py | 262 | 3.796875 | 4 | #63 SequÊncia de Fibonacci
n=int(input('Quantos termos você quer mostrar? '))
cont=2
t1=0
t2=1
print(' 0 - 1', end=' - ')
while cont < n:
cont+=1
t=t1+t2
print(t, end= ' - ')
t1=t2
t2=t
print('FIM')
|
51273a57efeea179f02bbf67eaf019c4067099ff | Dioclesiano/Estudos_sobre_Python | /Defs/ex113/Validador/__init__.py | 671 | 3.953125 | 4 | # Testador de Inteiro e Float
def leiaInt(dado):
while True:
try:
num = int(input(dado))
except(ValueError, TypeError):
print('Comando Inválido! ', end='')
continue
except KeyboardInterrupt:
print('\nFoi ativado a opção de cancelamento.')
return 0
else:
return num
def leiaFloat(dado):
while True:
try:
num = float(input(dado))
except (ValueError, TypeError):
print('Comando Inválido! ', end='')
except KeyboardInterrupt:
print('\nEncerrando o Programa!')
else:
return num |
670e547fdfce03f2546dfa2193fac686c40cf672 | Yzoni/natuurlijke-taalmodellen-en-interfaces_2015_2016 | /partB/b1step1.py | 8,063 | 3.578125 | 4 | #!/usr/bin/env python3.5
__author__ = 'Yorick de Boer [10786015]'
"""
Binarizes a file containing trees, outputting binarized trees as strings.
############################
# (ROOT
# (S
# (NP
# (NNP Ms.)
# (NNP Haag)
# )
# (VP
# (VBZ plays)
# (NP
# (NNP Elianti)
# )
# )
# (. .)
# )
# )
###########################
# (ROOT
# (S
# (NP
# (NNP Ms.)
# (@NP->_NNP
# (NNP Haag)
# )
# )
# (@S->_NP
# (VP
# (VBZ plays)
# (@VP->_VBZ
# (NP
# (NNP Elianti)
# )
# )
# )
# (@S->_NP_VP
# (. .)
# )
# )
# )
# )
"""
import argparse
import re
import unittest
import progressbar
def parse_to_list(sentence):
"""Returns a nested list from a tree in the form of a string.
Works by splitting all elements of the string using regex and iterating over them."""
accum = []
nested_list = []
regex = re.compile(r'([^(^)\s]+|\()|(\))')
for termtypes in re.finditer(regex, sentence):
tt = termtypes.group(0).strip()
if tt == '(':
accum.append(nested_list)
nested_list = []
elif tt == ')':
tmp = nested_list
nested_list = accum[-1]
nested_list.append(tmp)
del accum[-1]
else: # A word
nested_list.append(tt)
return nested_list[0] # Remove outer list
def binarize(nested_list):
"""Binarizes a tree in the formatted as a nested list.
Works by recursively looping over all nested list elements."""
if isinstance(nested_list, list):
if len(nested_list) > 2:
if '@' in nested_list[0]:
bt = nested_list[0] + '_' + nested_list[1][0]
else:
bt = '@' + nested_list[0] + '->_' + nested_list[1][0]
nested_list[2] = [bt] + nested_list[2:]
if len(nested_list) > 3:
del nested_list[3:]
for idx, e in enumerate(nested_list):
nested_list[idx] = binarize(e)
return nested_list
def binarized_to_string(nested_list):
"""Transforms a list to a string, removing list elements"""
return str(nested_list).replace("[", "(") \
.replace(']', ')') \
.replace("')", ")") \
.replace("('", "(") \
.replace(', ', ' ') \
.replace("' ", " ") \
.replace(" '", " ") \
.replace('"', '')
class TestBStep1(unittest.TestCase):
def setUp(self):
self.maxDiff = None
self.test_string_sentences = [
'''(ROOT (S (NP (NNP Ms.) (NNP Haag)) (VP (VBZ plays) (NP (NNP Elianti))) (. .)))''',
'''(ROOT (S (NP (NNP Rolls-Royce) (NNP Motor) (NNPS Cars) (NNP Inc.)) (VP (VBD said) (SBAR (S (NP (PRP it)) (VP (VBZ expects) (S (NP (PRP$ its) (NNP U.S.) (NNS sales)) (VP (TO to) (VP (VB remain) (ADJP (JJ steady)) (PP (IN at) (NP (QP (IN about) (CD 1,200)) (NNS cars))) (PP (IN in) (NP (CD 1990)))))))))) (. .)))''',
'''(ROOT (S (NP (DT The) (NN luxury) (NN auto) (NN maker)) (NP (JJ last) (NN year)) (VP (VBD sold) (NP (CD 1,214) (NNS cars)) (PP (IN in) (NP (DT the) (NNP U.S.))))))''',
'''(ROOT (S (`` ``) (ADVP (RB Apparently)) (NP (DT the) (NN commission)) (VP (VBD did) (RB not) (ADVP (RB really)) (VP (VB believe) (PP (IN in) (NP (DT this) (NN ideal))))) (. .) ('' '')))''',
'''(ROOT (S (CC But) (NP (NP (QP (IN about) (CD 25)) (NN %)) (PP (IN of) (NP (DT the) (NNS insiders)))) (, ,) (PP (VBG according) (PP (TO to) (NP (NNP SEC) (NNS figures)))) (, ,) (VP (VBP file) (NP (PRP$ their) (NNS reports)) (ADVP (RB late))) (. .)))''',
'''(ROOT (S (ADVP (RB Already)) (, ,) (NP (DT the) (NNS consequences)) (VP (VBP are) (VP (VBG being) (VP (VBN felt) (PP (IN by) (NP (NP (NP (JJ other) (NNS players)) (PP (IN in) (NP (DT the) (JJ financial) (NNS markets)))) (: --) (JJ even) (NP (NNS governments))))))) (. .)))'''
]
self.test_bin_sentences = [
'''(ROOT (S (NP (NNP Ms.) (@NP->_NNP (NNP Haag))) (@S->_NP (VP (VBZ plays) (@VP->_VBZ (NP (NNP Elianti)))) (@S->_NP_VP (. .)))))''',
'''(ROOT (S (NP (NNP Rolls-Royce) (@NP->_NNP (NNP Motor) (@NP->_NNP_NNP (NNPS Cars) (@NP->_NNP_NNP_NNPS (NNP Inc.))))) (@S->_NP (VP (VBD said) (@VP->_VBD (SBAR (S (NP (PRP it)) (@S->_NP (VP (VBZ expects) (@VP->_VBZ (S (NP (PRP$ its) (@NP->_PRP$ (NNP U.S.) (@NP->_PRP$_NNP (NNS sales)))) (@S->_NP (VP (TO to) (@VP->_TO (VP (VB remain) (@VP->_VB (ADJP (JJ steady)) (@VP->_VB_ADJP (PP (IN at) (@PP->_IN (NP (QP (IN about) (@QP->_IN (CD 1,200))) (@NP->_QP (NNS cars))))) (@VP->_VB_ADJP_PP (PP (IN in) (@PP->_IN (NP (CD 1990))))))))))))))))))) (@S->_NP_VP (. .)))))''',
'''(ROOT (S (NP (DT The) (@NP->_DT (NN luxury) (@NP->_DT_NN (NN auto) (@NP->_DT_NN_NN (NN maker))))) (@S->_NP (NP (JJ last) (@NP->_JJ (NN year))) (@S->_NP_NP (VP (VBD sold) (@VP->_VBD (NP (CD 1,214) (@NP->_CD (NNS cars))) (@VP->_VBD_NP (PP (IN in) (@PP->_IN (NP (DT the) (@NP->_DT (NNP U.S.))))))))))))''',
'''(ROOT (S (`` ``) (@S->_`` (ADVP (RB Apparently)) (@S->_``_ADVP (NP (DT the) (@NP->_DT (NN commission))) (@S->_``_ADVP_NP (VP (VBD did) (@VP->_VBD (RB not) (@VP->_VBD_RB (ADVP (RB really)) (@VP->_VBD_RB_ADVP (VP (VB believe) (@VP->_VB (PP (IN in) (@PP->_IN (NP (DT this) (@NP->_DT (NN ideal))))))))))) (@S->_``_ADVP_NP_VP (. .) (@S->_``_ADVP_NP_VP_. ('' ''))))))))''',
'''(ROOT (S (CC But) (@S->_CC (NP (NP (QP (IN about) (@QP->_IN (CD 25))) (@NP->_QP (NN %))) (@NP->_NP (PP (IN of) (@PP->_IN (NP (DT the) (@NP->_DT (NNS insiders))))))) (@S->_CC_NP (, ,) (@S->_CC_NP_, (PP (VBG according) (@PP->_VBG (PP (TO to) (@PP->_TO (NP (NNP SEC) (@NP->_NNP (NNS figures))))))) (@S->_CC_NP_,_PP (, ,) (@S->_CC_NP_,_PP_, (VP (VBP file) (@VP->_VBP (NP (PRP$ their) (@NP->_PRP$ (NNS reports))) (@VP->_VBP_NP (ADVP (RB late))))) (@S->_CC_NP_,_PP_,_VP (. .)))))))))''',
'''(ROOT (S (ADVP (RB Already)) (@S->_ADVP (, ,) (@S->_ADVP_, (NP (DT the) (@NP->_DT (NNS consequences))) (@S->_ADVP_,_NP (VP (VBP are) (@VP->_VBP (VP (VBG being) (@VP->_VBG (VP (VBN felt) (@VP->_VBN (PP (IN by) (@PP->_IN (NP (NP (NP (JJ other) (@NP->_JJ (NNS players))) (@NP->_NP (PP (IN in) (@PP->_IN (NP (DT the) (@NP->_DT (JJ financial) (@NP->_DT_JJ (NNS markets)))))))) (@NP->_NP (: --) (@NP->_NP_: (JJ even) (@NP->_NP_:_JJ (NP (NNS governments)))))))))))))) (@S->_ADVP_,_NP_VP (. .)))))))'''
]
def test_binarize(self):
for test_string_sentence, test_bin_sentence in zip(self.test_string_sentences, self.test_bin_sentences):
parsed = parse_to_list(test_string_sentence)
binarized_list = binarize(parsed)
self.assertEqual(binarized_to_string(binarized_list), test_bin_sentence)
def binarize_to_file(infile, outfile):
"""Reads all lines form a file, binarizes them, and writes the binarized tree to a new file"""
f_out = open(outfile, 'w')
num_lines = sum(1 for _ in open(infile))
count = 0
pbar = progressbar.ProgressBar(widgets=[progressbar.Percentage(), progressbar.Bar()], maxval=num_lines).start()
print('Binarizing...')
with open(infile, 'r') as f_in:
for line in f_in:
count += 1
pbar.update(count)
if line == '\n':
f_out.write('\n')
else:
binarized_line = binarized_to_string(binarize(parse_to_list(line)))
f_out.write(binarized_line + '\n')
print('Done.')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-infile', type=str, help='Path to file containing S-Expressions')
parser.add_argument('-outfile', type=str, help='Path to where tot save binary S-Expressions')
args = parser.parse_args()
if not args.infile and not args.outfile:
unittest.main()
else:
binarize_to_file(args.infile, args.outfile)
|
e2fa0fe69f66582657600a48cc0ad7d78a9c2b82 | KarenWest/pythonClassProjects | /problem_set_6_problem_11.py | 1,492 | 3.75 | 4 | def makeTrigger(triggerMap, triggerType, params, name):
"""
Takes in a map of names to trigger instance, the type of trigger to make,
and the list of parameters to the constructor, and adds a new trigger
to the trigger map dictionary.
triggerMap: dictionary with names as keys (strings) and triggers as values
triggerType: string indicating the type of trigger to make (ex: "TITLE")
params: list of strings with the inputs to the trigger constructor (ex: ["world"])
name: a string representing the name of the new trigger (ex: "t1")
Modifies triggerMap, adding a new key-value pair for this trigger.
Returns: None
"""
def word_param():
return params
def trigger_param():
return [triggerMap[p] for p in params]
def phrase_param():
return [' '.join(params)]
trigger_types = {
'TITLE': (TitleTrigger, word_param),
'SUBJECT': (SubjectTrigger, word_param),
'SUMMARY': (SummaryTrigger, word_param),
'NOT': (NotTrigger, trigger_param),
'AND': (AndTrigger, trigger_param),
'OR': (OrTrigger, trigger_param),
'PHRASE': (PhraseTrigger, phrase_param)
}
params = trigger_types[triggerType][1]()
triggerMap[name] = trigger_types[triggerType][0](*params)
return triggerMap[name] |
d7fac6593729fb0b9a6e24c8b5437bd10ae48afc | AntonyHockin/cp1404practicals | /prac_01/electricity_bill.py | 532 | 4 | 4 | # TARIFF_11 = 0.244618
# TARIFF_31 = 0.136928
# cents_per_kwh = 0
#
# print("Electricity bill estimator 2.0")
# # cents_per_kwh = float(input("Enter cents per kWh: "))
# tariff = int(input("Which Tariff? 11 or 31: "))
# if tariff == 11:
# cents_per_kwh = TARIFF_11
# elif tariff == 31:
# cents_per_kwh = TARIFF_31
# daily_kwh = float(input("Enter daily use in kWh: "))
# billing_days = float(input("Enter number of billing days: "))
# bill = cents_per_kwh * daily_kwh * billing_days
# print(f"Estimated bill: ${bill:.2f}")
|
14ac8526b71460de6f0590a9388c1934f74457e2 | raghuxpert/Array7Boom | /question13.py | 469 | 4.125 | 4 | #Write a program that accepts a sentence and calculate the number of letters and digits.
#Suppose the following input is supplied to the program:
#hello world! 123
#Then, the output should be:
#LETTERS 10
#DIGITS 3
line = input("insert some text : ")
d = {"letters":0, "numbers":0}
for i in line:
if i.isalpha():
d["letters"]+=1
if i.isnumeric():
d["numbers"]+=1
print("Total Letters : ", d["letters"])
print("Total numbers : ", d["numbers"]) |
813858dbd7e340606b6b91754efdf1a17fa9c6dc | KerimUlusoy/Algoritma_Analizi | /week_08/bst_methods_2.py | 2,238 | 3.875 | 4 | import math
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
self.depth = 0
def __str__(self):
return "val : " + str(self.val) + "depth : " + str(self.depth)
#Insertion
def insert(root, node):
if root is None:
root = node
else:
node.depth += 1
if root.val < node.val:
if root.right is None:
root.right = node
else:
insert(root.right, node)
else:
if root.left is None:
root.left = node
else:
insert(root.left, node)
#Search
def search(root, key):
if root is None or root.val == key:
return root
if root.val < key:
return search(root.right, key)
return search(root.left, key)
#Min Value Node
def minValueNode(node):
current = node
while(current.left is not None):
current = current.left
return current
#Delete
def deleteNode(root, val):
if root is None:
return root
if val < root.val:
root.left = deleteNode(root.left, val)
elif(val > root.val):
root.right = deleteNode(root.right, val)
else:
if root.left is None:
temp = root.right
root = None
return temp
elif root.right is None:
temp = root.left
root = None
return temp
temp = minValueNode(root.right)
root.val = temp.val
root.right = deleteNode(root.right, temp.val)
return root
#Printing
SumOfDepth = 0
NumOfNodes = 0
def inorder(root):
if root:
inorder(root.left)
print(root.val, root.depth, end = " -- ")
global SumOfDepth
global NumOfNodes
NumOfNodes += 1
SumOfDepth += root.depth
inorder(root.right)
#Testing
r = Node(50)
insert(r, Node(30))
insert(r, Node(20))
insert(r, Node(40))
insert(r, Node(70))
insert(r, Node(60))
insert(r, Node(80))
inorder(r)
print("\n")
print("Toplam Derinlik:", SumOfDepth, ", Toplam Düğüm:", NumOfNodes)
print("Ortalama Derinlik:", SumOfDepth/NumOfNodes, math.log(NumOfNodes))
print("\n")
#deleteNode(r, 20)
#inorder(r)
|
d632477e4b779bc221874c205985af213f598553 | tindinhct93/leetcode | /20200704 ugly.py | 799 | 3.578125 | 4 | def nthUglyNumber(n):
def update_list(pop_list, num, number):
for i in range(0, len(pop_list)):
if pop_list[i] > int(number / num):
break
else:
pop_list.pop(0)
list = [1, 2, 3, 4, 5, 6, 8, 9, 10]
list_2 = [6, 8, 9, 10]
list_3 = [4, 5, 6, 8, 9, 10]
list_5 = [3, 4, 5, 6, 8, 9, 10]
def ugly():
list_t = [list_2[0] * 2, list_3[0] * 3, list_5[0] * 5]
number = min(list_t)
list.append(number)
list_2.append(number)
list_3.append(number)
list_5.append(number)
update_list(list_2, 2, number)
update_list(list_3, 3, number)
update_list(list_5, 5, number)
while len(list) < n:
ugly()
return list[n - 1]
print(nthUglyNumber(250)) |
99236da33dd16a3ab93a383ea0789c266053447d | cphomoyo/python_assignment | /question2.py | 180 | 4 | 4 | #the program outputs the first 3 and last 3 bases of the input sequence
s=raw_input("enter sequence: ")
if len(s)<6:
print 'error'
elif len(s)>=6:
s= s[:3] + s[-3:]
print s
|
400e0381f2c74ce50d7835d7a655d8a72ef1afda | BramCoucke/5WWIPython | /06-condities/FIBA ranking.py | 860 | 3.5 | 4 | #invoer
score_thuisploeg = float(input('geef score thuisploeg:'))
score_uitploeg = float(input('geef score uitploeg:'))
if score_thuisploeg >= 20 + score_uitploeg:
uitvoer1 = ('thuisploeg: 730.00')
uitvoer2 = ('uitploeg: 270.00')
elif score_thuisploeg >= 10 + score_uitploeg:
uitvoer1 = ('thuisploeg: 630.00')
uitvoer2 = ('uitploeg: 370.00')
elif score_thuisploeg > score_uitploeg:
uitvoer1 = ('thuisploeg: 530.00')
uitvoer2 = ('uitploeg: 470.00')
elif score_thuisploeg + 20 <= score_uitploeg:
uitvoer1 = ('thuisploeg: 130.00')
uitvoer2 = ('uitploeg: 870.00')
elif score_thuisploeg + 10 <= score_uitploeg:
uitvoer1 = ('thuisploeg: 230.00')
uitvoer2 = ('uitploeg: 770.00')
elif score_thuisploeg < score_uitploeg:
uitvoer1 = ('thuisploeg: 330.00')
uitvoer2 = ('uitploeg: 670.00')
print(uitvoer1)
print(uitvoer2)
|
7b5f852a8c7ad9fe48361b34afd6df7fac782ab1 | DavinderSohal/Python | /Activities/Assignment_1/A1Metro.py | 16,303 | 4.375 | 4 | # -----------------------------------------------------
# A1 Metro
# Written by: Davinder Singh (2092836) and Navneet Kaur (2092453)
# This program will controls metro trains and keep track of stations and who gets on and off
# For this program we used constructor, accessor and mutator methods. This will tell the current location of the
# metro along with other details like number of passengers it's carrying, passengers getting off and boarding etc.
# -----------------------------------------------------
import random
def welcome():
"""this function will take input from user for number of stations, their names and the direction"""
print("Welcome to Metro Manager - Enjoy your metro experience")
print("------------------------------------------------------\n")
no_of_stations = int(input("Enter number of metro stations (minimum 3): "))
while no_of_stations < 3:
print("Invalid Input\n")
no_of_stations = int(input("Enter number of metro stations (minimum 3): "))
print(f"This Metro line has {no_of_stations} stations.\n")
choose_direction = input("Choose the direction."
"\n\tType (NS or ns) for 'North-South'"
"\n\tType (NE or ne) for 'North-East'"
"\n\tTYPE (NW or nw) for 'North-West'"
"\n\tType (SE or se) for 'South-East'"
"\n\tType (SW or sw) for 'South-West'"
"\n\tType anything else 'East-West'"
"\nEnter your choice here: ")
print()
name_of_stations = {}
for i in range(no_of_stations):
name_of_stations[i + 1] = (input(f"Enter name of station {i + 1}: "))
return no_of_stations, name_of_stations, choose_direction
def compare(metro_id1, metro_id2, current_station1, current_station2, next_station1, next_station2, pass_total1,
pass_total2, direction1, direction2, count_metro1, count_metro2):
"""This function will return a table comparing different aspects of two trains"""
print("\nCOMPARISON TABLE:\n")
print(f"|-------------------------|---------------------|---------------------|"
f"\n| Metro ID | Metro {str(metro_id1).zfill(3)} | Metro "
f"{str(metro_id2).zfill(3)} |"
f"\n|-------------------------|---------------------|---------------------|"
f"\n| Current Station | Station No. {str(current_station1).zfill(2)} | Station No. "
f"{str(current_station2).zfill(2)} |"
f"\n|-------------------------|---------------------|---------------------|"
f"\n| Next Station | Station No. {str(next_station1).zfill(2)} | Station No. "
f"{str(next_station2).zfill(2)} |"
f"\n|-------------------------|---------------------|---------------------|"
f"\n| Passengers Aboard | {str(pass_total1).zfill(3)} | "
f"{str(pass_total2).zfill(3)} |"
f"\n|-------------------------|---------------------|---------------------|"
f"\n| Direction | {direction1} | {direction2} |"
f"\n|-------------------------|---------------------|---------------------|"
f"\n| # of stations travelled | {str(count_metro1).zfill(2)} | "
f"{str(count_metro2).zfill(2)} |"
f"\n|-------------------------|---------------------|---------------------|")
class A1Metro:
def __init__(self, metro_id = 1001):
"""created a constructor to initialize the values"""
if metro_id == 1001:
self.metro_id = random.randrange(1, 1000)
else:
self.metro_id = metro_id
self.station_num = 0
self.direction = 0
self.pass_total = 0
def get_metro_id(self):
"""Accessor method of metroID attribute."""
return self.metro_id
def get_station_num(self):
"""Accessor method of stationNum attribute."""
return self.station_num
def get_direction(self, u_direction):
"""Accessor method of direction attribute."""
if u_direction == "ns":
directions = ["North", "South"]
elif u_direction == "ne":
directions = ["North", "East "]
elif u_direction == "nw":
directions = ["North", "West "]
elif u_direction == "se":
directions = ["South", "East "]
elif u_direction == "sw":
directions = ["South", "West "]
else:
directions = ["East ", "West "]
return directions[self.direction]
def get_pass_total(self):
"""Accessor method of passTotal attribute."""
return self.pass_total
def set_metro_id(self, metro_id):
"""Mutator method of metroID attribute."""
self.metro_id = metro_id
def set_station_num(self, station_num):
"""Mutator method of stationNum attribute."""
self.station_num = station_num
def set_direction(self, direction):
"""Mutator method of direction attribute."""
self.direction = direction
def set_pass_total(self, pass_total):
"""Mutator method of passTotal attribute."""
self.pass_total = pass_total
def change_station(self, total_station):
"""this method will be called when station # and direction of metro is to be changed"""
# using global to access variable from outer scope
global temp1
global temp2
global train_number
if train_number == 1:
temp = temp1
else:
temp = temp2
# when train reaches at its final station, its direction will change
if self.station_num == total_station and self.direction == 0:
self.direction = 1
elif self.station_num == 1 and self.direction == 1:
self.direction = 0
if self.direction == 0:
# using temp so that when train reach its final station, then only direction will change and the station
# number will remain same
if temp == 1 and self.station_num == 1:
temp = 0
else:
self.station_num += 1 # if not final station station number will increment
else:
# this code block is for train tracing back its path to reach the starting station, so this time, station
# number will decrement
if temp == 0 and self.station_num == total_station:
temp = 1
else:
self.station_num -= 1
# after every call to this method, train number will change
if train_number == 1:
temp1 = temp
train_number = 2
else:
temp2 = temp
train_number = 1
def next_station(self, last_station):
"""This method will tell the station number towards which the train will be moving next"""
# if train at its final destination, then train will not be going anywhere but only change its direction
if (last_station == 1 and self.direction == 1) or (last_station == station_total and self.direction == 0):
next_station = last_station
elif self.direction == 0 and last_station < station_total:
next_station = last_station + 1
else:
next_station = last_station - 1
return next_station
def passengers(self):
"""this method will tell # of arriving passengers(generated randomly) and the passengers that got on board and
those who are left behind"""
# accessing the last_time dictionary to get the # of passengers that were left behind by the last train
waiting_passengers = last_time.get(str(self.direction) + '-' + str(self.station_num), 0)
new_passengers = 0
pass_getting_off = 0
pass_getting_on = 0
metro_capacity = 250
# if arriving passengers are more than the available seats, then some of them will be left behind to board
# next train
if (self.station_num == 1 and self.direction == 0) or (
self.station_num == station_total and self.direction == 1):
# if train at its starting station there will be no passengers aboard, so, no passenger will be leaving the
# train but only new ones will be arriving
new_passengers = random.randrange(0, 300)
if new_passengers <= metro_capacity:
waiting_passengers = 0
pass_getting_on = new_passengers
self.pass_total = new_passengers
else:
waiting_passengers = new_passengers - metro_capacity
pass_getting_on = metro_capacity
self.pass_total = pass_getting_on
elif (self.station_num == station_total and self.direction == 0) or (
self.station_num == 1 and self.direction == 1):
# when train is at its final station all the passengers will get off.
pass_getting_off = self.pass_total
self.pass_total = 0
waiting_passengers = 0
else:
# for any other station than first and last one, this statement will be executed
new_passengers = random.randrange(0, 300)
pass_getting_off = random.randrange(0, self.pass_total)
self.pass_total -= pass_getting_off
available_seats = metro_capacity - self.pass_total
if new_passengers + waiting_passengers <= available_seats:
waiting_passengers = 0
pass_getting_on = new_passengers + waiting_passengers
self.pass_total += pass_getting_on
else:
waiting_passengers = (new_passengers + waiting_passengers) - available_seats
pass_getting_on = available_seats
self.pass_total = metro_capacity
return waiting_passengers, new_passengers, pass_getting_on, pass_getting_off
def display(self, s_total, user_direction):
"""this method will print the details about the metro"""
if user_direction == "ns":
directions = ["north", "south"]
elif user_direction == "ne":
directions = ["north", " east"]
elif user_direction == "nw":
directions = ["north", " west"]
elif user_direction == "se":
directions = ["south", " east"]
elif user_direction == "sw":
directions = ["south", " west"]
else:
directions = [" east", " west"]
print("|##########################################################################|")
# calling change_station method to change station number and the direction of train when necessary
self.change_station(s_total)
# calling passengers method to know the # of passengers on board, waiting and getting off.
waiting_passengers, new_passengers, pass_getting_on, pass_getting_off = self.passengers()
print("| |")
print(
f"| Metro {str(self.metro_id).zfill(3)} at Station number {str(self.station_num).zfill(2)} "
f" |"
f"\n| (New passengers waiting {str(new_passengers).zfill(3)}) |"
f"\n| (Passengers left from last time "
f"{str(last_time.get(str(self.direction) + '-' + str(self.station_num), 0)).zfill(3)}) "
f" |")
print("|--------------------------------------------------------------------------|")
if train_number == 2:
# we will not be keeping record of the passengers that are left behind by the second train and assigning
# its value to zero
last_time[str(self.direction) + "-" + str(self.station_num)] = 0
else:
last_time[str(self.direction) + "-" + str(self.station_num)] = waiting_passengers
print(
f"| Metro {str(self.metro_id).zfill(3)} leaving station no. {str(self.station_num).zfill(2)} "
f"{directions[self.direction]} bound with {str(self.pass_total).zfill(3)} passenger(s). |"
f"\n|\t Passenger(s) got off: {str(pass_getting_off).zfill(3)} "
f" |"
f"\n|\t Passenger(s) new passengers waiting to board: {str(new_passengers).zfill(3)} |"
f"\n|\t Passenger(s) got on: {str(pass_getting_on).zfill(3)} |"
f"\n|\t Passenger(s) left behind waiting for next train: {str(waiting_passengers).zfill(3)} "
f" |")
print("| |")
print("|##########################################################################|")
# calling welcome function
station_total, station_name, required_direction = welcome()
# creating class objects and constructor is automatically called when object is created
train1 = A1Metro()
train2 = A1Metro()
print(f"\n ==> You will be following two metros with metro id {str(train1.metro_id)} and {str(train2.metro_id)}."
f"\n ==> Both metros will be moving in same direction and metro {str(train2.metro_id)} will be following metro "
f"{str(train1.metro_id)}."
f"\n ==> When you quit, you will see the comparison table for both trains.\n")
want_to_continue = True # want_to_continue is being used to create a loop until its value is 'false'
start_second = False
temp1 = 0 # temp 1 and temp 2 are temporary variables that are being used to help change the direction of metros
temp2 = 0
train_number = 1 # train_number tell which train is being looked at
last_time = {} # this will store the passengers left from last train
count_train1 = 0 # count_train will be used to store the number of stations the metro has passed
count_train2 = 0
while want_to_continue:
if not start_second:
# this block of code will run only once when train 1 is at station 1 and train 2 has not been started yet
train1.display(station_total, required_direction.lower())
print("\nName of station number {:02d} ==> {}".format(train1.station_num, station_name[train1.station_num]))
count_train1 += 1
start_second = True # once the train 1 leave station 1, second train will start
else:
# making call to display method using objects that we created
train1.display(station_total, required_direction.lower())
count_train1 += 1
train2.display(station_total, required_direction.lower())
count_train2 += 1
print("\nName of station number {:02d} ==> {}".format(train1.station_num, station_name[train1.station_num]))
print("Name of station number {:02d} ==> {}".format(train2.station_num, station_name[train2.station_num]))
print("\n-------------------------------------------------------------------------------")
choice = input(
f'Do you want to continue following Metro train {str(train1.metro_id)} and {str(train2.metro_id)}?'
f'\nType "n" or "N" for no, anything else for yes: ')
print()
if choice.lower() == "n":
want_to_continue = False
else:
next_stn1 = train1.next_station(train1.get_station_num()) # to get the next station number
next_stn2 = train2.next_station(train2.get_station_num())
# compare will print a table
compare(train1.get_metro_id(), train2.get_metro_id(), train1.get_station_num(), train2.get_station_num(), next_stn1,
next_stn2, train1.pass_total, train2.pass_total, train1.get_direction(required_direction),
train2.get_direction(required_direction), count_train1, count_train2)
print(f"\n\n*********************************************\n"
f"\n----[Thank you for using Metro Manager]----"
f"\nBe sure to look out for future enhancements!"
f"\n\n\t\t\t\t\( ・_・)")
exit() # terminate the program
# last updated on April 15,2021
|
df50d527096666be9be6fb9915968f5eae3760f8 | lawrencetheabhorrence/Data-Analysis-2020 | /hy-data-analysis-with-python-2020/part01-e19_sum_equation/src/sum_equation.py | 341 | 3.734375 | 4 | #!/usr/bin/env python3
from functools import reduce
def sum_equation(L):
if len(L) == 0: return "0 = 0"
sum = reduce(lambda x, y: x + y, L, 0)
showSum = reduce(lambda x, y: "{} + {}".format(x, y), L)
return "{} = {}".format(showSum, sum)
def main():
print(sum_equation([1,5,7]))
if __name__ == "__main__":
main()
|
104744d8047005dbaa1bcc05b2dd496e4ead6d9d | viiniciuspaes/Estrutura-de-Dados | /encadeamento/Lista(Usar Apenas como Referencia).py | 3,135 | 3.90625 | 4 | class Node:
def __init__(self, data):
"""Construtor do Nodo"""
self.data = data
self.nextNode = None
def getData(self):
"Retorna o Dado armazenado no nodo"
return self.data
def setData(self, data):
"Atribui chave ao Dado do nodo"
self.data = data
def getNextNode(self):
"Retorna a referencia do proximo nodo"
return self.nextNode
def setNextNode(self, newNode):
"Ajusta a referencia do proximo nodo"
self.nextNode = newNode;
class List:
"""Classe para uma Lista Encadeada:
Esta classe tem dois ponteiros:
firstNode: aponta para o primeiro nodo da lista
lastNode: aponta para o ultimo nodo da lista
Ao iniciar a lista ambos os ponteiros apontam para NULO"""
def __init__(self):
"Construtor da Lista"
self.firstNode = None
self.lastNode = None
def __str__(self):
"Override do Estatuto STRING"
if self.isEmpty():
return "A lista esta vazia!"
correntNode = self.firstNode
string = "A lista eh:"
while correntNode is not None:
string += str(correntNode.getData()) + " "
correntNode = correntNode.getNextNode()
return string
def insertAtBegin(self, value):
"Insere elemento no Inicio da lista"
newNode = Node(value) # instancia de um novo nodo
if self.isEmpty(): # Insersao para Lista vazia
self.firstNode = self.lastNode = newNode
else: # Insersao para lista nao vazia
newNode.setNextNode(self.firstNode)
self.firstNode = newNode
def insertAtEnd(self, value):
"Insere emento no inicio da lista"
newNode = Node(value) # instancia de um novo nodo
if self.isEmpty(): # Se a lista esta vazia
self.firstNode = self.lastNode = newNode
else:
self.lastNode.setNextNode(newNode)
self.lastNode = newNode
def removeFromBegin(self):
"Remove o nodo inicial da lista"
if self.isEmpty():
return IndexError, "Remossao de uma Lista Vazia"
firstNodeValue = self.firstNode.getData()
if self.firstNode is self.lastNode:
self.firstNode = self.lastNode = None
else:
self.firstNode = self.firstNode.getNextNode()
return firstNodeValue
def removeFromEnd(self):
"Remove o ultimo nodo da lista"
if self.isEmpty():
return IndexError, "Remocao de lista vazia!"
lastNodeValue = self.lastNode.getData()
if self.firstNode is self.lastNode:
self.firstNode = self.lastNode = None
else:
currentNode = self.firstNode
while currentNode.getNextNode() is not self.lastNode:
currentNode = currentNode.getNextNode()
currentNode.setNextNode(None)
self.lastNode = currentNode
return lastNodeValue
def isEmpty(self):
"A lista esta vazia? True or False"
return self.firstNode is None
|
9a480e523beec234ded24236fefdbeb6e8a1c5e2 | RahmadBasri/labpy03 | /latihan2.py | 238 | 3.890625 | 4 | #MENENTUKAN BILANGAN TERBESAR
#0 UNTUK BERHENTI
MAXIMUM = 0
B = 1
while B !=0:
B = int(input("Masukkan bilangan = "))
if B > MAXIMUM:
MAXIMUM = B
if B == 0:
break
print("Bilangan terbesar adalah:", MAXIMUM)
|
48c5bc726694c5817824079326c729ab2a6383c1 | vinniwei/stanford-machine-learning-course | /machine-learning-ex1/ex1-py/ex1.py | 444 | 3.578125 | 4 | __author__ = 'Vincent Wei'
import numpy as np
import matplotlib.pyplot as plt
A = np.identity(5)
# Load data from ex1data1
data = np.loadtxt('ex1data1.txt', delimiter=',')
# visualise the data
x = data[:,0] # Populations
y = data[:,1] # Profits
plt.scatter(x, y, c='red', marker='x')
plt.xlabel('Population of City in 10,000s')
plt.ylabel('Profit in $10,000s')
plt.show()
# implementing linear regression
m, n = np.shape(x);
print(m,n)
X = []
|
8ac2043da5c43d6fb96c8bcacb49c3cf5f0e093d | PandaWSH/PythonPractices | /linkedlist_nToTheLast.py | 663 | 3.875 | 4 | # --------------------
# Linked List Reversal
# --------------------
# Logistic I:
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
def nth(n, head):
# initialize
leftpoint = head
rightpoint = head
for i in range(n-1):
# edge case
if not rightpoint.next:
raise LookupError("edge case")
# if not edge case
rightpoint = rightpoint.next
# after moved n noded from the head, and there's still value
while rightpoint.next:
# keep n nodes section, move 2 pointers together
# stop when the right pointer hits the ending edge
leftpoint = leftpoint.next
rightpoint = rightpoint.next
return leftpoint
|
1717aa87fefccecf9563e3220f5ff5cdb37b34e4 | isabela-dominguez/practice | /checkPermutation.py | 313 | 3.921875 | 4 | def checkPermutation(word1, word2):
if((len(word1) != len(word2))):
return False
word1 = ''.join(sorted(word1))
word2 = ''.join(sorted(word2))
#if(word1 == word2):
# return True
#else:
# return False
return word1 == word2
print(checkPermutation("aabb", "bbab")) |
1ba9744d5734a290a9a0de3a8d2f9a09265814ae | valeriesantiago26/Body-Composition-App | /src/bodycomposition/bmicalculator/helperfunctions.py | 2,178 | 3.5625 | 4 |
def inchesToCentimeters(feet, inches):
totalInches = feet*12 + inches
centimeters_per_inch = 2.54
return totalInches*centimeters_per_inch
def feetsFromCentimeters(centimeters):
inches = centimeters / 2.54
return inches // 12
def inchesFromCentimeters(centimeters):
inches = centimeters / 2.54
feets = feetsFromCentimeters(centimeters)
return feets - (inches / 12)
def ComputeBMI(weight, height):
return (weight/height*height)
def ComputeJP3Point(gender, first, second, third, age):
if(gender == "male"):
x = first + second + third
return 1.10938 - (0.0008267*x) + (0.0000016*x*x) - (0.0002574*age)
else:
return 1.0994921 - (0.0009929*x) + (0.0000023*x*x) - (0.0001392*age)
def ComputeJP7Point(gender, first, second, third, fourth, fifth, sixth, seventh, age):
if(gender == "male"):
x = first + second + third + fourth + fifth + sixth + seventh
return 1.112 - (0.00043499*x) + (0.00000055*x*x) - (0.00028826*age)
else:
return 1.097 - (0.00046971*x) + (0.00000056*x*x) - (0.00012828*age)
def ComputeBodyFatPercentage(bodyDensity):
return (4.95/bodyDensity) - 4.50
def ComputeFatMass(fatPercentage, weight):
return fatPercentage*weight
def ComputeLeanMass(fatMass, weight):
return weight - fatMass
# Once you calculate your BMR factor in activity to account for calories burned during exercise.
# BMR x 1.2 for low intensity activities and leisure activities (primarily sedentary)
# BMR x 1.375 for light exercise (leisurely walking for 30-50 minutes 3-4 days/week, golfing, house chores)
# BMR x 1.55 for moderate exercise 3-5 days per week (60-70% MHR for 30-60 minutes/session)
# BMR x 1.725 for active individuals (exercising 6-7 days/week at moderate to high intensity (70-85% MHR) for 45-60 minutes/session)
# BMR x 1.9 for the extremely active individuals (engaged in heavy/intense exercise like heavy manual labor, heavy lifting, endurance athletes, and competitive team sports athletes 6-7 days/week for 90 + minutes/session)
def ComputeCalorieRequirement(activityLevel, leanMass):
activityLevelCoefficients = { 0: 1.2, 1: 1.375, 2: 1.55, 3: 1.725, 4: 1.9 }
c = choices.get(key, activityLevel)
return 13.8*leanMass*c |
91d40ac266fa24f09c528f3ce76a15b79359bc1b | chantera/nlp100 | /chapter01/n07.py | 451 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
07. テンプレートによる文生成
引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ.さらに,x=12, y="気温", z=22.4として,実行結果を確認せよ.
"""
from string import Template
def weather(x, y, z):
s = Template('$x時の$yは$z')
return s.substitute(x=str(x), y=str(y), z=str(z))
print(weather(12, "気温", 22.4))
|
bf42119dd8c1721c8adf375c8486b06daff9bcb2 | NoisyBoyII/Algorithm | /DataStructure/Stacks/Stack.py | 1,088 | 3.953125 | 4 | """
Stack is a abstract data type in which elements push at the end and pop at first basically it follows
the "last in first out" policy .
"""
class Stack:
def __init__(self,limit=10):
self.stack = []
self.limit = limit
def __str__(self):
return str(self.stack)
# we will push the element at the end of the stack
def push(self,data):
if len(self.stack) >= self.limit:
print "OverFlow"
return
self.stack.append(data)
# we will pop the last inserted element in stack
def pop(self):
if len(self.stack) == 0:
print "UnderFlow"
return
self.stack.pop()
# By this we can get the top most element in stack
def peek(self):
return self.stack[-1]
def isEmpty(self):
return not bool(self.stack)
if __name__ == "__main__":
s = Stack()
for i in range(1,10):
s.push(i)
print str(s)
s.pop()
print str(s)
s.pop()
print str(s)
s.pop()
print str(s)
print s.peek()
print s.isEmpty()
|
55ecd57c313ad75dfc22322ee9d4bf4f1fd5ad79 | MyodsOnline/diver.vlz-python_basis | /Lesson_1/task_3.py | 348 | 4.15625 | 4 | """урок 1 задание 3
Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. Например, пользователь ввёл число 3.
Считаем 3 + 33 + 333 = 369.
"""
n = input('Введите цифру: ')
print(f'{n} + {n*2} + {n*3} = {int(n) + int(n*2) + int(n*3)}') |
f5972f847685918e167e914ade7e6de61ee91bff | aigerimka/project_4 | /project4.py | 1,337 | 3.921875 | 4 | lst_letters = ['а', 'у', 'о', 'ы', 'и', 'э', 'я', 'ю', 'ё', 'е', 'А', 'У', 'О', 'Ы', 'И', 'Э', 'Я', 'Ю', 'Ё', 'Е']
const_letters = ['с', 'б', 'з', 'ф', 'к']
while 1:
text = input('Введите текст(0 = выход, 1 = обратный перевод)):')
if text == '0':
break
elif text == '1':
text = input('Введите текст для обратного перевода:')
while 1:
letter = input('Введите согласную (с/б/з/ф/к):')
if letter in const_letters:
for char in lst_letters:
text = text.replace(char+letter+char.lower(), char)
print(text)
print('')
break
else:
print('Введите букву из списка!')
continue
else:
while 1:
letter = input('Выберите согласную (с/б/з/ф/к):')
if letter in const_letters:
for char in lst_letters:
text = text.replace(char, char+letter+char.lower())
print(text)
print('')
break
else:
print('Введите букву из списка!')
continue
|
c0492305470627d50a0142e7954953f210759afc | samrheault/Genetic-Algorithm-independent-study | /functions/mutation.py | 840 | 3.96875 | 4 | import random
def main():
individual = [1,2,3,4,5,6]
print(mutate(individual))
def mutate(individual):
before=[]
after=[]
result=[]
L1 = random.randint(1,5);
L2 = random.randint(1,5);
while ( L1 == L2 ):
L1 = random.randint(1,5);
L2 = random.randint(1,5);
if (L1 > L2):
tmp = L2
L2 = L1
L1 = tmp;
before = individual[0:L1]
after = individual[L2:]
random.shuffle(before)
random.shuffle(after)
print("L1=", L1, "L2=",L2)
print("before:", before, "after:", after)
for i in range(len(before)):
result.append(before[i])
for i in range(L1, L2):
result.append(individual[i])
for i in range(len(after)):
result.append(after[i])
return result
main()
|
2e8687363d0f875dc33c2d4b3e326bd6c5504d53 | CaMeLCa5e/ObjectOriented | /TheAquarium.py | 498 | 4.09375 | 4 | #!/usr/bin/python
class Fish:
"the things that are swimming in the bowl"
fishCount = 0
def __init__(self, FishName, FishColor):
self.FishName = FishName
self.FishColor = FishColor
Fish.fishCount += 1
def displayCount(self):
print "Total fish in the bowl - %d" % Fish.fishCount
def displayFish(self):
print "Name : ", self.name, ", Color: ", self.FishColor
Fish1 = Fish("Bubbles", "red")
Fish2 = Fish("Nemo", "green")
print Fish1
print Fish2
if __name__ == '__main__':
main() |
66179bc14c1e2960914398c130b77e8039fe1aa3 | kayartaya-vinod/2018_11_PHILIPS_PYTHON_FUNDAMENTALS | /Examples/ex15.py | 2,080 | 4.0625 | 4 | '''
ex15
member functions in a class
'''
import math
class Circle(object):
def __init__(self, radius=1.0):
self.radius = radius # assignment via property
@property
def radius(self): return self.__radius
@radius.setter
def radius(self, value):
if type(value) not in (int, float):
raise TypeError('Radius must be numeric')
if value < 0:
raise ValueError('Radius cannot be negative')
self.__radius = value
# readonly property
@property
def AREA(self):
return math.pi * self.radius * self.radius
def __str__(self):
return 'Circle [radius={}, area={}]'.format(
self.radius, self.AREA)
def __lt__(self, value):
if type(value) == Circle:
return self.radius < value.radius
elif type(value) in (int, float):
return self.radius < value
else:
raise TypeError('Invalid value for < operator')
def __add__(self, value):
if type(value) == Circle:
return Circle(self.radius + value.radius)
elif type(value) in (int, float):
return Circle(self.radius + value)
else:
raise TypeError('Invalid value for + operator')
def __iadd__(self, value):
# __i*__ functions should return self
if type(value) in (int, float):
self.radius += value
elif type(value) == Circle:
self.radius += value.radius
else:
raise TypeError('Invalid type for +=')
return self
def main():
c1 = Circle()
c2 = Circle(12.34)
c3 = Circle(1.234)
print(c1)
print(c2)
print(c3)
c2 += 5.0
print('after c2 += 5.0, c2 is', c2)
c2 += c3
print('after c2 += c3, c2 is', c2)
print('c2 < c3 is', c2 < c3)
print('c2 < 15.0 is', c2 < 15.0)
c4 = c2 + c3 # c4 is a new Circle object with radius added from both c2 and c3
print(c4)
c5 = c2 + 5.0 # c5 is a new Circle object with c2.radius + 5.0
print(c5)
if __name__ == "__main__": main() |
793972f28600758a5feb3103809f7617a623738c | jhs851/algorithm | /sparta/week_3/11_get_absent_student.py | 805 | 3.59375 | 4 | all_students = ["나연", "정연", "모모", "사나", "지효", "미나", "다현", "채영", "쯔위"]
present_students = ["정연", "모모", "채영", "쯔위", "사나", "나연", "미나", "다현"]
# 내꺼
# 시간복잡도 O(N)
# def get_absent_student(all_array, present_array):
# present_array = set(present_array)
#
# for student in all_array:
# if student not in present_array:
# return student
# 답안
# 시간복잡도 O(N)
# 공간복잡도 O(N)
def get_absent_student(all_array, present_array):
student_dict = {}
for key in all_array:
student_dict[key] = True
for key in present_array:
del student_dict[key]
for key in student_dict.keys():
return key
print(get_absent_student(all_students, present_students))
|
bba3e73e615f62f04f3cb47007296a2d5fc570a0 | alexkie007/offer | /Target Offer/24. 反转链表.py | 693 | 3.9375 | 4 | '''
输入一个链表,反转链表后,输出链表的所有元素。
'''
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if pHead == None or pHead.next == None:
return pHead
last = None
while pHead:
temp = pHead.next
pHead.next = last
last = pHead
pHead = temp
return last
a = ListNode(3)
b = ListNode(1)
c = ListNode(4)
d = ListNode(2)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
s = Solution()
g = s.ReverseList(a)
while g:
print(g.val)
g = g.next
|
703880cae86af33309d43b75f37c0c2445514511 | Platforuma/Beginner-s_Python_Codes | /9_Loops/19_For_Dictionary--country-capital.py | 500 | 4.21875 | 4 | '''
Write a Python program to map two lists into a dictionary
'''
country = ['India', 'Nepal', 'Japan', 'China', 'England']
capital = ['Delhi', 'Kathmandu', 'Tokyo', 'Beijing', 'London']
new_dic = {}
#using Dictionary Methods
print('----Dictionary Method----')
new_dic = dict(zip(country, capital))
print(new_dic)
print(' ')
#using for loop and zip
print('----For Loop and Zip----')
new_dic2 = {}
for i,j in zip(country, capital):
new_dic2[i] = j
print(new_dic2)
|
74487381a5d4cd47b176caae2fdf3bf84289bd67 | lin13k/practice | /temp.py | 729 | 3.640625 | 4 |
def search(nums, target):
start = 0
end = len(nums) - 1
while end >= start:
mid = (start + end) // 2
if nums[mid] == target:
return True
if nums[mid] < target:
start = mid + 1
if nums[mid] > target:
end = mid - 1
return False
if __name__ == '__main__':
print(search([1,1,2,2], 0))
print(search([1,2,3,4,5], 1))
print(search([1,2,3,4,5], 0))
print(search([1,2,3,4,5], 6))
print(search([1,2,3,4,5], 2))
print(search([1,2,3,4,5], 3))
print(search([1,2,3,4,5], 4))
print(search([1,2,3,4,5], 5))
print(search([1,2,3,4,5,6,7,8], 6))
print(search([1,2,3,4,5,6,7,8], 7))
print(search([1,2,3,4,5,6,7,8], 8)) |
d9fd10faff8851877ba48da2515a7bd059a5cb7c | afsanaahsan/ML-Python-Tensorflow-CNN | /1.Python-print,userinput,variable create,string, all arithmatic problem solve, concatenation.py | 402 | 3.890625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[11]:
print("Hello World!")
print(22//7)
print(22*7)
print("afsana"+" ahsan")
a="roman"
b=619
print(a+str(b)) #python don't add different type data together
# In[12]:
var1=int(input("enter 1st num:"))
var2=int(input("enter 2nd num:"))
print(var1+var2)
print(var1-var2)
print(var1*var2)
print(var1/var2)
print(var1//var2)
print(var1%var2)
# In[ ]:
|
2de66f02fac340cd1beb457ea76322362404be56 | wiltonjr4/Python_Language | /Estudos/Python_Exercicios_Curso_Em_Video/ex011.py | 267 | 3.65625 | 4 | n1 = float(input('Quantos M² de Largura Mede a Parede?'))
n2 = float(input('Quantos M² de Altura Mede a Parede?'))
area = n1*n2
litros = area/2
print('Para pintar essa parede de {:.1f}m² de área, você precisará de: {:.1f} litros de tinta'.format(area,litros))
|
a3aa600dfb79f3b72a7e9b40a1885306cd720254 | PiKaLeX/.vscode | /Tutorials/Regular expressions/Metacharacters/repetition_curly_braces.py | 751 | 4.375 | 4 | import re
# Some more metacharacters are * + ? { and }.
# These specify numbers of repetitions.
# Curly braces can be used to represent the number of repetitions between two numbers.
# The regex {x,y} means "between x and y repetitions of something".
# Hence {0,1} is the same thing as ?.
# If the first number is missing, it is taken to be zero. If the second number is missing, it is taken to be infinity.
pattern = r"9{1,3}$"
if re.match(pattern, "0"):
print("Match 1")
if re.match(pattern, "9"):
print("Match 2")
if re.match(pattern, "99"):
print("Match 3")
if re.match(pattern, "999"):
print("Match 4")
if re.match(pattern, "9999"):
print("Match 5")
if re.match(pattern, "99099"):
print("Match 6") |
cf5dec440b002ae093dead03629c2a8fa9791a75 | Som94/Python-repo | /13th Aug/Test 1.py | 250 | 3.765625 | 4 | class emp:
pass
e1 = emp()
lst1 = [171,'Divakar',e1,56.22,'Ravi','78']
l=len(lst1)
if type(lst1[l-1])==str:
print("True")
else:
print("Not a string")
if type(lst1[l-2])==str:
print("True It's a string")
else:
print("Not a string") |
9211c5c54c77d563a7287a09e5506be7cc719b1e | futuremartian2018/Simple_Neural_Network_Python | /Neural Network - Python/main.py | 555 | 3.703125 | 4 | # NEURAL NETWORK TRAINING
# Importing required libraries and functions
import numpy as np
import neural as nn
import sklearn.datasets
import matplotlib.pyplot as plt
# Creating a data set using sklearn
X, Y = sklearn.datasets.make_moons(n_samples = 500, noise = 0.15)
X, Y = X.T, Y.reshape(1, Y.shape[0])
# Neural network training process
parameters, cost = nn.train(X, Y, 0.7, 12, 2000)
# Drawing cost chart
plt.figure(1, figsize=(10, 6))
plt.title('COST CHART')
plt.plot(cost)
plt.xlabel('Epoch')
plt.ylabel('Cost')
plt.show() |
d1b46c0173f1b5bcb2245e659ef0c3de3e1b93f6 | xiaoxue11/02_python_multi_task | /02_python核心编程/多任务/线程/interview3.py | 1,112 | 3.953125 | 4 | from threading import Thread, Condition
condition = Condition()
current = 'A'
class ClassA(Thread):
def run(self):
global current
for _ in range(10):
with condition:
while current != 'A':
condition.wait()
print('A')
current = 'B'
condition.notify_all()
class ClassB(Thread):
def run(self):
global current
for _ in range(10):
with condition:
while current != 'B':
condition.wait()
print('B')
current = 'C'
condition.notify_all()
class ClassC(Thread):
def run(self):
global current
for _ in range(10):
with condition:
while current != 'C':
condition.wait()
print('C')
current = 'A'
condition.notify_all()
def main():
t1 = ClassA()
t2 = ClassB()
t3 = ClassC()
t1.start()
t2.start()
t3.start()
if __name__ == '__main__':
main()
|
7bbf3bbd1ccdfacb3d1c255a8d084ed0b9277bed | Naresh523-Python/python-practice | /practice.py | 2,052 | 3.734375 | 4 |
# from collections import OrderedDict
# d=OrderedDict()
# d[100]='naresh'
# d[101]='mohan'
# d[103]='srinu'
# # print(dict)
# dt={104:'sai',105:'gopi'}
# d.update(dt)
# print(d)
# import sys
# for x,y in sys.argv:
# print ("Argument: ", x)
# print("Argument: ",y)
# how to give arguments in command prompt #######
import argparse
# import sys
#
# def check_arg(args=None):
# parser = argparse.ArgumentParser(description='Script to learn basic argparse')
# parser.add_argument('-H', '--host',
# help='host ip',
# required='True',
# default='localhost')
# parser.add_argument('-p', '--port',
# help='port of the web server',
# default='8080')
# parser.add_argument('-u', '--user',
# help='user name',
# default='root')
#
# results = parser.parse_args(args)
#
# return (results.host,
# results.port,
# results.user)
#
# if __name__ == '__main__':
# h, p, u = check_arg()
# print ('h =',h)
# print ('p =',p)
# print ('u =',u)
# lines=0
# words=0
# chars=0
# f=open('New Text Document.txt','r')
# data=f.read()
# print(data)
# for line in data:
# print(line)
# print(len(line))
# word=line.split(' ')
# print(word)
# print(len(word))
# lines=lines+1
# words=words+len(word)
# chars=chars+len(line)
# print('chars:',chars)
# print('words:',words)
# print('lines:',lines)
# import csv
# with open('student.csv','w')as f:
# w=csv.writer(f)
# w.writerow(["sno","sname","saddr"])
# n=int(input("enter number of students:"))
# for i in range(n):
# sno=input("enter student no:")
# sname=input("enter student name:")
# saddr=input("enter student addr:")
# w.writerow(["sno","sname","saddr"])
import csv
f=open('student.csv','r')
r=csv.reader(f)
data=list(r)
print(data)
for line in data:
for word in line:
print("word","\t")
|
549b54102ca38ac7d2b810f18b909baea5253a4a | finnbogi18/project_sjo | /stock_prices.py | 4,500 | 4.4375 | 4 | ''' This program takes a .csv file that the user inputs, then the program reads
the file and finds the average price for each month
and prints out the average price and the month of that price,
finally it prints out the year-month-day of the highest price '''
# Constants for the colums in the data list.
DATE = 0
ADJ_CLOSE = 5
VOLUME = 6
def open_file(filename):
''' This function opens the file and returns a file object,
if the file doesn't exist it prints out an error '''
try:
file_object = open(filename, "r")
return file_object
except FileNotFoundError:
print("Filename {} not found!".format(filename))
def get_data_list(file_object):
''' This function creates a list of lists
for the dates and stock prices '''
data_list = []
for line_str in file_object:
data_list.append(line_str.strip().split(",")) # Appends a list that splits at "," and then adds that to the main data list.
return data_list
def get_date_list(data_list):
''' This function creates a list of the dates, with the days removed
return the list with the following format: "YYYY-MM"
allowing the user for easier navigation when calculating averages '''
date_list = []
for i in range(1, len(data_list)):
temp_var = data_list[i][DATE]
temp_var = temp_var[:7]
if temp_var not in date_list:
date_list.append(temp_var)
return date_list
def get_monthly_average(data_list, date_list):
''' This functions reads the data list and calculates
the average stock price for each month and returns
the average price and the associated month as a list of tuples '''
month_counter = 0
month_tuple = ()
average_list = []
acv_sum = 0.0
vol_sum = 0.0
for i in data_list[1:]:
temp_var = i[DATE]
temp_var = temp_var[:7]
if temp_var == date_list[
month_counter]: # Checks if the current month matches the month being calcuated
acv_sum += float(i[ADJ_CLOSE]) * float(i[VOLUME])
vol_sum += float(i[VOLUME])
else: # If the months changes it calculates the average and adds the month and average to a tuple.
month_avg = acv_sum / vol_sum
month_tuple = (date_list[month_counter], month_avg)
average_list.append(month_tuple) # Adds the tuple to the main average list.
acv_sum = 0.0
vol_sum = 0.0
month_counter += 1
# Adds the first day of the new month as the starting sums.
# Because it's used to evaluate if a new month has begun causing it to be left out
# of the new month.
acv_sum += float(i[ADJ_CLOSE]) * float(i[VOLUME])
vol_sum += float(i[VOLUME])
# Adds the last month to the list.
month_avg = acv_sum / vol_sum
month_tuple = (date_list[month_counter], month_avg)
average_list.append(month_tuple)
return average_list
def find_highest(data_list):
""" This function finds the highest stock price in the whole list
and returns a tuple with the date and the price as a tuple."""
highest_price = 0.00
high_date = ""
for i in data_list[1:]:
temp_var = float(i[ADJ_CLOSE])
if temp_var > highest_price:
highest_price = temp_var
high_date = i[DATE]
high_tuple = (highest_price, high_date)
return high_tuple
def print_info(average_list, highest_tuple):
""" This function prints out the average price for each month in the time period that is given with the .csv file.
And lastly it prints out the price and date of the highest stock."""
print("{:<10}{:>7}".format("Month", "Price"))
for i in average_list:
print("{:<10}{:>7.2f}".format((i[0]),i[1]))
print("Highest price {:.2f} on day {}".format(highest_tuple[0], highest_tuple[1]))
def main(file_object):
""" The main function only runs most of the functions in the program.
If the file name entered by the user is wrong then this function wont run. """
data_list = get_data_list(file_object)
date_list = get_date_list(data_list)
average_list = get_monthly_average(data_list, date_list)
highest_tuple = find_highest(data_list)
print_info(average_list, highest_tuple)
filename = input("Enter filename: ")
file_object = open_file(filename)
if file_object != None:
main(file_object)
|
094b68c67d207ec6afa20fd8c57f620bb54782b3 | hroudae/CS6350 | /LinearRegression/StochasticGradientDescent.py | 1,012 | 3.828125 | 4 | ##########
# Author: Evan Hrouda
# Purpose: Implement the Stochastic Gradient Descent algorithm for least mean square
##########
import utilities
#####
# Author: Evan Hrouda
# Purpose: Perform the stochastic gradient descent learning algorithm
#####
def StochasticGradientDescent(x, y, r, iterations):
import random
wghts = [0 for i in range(len(x[0]))]
costs = [utilities.costValue(wghts, x, y)]
converge = False
for i in range(iterations):
# randomly sample an example
index = random.randrange(len(x))
# update weight vector with the stochastic grad
newWghts = []
for j in range(len(wghts)):
newWghts.append(wghts[j] + r*x[index][j]*(y[index] - utilities.dot(wghts,x[index])))
wghts = newWghts
# check convergence (calculate cost function)
costVal = utilities.costValue(wghts, x, y)
if abs(costVal - costs[-1]) < 10e-6:
converge = True
costs.append(costVal)
return wghts, costs, converge
|
50218453a06e56b73ba13c28fb91c22907657282 | jocphox/flashtrans | /getnewrow.py | 1,479 | 4.09375 | 4 |
def isTitle(ss):
if ss[0].isupper() and "." not in ss:
return True
elif ss[0].isupper() and "." in ss and len((ss.split(".")[0]).split(" "))>2:
return True
else:
return False
def newrow(lst,pos=1):
if pos<len(lst) and isTitle(lst[pos]):
lst[pos:pos+1]=["\n",lst[pos]]
newrow(lst,pos+2)
elif pos<len(lst):
newrow(lst,pos+1)
else:
pass
return lst
if __name__ == '__main__':
lst = ['A similar change has occurred in many other domains. Our ancestors got their',
'thrills the old-fashioned way: they took risks. Consider the human known as the',
'Iceman. About five thousand years ago, he set out on a European adventure and',
'ended up frozen in a glacier. Completely preserved, he can now be visited in a', 'museum',
'For the Iceman, a career mistake had fatal consequences. If we make a risky move',
'say, by taking a job with some poorly financed Internet company -and it fails',
'we will not be killed. More likely than not, we will find a new job with a higher',
'salary. If the failure is spectacular enough, we can write a series of books, like',
'Donald Trump. If we just rely on our instincts, we are likely to be too timid in our', 'professional lives']
newrow(lst)
text="".join(lst)
newlst=text.split("\n")
newtext="\n".join(newlst)
print(newtext) |
b1b8ea9c13b937798a097881037abd91d11b847e | naveenv20/myseleniumpythonlearn | /ControlFlow/ifcontrolflow.py | 278 | 3.875 | 4 | """
condition logic
"""
a=100
b=10
if(b<a):
print("%s less than %s"%(a,b))
print("This iwll always print")
val='Green'
value=val
if(value=='Red'):
print("Stop")
elif(value=='Green'):
print("Not in if so elif")
else:
print("Not in if or elif so inside else") |
3690784d3718d86ad47ed484da972a48e588b672 | gogagubi/Leetcode-Python | /array/_169_MajorityElement.py | 533 | 3.5625 | 4 | from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> int:
times = len(nums) // 2
map = dict.fromkeys(nums, 0)
for i in nums:
map[i] += 1
if map[i] > times:
return i
return -1
if True:
s = Solution()
nums = [3, 2, 3]
result = s.majorityElement(nums)
print("Result ", result)
if True:
s = Solution()
nums = [2, 2, 1, 1, 1, 2, 2]
result = s.majorityElement(nums)
print("Result ", result)
|
17ca21d5ee053c5a5b2d588630814fa3ed3e90f6 | TheAlgorithms/Python | /maths/combinations.py | 1,459 | 4.28125 | 4 | """
https://en.wikipedia.org/wiki/Combination
"""
from math import factorial
def combinations(n: int, k: int) -> int:
"""
Returns the number of different combinations of k length which can
be made from n values, where n >= k.
Examples:
>>> combinations(10,5)
252
>>> combinations(6,3)
20
>>> combinations(20,5)
15504
>>> combinations(52, 5)
2598960
>>> combinations(0, 0)
1
>>> combinations(-4, -5)
...
Traceback (most recent call last):
ValueError: Please enter positive integers for n and k where n >= k
"""
# If either of the conditions are true, the function is being asked
# to calculate a factorial of a negative number, which is not possible
if n < k or k < 0:
raise ValueError("Please enter positive integers for n and k where n >= k")
return factorial(n) // (factorial(k) * factorial(n - k))
if __name__ == "__main__":
print(
"The number of five-card hands possible from a standard",
f"fifty-two card deck is: {combinations(52, 5)}\n",
)
print(
"If a class of 40 students must be arranged into groups of",
f"4 for group projects, there are {combinations(40, 4)} ways",
"to arrange them.\n",
)
print(
"If 10 teams are competing in a Formula One race, there",
f"are {combinations(10, 3)} ways that first, second and",
"third place can be awarded.",
)
|
be7314fbc7c19f31acb7195cfdd447ee30b999ca | skiwee45/python | /dragon/password.py | 274 | 3.59375 | 4 | # Password program
print ("Welcome to System Security Inc.")
print ("-- where security is our middle name")
pwd = input("\nEnter your password:")
if pwd == "secret":
print("Access Granted")
else:
print("Access Denied")
input("\n\nPress any key to exit.") |
20bc5da2bd6cce8598e371689a7c7daba4cfbc25 | shahbagdadi/py-algo-n-ds | /arrays/bits/powerOfTwo/Solution.py | 251 | 3.75 | 4 | class Solution(object):
# Explanation - https://leetcode.com/problems/power-of-two/solution/
def isPowerOfTwo(self, n):
if n == 0:
return False
return n & (-n) == n
s = Solution()
ans = s.isPowerOfTwo(7)
print(ans) |
4189157a2283c83e99b9aacb1ea055bca65351ac | slawry00/CPE101 | /Labs/Lab_Filter.py | 2,012 | 3.875 | 4 | # Name: Spencer Lawry
# Name: Spencer Lawry
# Name: Spencer Lawry
# Course: CPE 101
# Instructor: Daniel Kauffman
# Assignment: Lab Assignment: Characters and Filtering
# Term: Fall 2016
def sum_101(my_list):
mysum = 0
for i in range(len(my_list)):
mysum = my_list[i] + mysum
return mysum
assert sum_101([1,5,3]) == 9
assert sum_101([-1,2,-1,5,5]) == 10
assert sum_101([-10,5,2,10,-30]) == -23
def index_of_smallest(my_list):
if len(my_list) <= 0:
return -1
else:
smallest = min(my_list)
return my_list.index(smallest)
assert index_of_smallest([5,2,1,-5]) == 3
assert index_of_smallest([]) == -1
assert index_of_smallest([1,1,1,1,0]) == 4
def is_lower_101(char):
return ord('a') <= ord(char) <= ord('z')
assert is_lower_101("a")
assert not is_lower_101("A")
assert is_lower_101("z")
def char_rot_13(char):
if ord('a') <= ord(char) <= ord('m') or ord('A') <= ord(char) <= ord('M'):
return chr(ord(char) + 13)
if ord('n') <= ord(char) <= ord('z') or ord('N') <= ord(char) <= ord('Z'):
return chr(ord(char) - 13)
assert char_rot_13('n') == 'a'
assert char_rot_13('m') == 'z'
assert char_rot_13('Z') == 'M'
def str_rot_13(my_str):
rot_13_str = ''
for i in range(len(my_str)):
current_rot_char = char_rot_13(my_str[i])
rot_13_str = rot_13_str + current_rot_char
return rot_13_str
assert str_rot_13('apples') == 'nccyrf'
assert str_rot_13('zigzag') == 'mvtmnt'
assert str_rot_13('AwEsOmE') == 'NjRfBzR'
def str_translate_101(my_str, old, new):
str_translate = ''
for i in range(len(my_str)):
current_char = my_str[i]
if current_char == old:
current_char = new
str_translate = str_translate + current_char
return str_translate
assert str_translate_101('mississippi', 'i', 'z') == 'mzsszsszppz'
assert str_translate_101('lollipop', 'o', 'u') == 'lullipup'
assert str_translate_101('hippopotamus', 'p', 's') == 'hissosotamus'
|
381672cd8628cc9454d79ca8660fe6093dc1b55d | dotch3/Python | /CODE/06/FROM CLASSES/square_test.py | 538 | 3.8125 | 4 | import unittest
from geometry import Rectangle
from geometry import Square
class SquareTest(unittest.TestCase):
def test_square_is_a_derivative_of_rectangle(self):
square =Square(0 , 0 , 5)
self.assertTrue(isinstance(square, Rectangle))
self.assertTrue(isinstance(square, Square))
def test_perimeter_returns_four_times_its_side(self):
square = Square(0 , 0 , 5)
self.assertEqual(20, square.perimeter())
square.width =3
self.assertEqual(20, square.perimeter())
if __name__ == '__main__':
unittest.main()
|
6c8f8e5235655fc9e6699b66306cc833283d0727 | ykdsg/myPython | /geekbang/algo/41_dynamic_programming/coins_problem_function_02.py | 542 | 3.890625 | 4 | # 状态转移方程,这个解法就很像回溯+缓存
from typing import List
def min_coin_num(price: int, coins: List[int], memo: List[int]):
if price == 0:
return 0
if price < 0:
return 99999
if memo[price] > 0:
return memo[price]
result = min(min_coin_num(price - coin, coins, memo) for coin in coins) + 1
memo[price] = result
return result
if __name__ == '__main__':
coins = [1, 3, 5]
price = 18
memo = [-1] * (price + 1)
print(min_coin_num(price, coins, memo))
|
7633206669af54e4a91de8b478508577d504dc4d | HaneulJ/Python | /listLab2.py | 514 | 3.9375 | 4 | """최솟값을 구하는 기능은 함수를 사용하지 않고 제어문으로 직접 구현한다.
1. listLab2.py 이라는 소스를 생성한다.
2. 다음 값들로 구성되는 리스트를 생성하여 listnum 에 저장한다.
10, 5, 7, 21, 4, 8, 18
3. listnum 에 저장된 값들 중에서 최솟값을 추출하여 출력한다.
"""
listnum = [10, 5, 7, 21, 4, 8, 18]
lmin = listnum[0]
for i in range(1,len(listnum)):
if lmin > listnum[i]:
lmin = listnum[i]
print("최솟값: ", lmin) |
27d7efe28dbf887c2ee1970064ef27469bf05a9d | lion137/blog | /porpositional_logic_eval.py | 4,319 | 3.53125 | 4 | import string
import re
import operator as op
import functools
from itertools import product
class BinaryTree:
def __init__(self, rootObj):
self.key = rootObj
self.parent = None
self.leftChild = None
self.rightChild = None
def insertLeft(self, newNode):
if self.leftChild == None:
t = BinaryTree(newNode)
self.leftChild = t
t.parent = self
else:
t = BinaryTree(newNode)
t.parent = self
t.leftChild = self.leftChild
self.leftChild.parent = t
self.leftChild = t
def insertRight(self, newNode):
if self.rightChild == None:
t = BinaryTree(newNode)
self.rightChild = t
t.parent = self
else:
t = BinaryTree(newNode)
t.parent = self
t.rightChild = self.rightChild
self.rightChild.parent = t
self.rightChild = t
def getRightChild(self):
return self.rightChild
def getLeftChild(self):
return self.leftChild
def getParent(self):
return self.parent
def getRootVal(self):
return self.key
def setRootVal(self, obj):
self.key = obj
def setLeftChild(self, nodeObj):
self.leftChild = nodeObj
def setRightChild(self, nodeObj):
self.rightChild = nodeObj
def setParent(self, nodeObj):
self.parent = nodeObj
def isRightChild(self):
return self.parent and self.parent.rightChild == self
def isLeftChild(self):
return self.parent and self.parent.leftChild == self
def isRoot(self):
return
def inorder_traversal(tree):
if tree:
inorder_traversal(tree.getLeftChild())
print(tree.getRootVal())
inorder_traversal(tree.getRightChild())
implication = lambda x, y: op.or_(op.not_(x), y)
equality = lambda x ,y: op.and_(implication(x, y), implication(y, x))
xor = lambda x, y: op.and_(op.or_(x, y), op.not_(op.and_(x, y)))
def build_parse_tree(exp):
exp_list = exp.replace('(', ' ( ').replace(')', ' ) ').replace('~', ' ~ ').split()
e_tree = BinaryTree('')
current_tree = e_tree
for token in exp_list:
if token == '(':
current_tree.insertLeft('')
current_tree = current_tree.getLeftChild()
elif token in ['||','&&', '->', '==', 'XR']:
if current_tree.getRootVal() == '~':
current_tree.getParent().setRootVal(token)
current_tree.insertRight('')
current_tree = current_tree.getRightChild()
else:
current_tree.setRootVal(token)
current_tree.insertRight('')
current_tree = current_tree.getRightChild()
elif token in ['1', '0']:
current_tree.setRootVal(bool(int(token)))
current_tree = current_tree.getParent()
if current_tree.getRootVal() == '~':
current_tree = current_tree.getParent()
elif token == '~':
current_tree.setRootVal('~')
current_tree.insertLeft('')
current_tree = current_tree.getLeftChild()
elif token == ')':
current_tree = current_tree.getParent()
else:
raise ValueError
return e_tree
def evaluate_parse_tree(tree):
opers = {'||': op.or_, '&&': op.and_, '~': op.not_, '->': implication, '==': equality, 'XR': xor}
leftT = tree.getLeftChild()
rightT = tree.getRightChild()
if leftT and not rightT:
fn = opers[tree.getRootVal()]
return fn(evaluate_parse_tree(leftT))
elif leftT and rightT:
fn = opers[tree.getRootVal()]
return fn(evaluate_parse_tree(leftT), evaluate_parse_tree(rightT))
else:
return tree.getRootVal()
def fill_values(formula):
"""returns genexp with the all fillings with 0 and 1"""
letters = ''.join(set(re.findall('[A-Z]', formula)))
for digits in product('10', repeat=len(letters)):
table = str.maketrans(letters, ''.join(digits))
yield formula.translate(table)
def is_tautology(formula):
for x in fill_values(formula):
if not evaluate_parse_tree(build_parse_tree(x)):
return False
return True
|
c7c3b02de464380102729f0a2191937cbe3bcf21 | jlameiro87/cs50 | /import.py | 1,390 | 3.921875 | 4 | from cs50 import SQL
from csv import reader
from sys import argv
def main():
# validate entry input
if len(argv) != 2:
print("usage error, import.py characters.csv")
exit()
# open the SQLite database
db = SQL('sqlite:///students.db')
# open the csv file and copy the content to a list
with open(argv[1], newline='') as charactersFile:
# read the characters
characters = reader(charactersFile)
# for each character
for character in characters:
# check for empty names
if character[0] == 'name':
continue
# split the full name into first, last and middle name as required
fullName = character[0].split()
# character dictionary
charDictionary = {
'first': fullName[0],
'middle': fullName[1] if len(fullName) > 2 else None,
'last': fullName[2] if len(fullName) > 2 else fullName[1],
'house': character[1],
'birth': character[2]
}
# insert the character into the database
db.execute("INSERT INTO students(first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)",
charDictionary['first'], charDictionary['middle'], charDictionary['last'], charDictionary['house'], charDictionary['birth'])
main()
|
16e32913cebea2b9c18a77b817a06f281c0e72b7 | Sana-mohd/functionsQuestions | /evenodd.py | 221 | 3.96875 | 4 | def shownumber(limit=int(input("enter your number: "))):
i=0
while i<=limit:
if i%2==0:
print( i,"even ")
else:
print(i,"odd")
i=i+1
print(shownumber())
|
e74417256687935ad7415a6e015f697302113334 | Ing-Josef-Klotzner/python | /2017/hackerrank/gridLand_sol.py | 3,106 | 3.5625 | 4 | #!/usr/bin/python3
class Solution:
def __init__(self):
self.size = int(input())
self.array = []
self.array.append(input().strip())
self.array.append(input().strip())
self.hash = set()
def add_to_hash(self, results):
for set_str in results:
self.hash.add(hash(set_str))
self.hash.add(hash(set_str[::-1]))
def calculate(self):
if len(set(self.array[0]+self.array[1]))==1:
return 1
results = self.get_circles(self.array[0]+self.array[1][::-1])
full_string1 = self.array[1][::-1]+self.array[0]
full_string2 = self.array[0][::-1]+self.array[1]
full_zigzags=self.get_zigzag('',1,0,+1)
self.add_to_hash(results)
results=set(full_zigzags.keys())
for i in range(1,self.size):
for zig,diverge in full_zigzags.items():
if diverge < i:
continue
j = self.size -i
if i%2 == 0:
new_str = full_string2[j:-j]+zig[i*2:]
else:
new_str = full_string1[j:-j]+zig[i*2:]
results.add(new_str)
self.add_to_hash(results)
full_zigzags=self.get_zigzag('',0,0,+1)
results=set(full_zigzags.keys())
for i in range(1,self.size):
for zig,diverge in full_zigzags.items():
if diverge < i:
continue
j = self.size -i
if i%2 == 0:
new_str = full_string1[j:-j]+zig[i*2:]
else:
new_str = full_string2[j:-j]+zig[i*2:]
results.add(new_str)
self.add_to_hash(results)
return len(self.hash)
def get_circles(self,loop):
circles = set()
circles.add(loop)
for i in range(self.size*2-1):
loop = loop[1:]+loop[0]
circles.add(loop)
return circles
def get_zigzag(self,seed,row,col,right):
output = list(seed)
steps = 0
zigzags = {}
while col >=0 and col <self.size:
output.append(self.array[row][col])
steps+=1
row = 0 if row == 1 else 1
if steps < self.size*2:
zigzags[self.add_circle_diversion(row,col,right,''.join(output))]=steps//2
output.append(self.array[row][col])
steps+=1
col+=right
zigzags[''.join(output)]=self.size
return zigzags
def add_circle_diversion(self, row, col, right, built_str):
built_str+=self.array[row][col::right]
remaining = 2*self.size-len(built_str)
if remaining == 0:
return built_str
row = 0 if row == 1 else 1
built_str+=self.array[row][::-1*right][:remaining]
return built_str
def main():
cases = int(input())
for i in range(cases):
my_object = Solution()
print(my_object.calculate())
def get_int_list(in_str):
return [int(i) for i in in_str.strip().split()]
if __name__ == "__main__":
main()
|
46e0b839d5720a1f398c6be39f5a589b5a606227 | srinivassjce/srinivas | /PYTHON/infinite_array.py | 399 | 3.515625 | 4 | #!/usr/bin/python
def find_element(array,k,entry) :
min=0
entry=int(entry)
while True :
flag=0
if entry <= array[k] :
flag=1
print k
if array[k] == entry :
#print k
return k
break
else :
k += 1
if flag==1 :
k= k/10
a=find_element(array,int(k),entry)
return a
array=[ i for i in range(100,2033111,1)]
print find_element(array,1000,121)
|
069b52f83f6dbf9d34947ae33e8cdf2b760b1af3 | manojkumar1053/GMAONS | /Sorting/quickSelect.py | 962 | 3.671875 | 4 | def quickSelect(array, k):
return quickSelectHelper(array, 0, len(array) - 1, k - 1)
def quickSelectHelper(array, startIdx, endIdx, position):
while True:
if startIdx > endIdx:
raise Exception("Error !!!")
pivotIndex = startIdx
leftIdx = startIdx + 1
rightIdx = endIdx
while leftIdx <= rightIdx:
if array[leftIdx] > array[pivotIndex] and array[rightIdx] < array[pivotIndex]:
swap(array, leftIdx, rightIdx)
if array[leftIdx] < array[pivotIndex]:
leftIdx += 1
if array[rightIdx] > array[pivotIndex]:
rightIdx -= 1
swap(array, pivotIndex, rightIdx)
if rightIdx == position:
return array[rightIdx]
elif array[rightIdx] < position:
startIdx = rightIdx + 1
else:
endIdx = rightIdx - 1
def swap(array, i, j):
array[i], array[j] = array[j], array[i]
|
232bd30f0b0e6b18cbef74fc23b178eb5fd40d48 | bujanvdv/lesson | /task_2.py | 423 | 4 | 4 | # Пользователь вводит время в секундах.
# Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс.
# Используйте форматирование строк.
sec = int(input('Введите время в секундах: '))
h=sec/3600
m=sec%3600/60
s=sec%3600%60
time = ('%i:%i:%i' % (h, m, s))
print(time)
|
aa97656496e1e0bd2f9198e024dba27052f2fd0b | yaayitsamber/Udacity-Python-Projects | /CircleTurtle.py | 299 | 3.640625 | 4 | import turtle
def draw_shapes():
window = turtle.Screen()
window.bgcolor("blue")
amy = turtle.Turtle()
amy.shape("turtle")
amy.color("white")
amy.speed(6)
for i in range(1, 11):
amy.circle(100)
amy.right
window.exitonclick()
draw_shapes()
|
256f6ae425ccc1c0218ea6789328ab3bbcd9f10c | mdmirabal/uip-prog3 | /investigaciones/Prueba Unitaria/Unittest.py | 345 | 3.671875 | 4 | import unittest
def cuadrado(num):
"""Calcula el cuadrado de un numero."""
return num ** 2
class EjemploPruebas(unittest.TestCase):
def test(self):
l = [0, 1, 2, 3]
r = [cuadrado(n) for n in l]
self.assertEqual(r, [0, 1, 4, 9])
if __name__ == "__main__":
unittest.main() |
e694a2318887d7baf70da015fe572d5d0b68bc7d | reyllama/algorithms | /#34.py | 2,834 | 3.796875 | 4 | """
2023.03.27
"""
"""
34. Find First and Last Position of Element in Sorted Array
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
"""
class Solution:
def searchRange(self, nums, target):
if len(nums) < 1:
return [-1, -1]
if len(nums) < 2:
if nums[0] == target:
return [0, 0]
else:
return [-1, -1]
self.left, self.right = -1, -1
def bisect(nums, target, l=None, r=None):
print(l, r)
if l == r:
if nums[l] == target:
if l == 0:
self.left = l
self.right = max(self.right, l)
elif r == len(nums) - 1:
self.right = r
if self.left == -1:
self.left = r
return
if l > r:
return
mid = (l + r) // 2
if nums[mid] == target:
if mid == 0:
self.left = mid
elif nums[mid - 1] != target:
self.left = mid
else:
bisect(nums, target, l=l, r=mid)
if mid == len(nums) - 1:
self.right = mid
elif nums[mid + 1] != target:
self.right = mid
else:
bisect(nums, target, l=mid + 1, r=r)
elif nums[mid] > target:
bisect(nums, target, l=l, r=mid)
else:
bisect(nums, target, l=mid + 1, r=r)
bisect(nums, target, 0, len(nums) - 1)
return [self.left, self.right]
"""
Time > 53.7%, Memory: 5.38%
Working, but very messy. Looking for a cleaner code.
"""
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
# Get the starting pos when target is present
# Get The one in either boundary (of the chasm) when target is absent
def search(x):
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < x:
lo = mid + 1
else:
hi = mid
return lo
lo = search(target)
hi = search(target + 1) - 1
if lo <= hi:
return [lo, hi]
return [-1, -1]
"""
Simply search for the 'lower bound (+1)' of the target range, by not specifying the condition when nums[mid]==x in search().
Then, we can get the higher bound by looking for a value slightly higher minus 1. Elegant.
""" |
7fdb4e8e9b4a9909c307347b6efbef745bbb485b | hellfireboy/game2.0 | /D5/100chicken.py | 945 | 3.59375 | 4 | # 公鸡5元一只,母鸡3元一只,小鸡1元三只,用100块钱买一百只鸡,问公鸡、母鸡、小鸡各有多少只?
# flag = False
#
# for x in range(0, 100):
# for y in range(0, 100):
# z = 100 - x - y
# if x * 5 + y * 3 + z / 3 == 100:
# a = x
# b = y
# c = z
# flag = True
#
# if flag == True:
# print("公鸡%d只,母鸡%d只,小鸡%d只。" % (a, b, c))
# else:
# print('不可能的事')
# print("公鸡%d只,母鸡%d只,小鸡%d只。" % (x, y, z))
# else:
# print('不可能')
flag = False
for x in range(0, 22):
for y in range(0, 51):
z = 100 - x - y
if x * 5 + y * 3 + z / 3 == 100:
print("公鸡%d只,母鸡%d只,小鸡%d只。" % (x, y, z))
flag = True
elif x == 21 and flag == False:
print("不可能")
break
# else:
# print('不可能')
|
ed36e7f6621e6d6245bcef325190efe345f73b3c | FranzDiebold/project-euler-solutions | /src/p053_combinatoric_selections.py | 1,518 | 4.125 | 4 | """
Problem 53: Combinatoric selections
https://projecteuler.net/problem=53
There are exactly ten ways of selecting three from five, 12345:
123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
In combinatorics, we use the notation, (5 over 3) = 10.
In general, (n over r) = n! / (r! * (n−r)!), where r <= n, n! = n * (n−1) * ... * 3 * 2 * 1,
and 0! = 1.
It is not until n = 23, that a value exceeds one-million: (23 over 10) = 1144066.
How many, not necessarily distinct, values of (n over r) for 1 <= n <= 100,
are greater than one-million?
"""
from typing import Iterable, Tuple
from src.common.calculations import calculate_binomial_coefficient
# pylint: disable=invalid-name
def get_large_binomial_coefficients(max_n: int, threshold: int) -> Iterable[Tuple[int, int, int]]:
"""
Get binomial coefficients (n over r) for `1 <= n <= max_n` that are greater than `threshold`.
Returns tuples `(n, r, (n over r))`.
"""
for n in range(1, max_n + 1):
for r in range(n + 1):
binomial_coefficient = calculate_binomial_coefficient(n, r)
if binomial_coefficient > threshold:
yield n, r, binomial_coefficient
def main() -> None:
"""Main function."""
max_n = 100
threshold = int(1e6)
count = len(list(get_large_binomial_coefficients(max_n, threshold)))
print(f'The number of values of (n over r) for 1 <= n <= {max_n} ' \
f'that are greater than {threshold:,} is {count}.')
if __name__ == '__main__':
main()
|
acf7fee9a3c2281a0515c6e0124e21a3f5e818dc | naveeez10/Snake-Game | /snake.py | 1,570 | 3.625 | 4 | from turtle import *
import random
class Snake:
def __init__(self) -> None:
self.segs = []
self.positions = [(-240, 0), (-260, 0), (-280, 0)]
for pos in self.positions:
self.create_snake(pos)
self.head = self.segs[0]
def create_snake(self,pos):
new = Turtle()
new.speed("fastest")
new.color("white")
new.penup()
new.shape("square")
new.goto(pos)
self.segs.append(new)
def extend(self):
self.create_snake(self.segs[-1].position())
def move_forward(self):
for seg_num in range(len(self.segs) - 1, 0, -1):
new_x = self.segs[seg_num - 1].xcor()
new_y = self.segs[seg_num - 1].ycor()
self.segs[seg_num].goto(new_x, new_y)
self.segs[0].forward(20)
def move_right(self):
if self.segs[0].heading() == 90:
self.segs[0].right(90)
elif self.segs[0].heading() == 270:
self.segs[0].left(90)
def move_up(self):
if self.segs[0].heading() == 180:
self.segs[0].right(90)
elif self.segs[0].heading() == 0:
self.segs[0].left(90)
def move_down(self):
if self.segs[0].heading() == 0:
self.segs[0].right(90)
elif self.segs[0].heading() == 180:
self.segs[0].left(90)
def move_left(self):
if self.segs[0].heading() == 270:
self.segs[0].right(90)
elif self.segs[0].heading() == 90:
self.segs[0].left(90)
|
dae092634d883118596da8e9a927e9c215c57f4d | mkamon/codewars | /python/6_kyu/BuildPileCubes.py | 768 | 4.03125 | 4 | # Your task is to construct a building which will be a pile of n cubes.
# The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3.
# You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?
# The parameter of the function findNb (find_nb, find-nb, findNb)
# will be an integer m and you have to return the integer n such as n^3 + (n-1)^3 + ... + 1^3 = m if such a n exists or -1 if there is no such n.
# Examples:
# findNb(1071225) --> 45
# findNb(91716553919377) --> -1
def find_nb(m):
n, sum = 0,0
while sum < m :
n += 1
sum += n ** 3
return n if sum == n else -1 |
9686dfe29cf589e1d4d4bbae479b465e78069007 | lamblard/CallofDuty112Zombies- | /Project Source and Support Files /termProjectRunGame.py | 85,142 | 3.53125 | 4 | """
15-112 Term Project: Call of Duty: 112 - Zombies
Name: Luca Amblard
Andrew ID: lamblard
Section: D
"""
import pygame
import random
import copy
# I learned basic pygame from Lukas Peraza's website
# http://blog.lukasperaza.com/getting-started-with-pygame/
# Pygame syntax learned from the pygame website
# https://www.pygame.org/docs/ref/sprite.html
# https://www.pygame.org/docs/ref/mixer.html
# Other citations are located next to code
# PygameGame class below from
# https://github.com/LBPeraza/Pygame-Asteroids/blob/master/pygamegame.py
class PygameGame(object):
def init(self):
pass
def mousePressed(self, x, y):
pass
def mouseReleased(self, x, y):
pass
def mouseMotion(self, x, y):
pass
def mouseDrag(self, x, y):
pass
def keyPressed(self, keyCode, modifier):
pass
def keyReleased(self, keyCode, modifier):
pass
def timerFired(self, dt):
pass
def redrawAll(self, screen):
pass
def isKeyPressed(self, key):
''' return whether a specific key is being held '''
return self._keys.get(key, False)
def __init__(self, width=600, height=400, fps=200, title
="Call of Duty: 112 - Zombies"):
self.width = width
self.height = height
self.fps = fps
self.title = title
self.bgColor = (255, 255, 255)
pygame.init()
def run(self):
clock = pygame.time.Clock()
screen = pygame.display.set_mode((self.width, self.height))
# set the title of the window
pygame.display.set_caption(self.title)
# stores all the keys currently being held down
self._keys = dict()
# call game-specific initialization
self.init()
self.playing = True
while self.playing:
time = clock.tick(self.fps)
self.timerFired(time)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
self.mousePressed(*(event.pos))
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
self.mouseReleased(*(event.pos))
elif (event.type == pygame.MOUSEMOTION and
event.buttons == (0, 0, 0)):
self.mouseMotion(*(event.pos))
elif (event.type == pygame.MOUSEMOTION and
event.buttons[0] == 1):
self.mouseDrag(*(event.pos))
elif event.type == pygame.KEYDOWN:
self._keys[event.key] = True
self.keyPressed(event.key, event.mod)
elif event.type == pygame.KEYUP:
self._keys[event.key] = False
self.keyReleased(event.key, event.mod)
elif event.type == pygame.QUIT:
self.playing = False
screen.fill(self.bgColor)
self.redrawAll(screen)
pygame.display.flip()
pygame.quit()
# TA Nikolai Lenney advised me to use the Game and Mode classes below
# He explained to me how these classes would work but I wrote both classes
# on my own
class Game(PygameGame):
def __init__(self, width, height):
self.width, self.height = width, height
super().__init__(self.width, self.height)
self.mode = StartGame(self)
def init(self):
self.mode.init()
def mousePressed(self, x, y):
self.mode.mousePressed(x, y)
def keyPressed(self, keyCode, modifier):
self.mode.keyPressed(keyCode, modifier)
def keyReleased(self, keyCode, modifier):
self.mode.keyReleased(keyCode, modifier)
def timerFired(self, dt):
self.mode.timerFired(dt)
def redrawAll(self, screen):
self.mode.redrawAll(screen)
class Mode(object):
def __init__(self, game):
self.game = game
class StartGame(Mode):
def __init__(self, game):
super().__init__(game)
self.width, self.height = self.game.width, self.game.height
def init(self):
w, h = self.width, self.height
self.mode = "Start"
# rects of the different buttons
incr = 40
self.playBot = (w*0.1, h*0.8, 160, 45)
self.instBot = (w*0.25+incr, h*0.8, 160, 45)
self.backBot = (w*(56/135), h*0.9, 160, 45)
self.soloBot = (w*0.1, h*0.8, 160, 45)
self.coopBot = (w*0.25, h*0.8, 160, 45)
size = 100
self.font = pygame.font.SysFont(None, size, True)
# click sound from http://soundbible.com/1705-Click2.html
self.click = pygame.mixer.Sound("click.wav")
self.loadImages()
def loadImages(self):
self.loadBackgroundImage()
self.loadStartScreenCoDImage()
self.loadStartScreenZombiesImage()
self.loadPlayBottonImage()
self.loadInstructionsBottonImage()
self.loadBackBottonImage()
self.loadSoloBottonImage()
self.loadCoopBottonImage()
self.loadInstructionsImage()
def getCoords(self, bot):
x0, y0 = bot[0], bot[1]
x1, y1 = (x0 + bot[2]), (y0 + bot[-1])
return x0, y0, x1, y1
def mousePressed(self, x, y):
if (self.mode == "Start"):
playX0, playY0, playX1, playY1 = self.getCoords(self.playBot)
instX0, instY0, instX1, instY1 = self.getCoords(self.instBot)
# we check whether or not the play button was pressed
if (playX0<=x<=playX1) and (playY0<=y<=playY1):
self.click.play()
self.mode = "SoloOrCoop"
# we check whether or not the instructions button was pressed
elif (instX0<=x<=instX1) and (instY0<=y<=instY1):
self.click.play()
self.mode = "Instructions"
elif (self.mode == "Instructions"):
bX0, bY0, bX1, bY1 = self.getCoords(self.backBot)
# we check whether or not the back button was pressed
if (bX0<=x<=bX1) and (bY0<=y<=bY1):
self.click.play()
self.mode = "Start"
elif (self.mode == "SoloOrCoop"):
soloX0, soloY0, soloX1, soloY1 = self.getCoords(self.soloBot)
coopX0, coopY0, coopX1, coopY1 = self.getCoords(self.coopBot)
# we check whether or not the solo button was pressed
if (soloX0<=x<=soloX1) and (soloY0<=y<=soloY1):
self.click.play()
self.game.mode = PlaceSoldier(self.game, False)
self.game.init()
# we check whether or not theb cooop button was pressed
elif (coopX0<=x<=coopX1) and (coopY0<=y<=coopY1):
self.click.play()
self.game.mode = PlaceSoldier(self.game, True)
self.game.init()
def keyPressed(self, keyCode, modifier):
pass
def keyReleased(self, keyCode, modifier):
pass
def timerFired(self, dt):
pass
def redrawAll(self, screen):
if (self.mode == "Start"):
self.drawStartScreen(screen)
elif (self.mode == "Instructions"):
self.drawInstructionsScreen(screen)
elif (self.mode == "SoloOrCoop"):
self.drawSoloOrCoopScreen(screen)
def drawStartScreen(self, screen):
screen.blit(self.background, (0, 0))
xRatio, yRatio = (7/24), (1/3)
x0, y0 = (xRatio * self.width), (yRatio * self.height)
screen.blit(self.startScreenCoD, (x0, y0))
xRatio, yRatio = (11/30), (46/75)
x0, y0 = (xRatio * self.width), (yRatio * self.height)
screen.blit(self.startScreenZombies, (x0, y0))
self.draw112(screen)
self.drawStartScreenBottons(screen)
def draw112(self, screen):
white = (204, 195, 195)
xRatio, yRatio = (13/30), (74/150)
text = "112"
text = self.font.render(text, True, white)
left, top = (xRatio * self.width), (yRatio * self.height)
screen.blit(text, [left, top])
def drawStartScreenBottons(self, screen):
screen.blit(self.playBotton, (self.playBot[0], self.playBot[1]))
screen.blit(self.instructionsBotton, (self.instBot[0], self.instBot[1]))
def drawInstructionsScreen(self, screen):
x0, y0 = 0, 0
screen.blit(self.background, (x0, y0))
screen.blit(self.backBotton, (self.backBot[0], self.backBot[1]))
xRatio, yRatio = (6/25), (1/40) #(9/71) (1/ 20)
incr = 40
x0, y0 = (xRatio * self.width - incr), (yRatio * self.height)
screen.blit(self.instructions, (x0, y0))
def drawSoloOrCoopScreen(self, screen):
x0, y0 = 0, 0
screen.blit(self.background, (x0, y0))
screen.blit(self.soloBotton, (self.soloBot[0], self.soloBot[1]))
screen.blit(self.coopBotton, (self.coopBot[0], self.coopBot[1]))
def loadBackgroundImage(self):
# background image from http://www.meristation.com/noticias/la-historia
# -de-call-of-duty-zombies-acabara-con-el-proximo-dlc/2139143
background = pygame.image.load("background.png").convert_alpha()
w, h = self.width, self.height
self.background = pygame.transform.scale(background, (w, h))
def loadStartScreenCoDImage(self):
# startScreenCoD image from
# http://gearnuke.com/top-5-perks-call-duty-zombies/
startScreenCoD = (pygame.image.load("startScreenCoD.png").
convert_alpha())
wRatio, hRatio = (49/120), (3/25)
w, h = int(wRatio * self.width), int(hRatio * self.height)
self.startScreenCoD = pygame.transform.scale(startScreenCoD, (w, h))
def loadStartScreenZombiesImage(self):
# startScreenZombies image from
# http://gearnuke.com/top-5-perks-call-duty-zombies/
startScreenZombies = (pygame.image.load("startScreenZombies.png").
convert_alpha())
wRatio, hRatio = (31/120), (7/75)
w, h = int(wRatio * self.width), int(hRatio * self.height)
self.startScreenZombies = pygame.transform.scale(startScreenZombies,
(w, h))
def loadPlayBottonImage(self):
# background of image is from
# http://gearnuke.com/top-5-perks-call-duty-zombies/
playBotton = pygame.image.load("playBotton.png").convert_alpha()
w, h = self.playBot[2], self.playBot[-1]
self.playBotton = pygame.transform.scale(playBotton, (w, h))
def loadInstructionsBottonImage(self):
# background of image is from
# http://gearnuke.com/top-5-perks-call-duty-zombies/
instructionsBotton = (pygame.image.load("instructionsBotton.png").
convert_alpha())
w, h = self.instBot[2], self.instBot[-1]
self.instructionsBotton = pygame.transform.scale(instructionsBotton,
(w, h))
def loadBackBottonImage(self):
# background of image is from
# http://gearnuke.com/top-5-perks-call-duty-zombies/
backBotton = pygame.image.load("backBotton.png").convert_alpha()
w, h = self.backBot[2], self.backBot[-1]
self.backBotton = pygame.transform.scale(backBotton, (w, h))
def loadSoloBottonImage(self):
# background of image is from
# http://gearnuke.com/top-5-perks-call-duty-zombies/
soloBotton = pygame.image.load("soloBotton.png").convert_alpha()
w, h = self.soloBot[2], self.soloBot[-1]
self.soloBotton = pygame.transform.scale(soloBotton, (w, h))
def loadCoopBottonImage(self):
# background of image is from
# http://gearnuke.com/top-5-perks-call-duty-zombies/
coopBotton = pygame.image.load("coopBotton.png").convert_alpha()
w, h = self.coopBot[2], self.coopBot[-1]
self.coopBotton = pygame.transform.scale(coopBotton, (w, h))
def loadInstructionsImage(self):
# background of image is from
# http://gearnuke.com/top-5-perks-call-duty-zombies/
self.instructions = (pygame.image.load("instructions.png").
convert_alpha())
class PlaceSoldier(Mode):
def __init__(self, game, coop):
super().__init__(game)
# screen width and screen height
self.width, self.height = self.game.width, self.game.height
# coop is a boolean that determines whether we are in
# solo mode or coop mode
self.coop = coop
def init(self):
divisor = 30
self.cellSize = self.width // divisor
self.rows = self.height // self.cellSize
self.cols = self.width // self.cellSize
self.blockGroup = pygame.sprite.Group(Block(0, 0, self.cellSize))
self.screenX0, self.screenY0 = 0, 0
self.soldierGroup = None
size = 40
self.font = pygame.font.SysFont(None, size, True)
leftSideMult = 8
lengthMult = 14
self.scoreBar = (leftSideMult * self.cellSize, 0, lengthMult *
self.cellSize, self.cellSize)
self.board = [[(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),
(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)],
[(1), -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1,(1),(1), -1, -1, -1, -1, -1, -1, -1, -1,(1)],
[(1), -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1,(1),(1), -1, -1, -1, -1, -1, -1, -1, -1,(1)],
[(1),(1),(1), -1, -1,(1),(1), -1, -1,(1),(1),(1),(1),(1),(1), -1, -1,
(1),(1),(1),(1),(1),(1), -1, -1,(1),(1), -1, -1,(1)],
[(1),(1),(1), -1, -1,(1),(1), -1, -1,(1),(1),(1),(1),(1),(1), -1, -1,
(1),(1),(1),(1),(1),(1), -1, -1,(1),(1), -1, -1,(1)],
[(1), -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,(1),(1), -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,(1)],
[(1), -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,(1),(1), -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,(1)],
[(1), -1, -1,(1),(1),(1),(1),(1),(1),(1),(1), -1, -1, -1, -1, -1, -1,
(1),(1), -1, -1,(1),(1),(1),(1),(1),(1), -1, -1,(1)],
[(1), -1, -1,(1),(1),(1),(1),(1),(1),(1),(1), -1, -1, -1, -1, -1, -1,
(1),(1), -1, -1,(1),(1),(1),(1),(1),(1), -1, -1,(1)],
[(1), -1, -1,(1),(1), -1, -1, -1, -1, -1, -1, -1, -1,(1),(1), -1, -1,
-1, -1, -1, -1,(1),(1), -1, -1, -1, -1, -1, -1,(1)],
[(1), -1, -1,(1),(1), -1, -1, -1, -1, -1, -1, -1, -1,(1),(1), -1, -1,
-1, -1, -1, -1,(1),(1), -1, -1, -1, -1, -1, -1,(1)],
[(1), -1, -1,(1),(1), -1, -1,(1),(1),(1),(1), -1, -1,(1),(1), -1, -1,
(1),(1), -1, -1, -1, -1, -1, -1,(1),(1), -1, -1,(1)],
[(1), -1, -1,(1),(1), -1, -1,(1),(1),(1),(1), -1, -1,(1),(1), -1, -1,
(1),(1), -1, -1, -1, -1, -1, -1,(1),(1), -1, -1,(1)],
[(1), -1, -1, -1, -1, -1, -1,(1),(1), -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1,(1),(1), -1, -1, -1, -1, -1, -1,(1)],
[(1), -1, -1, -1, -1, -1, -1,(1),(1), -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1,(1),(1), -1, -1, -1, -1, -1, -1,(1)],
[(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),
(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)]]
self.placeBlocks()
self.loadFloorImage()
def placeBlocks(self):
for row in range(len(self.board)):
for col in range(len(self.board[0])):
if self.board[row][col] == 1:
x0, y0, = self.getCellTopLeft(row, col)
self.blockGroup.add(Block(x0, y0, self.cellSize))
def loadFloorImage(self):
# floor image from https://minecraft.novaskin.me/search?q=sand%20block
floor = pygame.image.load("floor.png").convert_alpha()
w, h = self.cellSize, self.cellSize
self.image = pygame.transform.scale(floor, (w, h))
def getCellTopLeft(self, row, col):
x0 = (col * self.cellSize) - self.screenX0
y0 = (row * self.cellSize) - self.screenY0
return x0, y0
def mousePressed(self, x, y):
placeable = True
for block in iter(self.blockGroup):
if block.rect.collidepoint(x,y):
# prevents user from blacing soldier on a block
placeable = False
if placeable:
row, col = (y // self.cellSize), (x // self.cellSize)
x0, y0 = self.getCellTopLeft(row, col)
self.placeSoldier(x0, y0)
def placeSoldier(self, x0, y0):
self.soldierGroup = (pygame.sprite.Group(Soldier(x0, y0,
self.cellSize)))
# when the soldier is placed, the game starts
self.game.mode = PlayGame(self.game, self.blockGroup,
self.cellSize, self.rows, self.cols, self.screenX0,
self.screenY0, self.soldierGroup, self.coop)
self.game.init()
def keyPressed(self, keyCode, modifier):
pass
def keyReleased(self, keyCode, modifier):
pass
def timerFired(self, dt):
pass
def redrawAll(self, screen):
self.drawFloor(screen)
self.blockGroup.draw(screen)
self.drawPlaceSoldierBar(screen)
def drawFloor(self, screen):
for row in range(1, self.rows-1):
for col in range(1, self.cols-1):
x0, y0 = self.getCellTopLeft(row, col)
screen.blit(self.image, (x0, y0))
def drawPlaceSoldierBar(self, screen):
black = (0, 0, 0)
red = (250, 40, 40)
pygame.draw.rect(screen, black, pygame.Rect(self.scoreBar))
text = "Click on the map to place soldier"
text = self.font.render(text, True, red)
mult = 17/2
left = self.cellSize * mult
top = self.cellSize/2**2
screen.blit(text, [left, top])
class PlayGame(Mode):
def __init__(self, game, blockGroup, cellSize, rows, cols, screenX0,
screenY0, soldierGroup, coop):
super().__init__(game)
self.width, self.height = self.game.width, self.game.height
self.blockGroup = blockGroup
self.cellSize = cellSize
self.rows, self.cols = rows, cols
self.screenX0 = screenX0
self.screenY0 = screenY0
self.soldierGroup = soldierGroup
self.coop = coop
self.decreased = False
zombMult = 2
botMult = 2
foodMult = 2
self.spawningZombieLimit = zombMult * self.cellSize
self.spawningFoodLimit = foodMult * self.cellSize
self.spawningBotLimit = botMult * self.cellSize
self.spriteVariableInit()
# gunshot sound from http://soundbible.com/2120-9mm-Gunshot.html
self.gunshot = pygame.mixer.Sound("gunshot.wav")
# new round sound from http://soundbible.com/2108-Shoot-Arrow.html
self.newRound = pygame.mixer.Sound("newRound.wav")
# game over sound from http://soundbible.com/1771-Laser-Cannon.html
self.gameOverSound = pygame.mixer.Sound("gameOver.wav")
self.powerUpNum = 1
self.powerUpList = ["nuke", "penetration", "invinsibility", "speed",
"instaKill", "decoy"]
self.powerUpGroupsInit()
self.powerUpInit()
self.round = 1
# indicates whether or not the round is transitioning
self.roundTrans = False
self.roundDelay = 0
self.roundBegin = 50
self.time = 0
self.timeLimit = 900
self.secs = 60
self.minDistIncreased = False
self.minDistIncreasedSecond = False
leftSideMult = 9
lengthMult = 12
self.scoreBar = (leftSideMult * self.cellSize, 0, lengthMult *
self.cellSize, self.cellSize)
size = 40
self.font = pygame.font.SysFont(None, size, True)
self.moveBoard = [ [ -1, -1, -1, -1, -1, -1, -1, -1, -1,(1), -1, -1,
-1, -1],
[(1), -1,(1), -1,(1),(1),(1), -1,(1),(1),(1), -1,(1), -1],
[ -1, -1, -1, -1, -1, -1,(1), -1, -1, -1, -1, -1, -1, -1],
[ -1,(1),(1),(1),(1), -1, -1, -1,(1), -1,(1),(1),(1), -1],
[ -1,(1), -1, -1, -1, -1,(1), -1, -1, -1,(1), -1, -1, -1],
[ -1,(1), -1,(1),(1), -1,(1), -1,(1), -1, -1, -1,(1), -1],
[ -1, -1, -1,(1), -1, -1, -1, -1, -1, -1,(1), -1, -1, -1] ]
self.botGroup = pygame.sprite.Group()
self.botNum = 2
if self.coop:
for i in range(self.botNum):
self.placeBot()
self.placeFoodAndZombies()
def init(self):
self.loadFloorImage()
def placeFoodAndZombies(self):
for i in range(self.foodNumber):
self.placeFood()
for i in range(self.zombieNum):
self.placeZombie()
def loadFloorImage(self):
# floor image from https://minecraft.novaskin.me/search?q=sand%20block
floor = pygame.image.load("floor.png").convert_alpha()
w, h = self.cellSize, self.cellSize
self.image = pygame.transform.scale(floor, (w, h))
def powerUpGroupsInit(self):
self.nukeGroup = pygame.sprite.GroupSingle()
self.penetrationGroup = pygame.sprite.GroupSingle()
self.invinsibilityGroup = pygame.sprite.GroupSingle()
self.speedGroup = pygame.sprite.GroupSingle()
self.instaKillGroup = pygame.sprite.GroupSingle()
self.decoyPowerUpGroup = pygame.sprite.GroupSingle()
self.decoyGroup = pygame.sprite.GroupSingle()
def powerUpInit(self):
self.nuke = False
self.penetration = False
self.penetrationCount = 0
self.penetrationLimit = 200
self.invinsibilityCount = 0
self.invinsibilityLimit = 200
self.invinsibility = False
self.speedCount = 0
self.speedLimit = 200
self.speed = False
self.instaKillCount = 0
self.instaKillLimit = 200
self.instaKill = False
self.decoyCount = 0
self.decoyLimit = 200
self.decoy = False
self.decoyPos = (None, None)
def spriteVariableInit(self):
self.zombieGroup = pygame.sprite.Group()
self.bulletsToKillRange = 1
# number of zombies on the map at a certain round
self.zombieNum = 4
self.zombieSpeed = 2
# maximum number of zombies on the map
self.zombieMax = 6
self.bulletGroup = pygame.sprite.Group()
self.bulletSize = 10
self.foodGroup = pygame.sprite.Group()
mult = 0.6
self.foodSize = int(mult * self.cellSize)
self.foodNumber = 3
def mousePressed(self, x, y):
pass
def keyPressed(self, keyCode, modifier):
# if the round is not in the phase of changing
if not(self.roundTrans):
for soldier in iter(self.soldierGroup):
# moves soldier and rotates the image of the soldier
# in the direction corresponding to the arrow key pressed
soldier.direct(keyCode, self.invinsibility)
angle = soldier.getAngle()
if (keyCode == pygame.K_c):
# bullet is shot by soldier
x0, y0 = self.getBulletCoords(angle)
self.gunshot.play()
self.bulletGroup.add(Bullet(x0, y0, angle, self.bulletSize,
False, self.penetration, self.instaKill))
def getBulletCoords(self, angle):
# function positions bullet on screen in a location such
# that it looks like the bullet is coming out
# of the soldier's gun
top, left, right, bottom = 0, 90, 270, 180
offset = self.cellSize // 2
incr = 10
for soldier in iter(self.soldierGroup):
x0, y0 = soldier.rect.left, soldier.rect.top
x1, y1 = soldier.rect.right, soldier.rect.bottom
if (angle == top):
bulletX0 = x0 + offset
bulletY0 = y0 - self.bulletSize
elif (angle == right):
bulletX0 = x1
bulletY0 = y0 + offset
elif (angle == left):
bulletX0 = x0 - self.bulletSize
bulletY0 = y0 + (self.cellSize - offset) - incr
elif (angle == bottom):
bulletX0 = x0 + (self.cellSize - offset) - incr
bulletY0 = y1
return bulletX0, bulletY0
def keyReleased(self, keyCode, modifier):
for soldier in iter(self.soldierGroup):
soldier.stop(keyCode)
def getFoodCoords(self, x0Cell, y0Cell):
divisor = 3/2
x0Food = x0Cell + (self.cellSize + self.foodSize)//divisor
y0Food = y0Cell + (self.cellSize + self.foodSize)//divisor
return x0Food, y0Food
def getPowerUpCoords(self, x0Cell, y0Cell):
x0powerUp = x0Cell + (self.cellSize - self.foodSize) // 2
y0powerUp = y0Cell + (self.cellSize - self.foodSize) // 2
return x0powerUp, y0powerUp
def placeBot(self):
works = False
while not(works):
works = True
moveBoardRow = random.randint(0, len(self.moveBoard) - 1)
moveBoardCol = random.randint(0, len(self.moveBoard[0]) - 1)
if (self.moveBoard[moveBoardRow][moveBoardCol] == 1):
# prevents the bot from being placed on a wall
works = False
else:
# realRow and realCol are on the grid on which
# the outer blocks lie
realRow = 1 + 2 * moveBoardRow
realCol = 1 + 2 * moveBoardCol
x0Cell, y0Cell = self.getCellTopLeft(realRow, realCol)
x0Bot, y0Bot = self.getZombieCoords(x0Cell, y0Cell)
for zomb in iter(self.zombieGroup):
if ((abs(x0Bot - zomb.rect.left) <
self.spawningZombieLimit) or
(abs(y0Bot - zomb.rect.top) <
self.spawningZombieLimit)):
works = False
self.botGroup.add(Bot(x0Bot, y0Bot, self.cellSize))
# this prevents the bot from being placed on food, on a zombie
# or on the soldier
if ((pygame.sprite.groupcollide(self.zombieGroup, self.botGroup,
False, True))
or (pygame.sprite.groupcollide(self.soldierGroup, self.botGroup,
False, True))):
self.placeBot()
def placeFood(self):
works = False
while not(works):
works = True
moveBoardRow = random.randint(0, len(self.moveBoard) - 1)
moveBoardCol = random.randint(0, len(self.moveBoard[0]) - 1)
if (self.moveBoard[moveBoardRow][moveBoardCol] == 1):
works = False
else:
# realRow and realCol are on the grid on which
# the outer blocks lie
realRow = 1 + 2 * moveBoardRow
realCol = 1 + 2 * moveBoardCol
x0Cell, y0Cell = self.getCellTopLeft(realRow, realCol)
x0Food, y0Food = self.getFoodCoords(x0Cell,y0Cell)
for soldier in iter(self.soldierGroup):
if ((abs(x0Food - soldier.rect.left) <
self.spawningFoodLimit) or
(abs(y0Food - soldier.rect.top) <
self.spawningFoodLimit)):
works = False
# this prevents the food from spawning within a certain
# distance of the soldier
# if the food spawned right next to the solier,
# the game would be too easy
self.foodGroup.add(Food(x0Food, y0Food,
self.foodSize))
def timerFired(self, dt):
if not(self.roundTrans):
self.time += 1
minute = 15
if (self.time % minute == 0) and (self.secs > 1):
self.secs -= 1
# the time allowed to get all the apples in a round is limited
if (self.time == self.timeLimit):
self.gameOver()
# ensures the number of zombies in the map at a given round
# stays constant
if not(self.nuke):
while (len(self.zombieGroup) != self.zombieNum):
self.placeZombie()
target = 1
maximum = 200
result = random.randint(1, maximum)
# chances of a power up spawning are 1/maximum
if result == target:
self.spawnPowerUp()
self.powerUpTimer()
self.checkPowerUpCollisions()
for soldier in iter(self.soldierGroup):
soldier.move()
if pygame.sprite.groupcollide(self.blockGroup,
self.soldierGroup, False, False, pygame.sprite.collide_rect):
for soldier in iter(self.soldierGroup):
# prevents soldier from moving through walls
soldier.unmove()
for soldier in iter(self.soldierGroup):
soldierCoords = (soldier.rect.left + self.cellSize/2,
soldier.rect.top + self.cellSize/2)
soldierCenterRowCol = soldier.getSoldierCenterRowCol()
soldierBoardRowCol = (int((soldierCenterRowCol[0] - 1) // 2),
int((soldierCenterRowCol[1] - 1) // 2))
moveBoard = copy.deepcopy(self.moveBoard)
self.zombieGroup.update(soldierBoardRowCol, moveBoard,
soldierCoords, self.decoy, self.decoyPos)
self.bulletGroup.update()
if not(self.penetration):
# prevents bullets from going through walls
pygame.sprite.groupcollide(self.blockGroup, self.bulletGroup,
False, True)
if not(self.instaKill):
# this allows the number of bullets required to kill a
# zombie to be increased
for zomb in iter(self.zombieGroup):
bulletList = (pygame.sprite.spritecollide(zomb,
self.bulletGroup, False))
if len(bulletList) != 0:
for bullet in bulletList:
bullet.kill()
zomb.damage()
else:
pygame.sprite.groupcollide(self.zombieGroup, self.bulletGroup,
True, True)
if (self.invinsibility):
pygame.sprite.groupcollide(self.zombieGroup, self.soldierGroup,
True, False)
# collision of a zombie with the soldier ends the game
elif pygame.sprite.groupcollide(
self.zombieGroup, self.soldierGroup, False, True):
self.gameOverSound.play()
self.gameOver()
pygame.sprite.groupcollide(self.soldierGroup, self.foodGroup, False,
True)
# allows the bots to also get the food
pygame.sprite.groupcollide(self.botGroup, self.foodGroup, False,
True)
if (len(self.foodGroup) == 0):
# when the soldier gets all the food, we move to the next round
self.roundTrans = True
# allows zombies to kill bots
pygame.sprite.groupcollide(self.botGroup, self.zombieGroup, True,
False)
self.botGroup.update(self.moveBoard, self.zombieGroup,
self.bulletSize, self.bulletGroup, self.nuke, self.penetration,
self.decoy, self.instaKill)
else:
self.nextRound()
def powerUpTimer(self):
if self.penetration:
self.penetrationCount += 1
if (self.penetrationCount == self.penetrationLimit):
self.penetration = False
self.penetrationCount = 0
elif self.invinsibility:
self.invinsibilityCount += 1
if (self.invinsibilityCount == self.invinsibilityLimit):
self.invinsibility = False
self.invinsibilityCount = 0
for soldier in iter(self.soldierGroup):
soldier.updateImage(self.invinsibility)
elif self.speed:
self.speedCount += 1
if (self.speedCount == self.speedLimit):
self.speed = False
self.speedCount = 0
for soldier in iter(self.soldierGroup):
soldier.resetSpeed()
elif self.instaKill:
self.instaKillCount += 1
if (self.instaKillCount == self.instaKillLimit):
self.instaKill = False
self.instaKillCount = 0
elif self.decoy:
self.decoyCount += 1
if (self.decoyCount == self.decoyLimit):
self.decoy = False
self.decoyCount = 0
self.decoyGroup.empty()
def checkPowerUpCollisions(self):
# each statement indicates what happens if a given power up is picked up
if (pygame.sprite.groupcollide(self.soldierGroup, self.nukeGroup, False,
True) or
pygame.sprite.groupcollide(self.botGroup, self.nukeGroup, False, True)):
self.nuke = True
self.zombieGroup.empty()
elif (pygame.sprite.groupcollide(self.soldierGroup,
self.penetrationGroup, False, True) or
pygame.sprite.groupcollide(self.botGroup, self.penetrationGroup, False,
True)):
self.penetration = True
elif (pygame.sprite.groupcollide(self.soldierGroup,
self.invinsibilityGroup, False, True) or
pygame.sprite.groupcollide(self.botGroup, self.invinsibilityGroup,
False, True)):
self.invinsibility = True
for soldier in iter(self.soldierGroup):
soldier.updateImage(self.invinsibility)
elif (pygame.sprite.groupcollide(self.soldierGroup,
self.speedGroup, False, True) or
pygame.sprite.groupcollide(self.botGroup, self.speedGroup,
False, True)):
self.speed = True
for soldier in iter(self.soldierGroup):
soldier.increaseSpeed()
elif (pygame.sprite.groupcollide(self.soldierGroup,
self.instaKillGroup, False, True) or
pygame.sprite.groupcollide(self.botGroup, self.instaKillGroup,
False, True)):
self.instaKill = True
elif (pygame.sprite.groupcollide(self.soldierGroup,
self.decoyPowerUpGroup, False, True) or
pygame.sprite.groupcollide(self.botGroup, self.decoyPowerUpGroup,
False, True)):
self.decoy = True
self.placeDecoy()
def placeDecoy(self):
works = False
while not(works):
works = True
moveBoardRow = random.randint(0, len(self.moveBoard) - 1)
moveBoardCol = random.randint(0, len(self.moveBoard[0]) - 1)
if (self.moveBoard[moveBoardRow][moveBoardCol] == 1):
# prevents the bot from being placed on a wall
works = False
else:
# realRow and realCol are on the grid on which
# the outer blocks lie
realRow = 1 + 2 * moveBoardRow
realCol = 1 + 2 * moveBoardCol
x0Cell, y0Cell = self.getCellTopLeft(realRow, realCol)
x0Decoy, y0Decoy = self.getZombieCoords(x0Cell, y0Cell)
self.decoyPos = (moveBoardRow, moveBoardCol)
self.decoyGroup.add(Decoy(x0Decoy, y0Decoy, self.cellSize))
def spawnPowerUp(self):
# ensures that a power up is spawned only if there aren't any
# other power ups in the map already
if ((len(self.nukeGroup) == 0) and (len(self.penetrationGroup) == 0)
and (len(self.invinsibilityGroup) == 0) and (len(self.speedGroup) == 0)
and (len(self.instaKillGroup) == 0) and
(len(self.decoyPowerUpGroup) == 0)):
self.spawnPowerUpHelper()
def spawnPowerUpHelper(self):
powerUp = random.choice(self.powerUpList)
works = False
while not(works):
works = True
moveBoardRow = random.randint(0, len(self.moveBoard) - 1)
moveBoardCol = random.randint(0, len(self.moveBoard[0]) - 1)
if (self.moveBoard[moveBoardRow][moveBoardCol] == 1):
works = False
else:
# realRow and realCol are on the grid on which
# the outer blocks lie
realRow = 1 + 2 * moveBoardRow
realCol = 1 + 2 * moveBoardCol
x0Cell, y0Cell = self.getCellTopLeft(realRow, realCol)
x0powerUp, y0powerUp = self.getPowerUpCoords(x0Cell,y0Cell)
# one of the following power ups is spawned
if (powerUp == "nuke") and (len(self.nukeGroup) == 0):
self.nukeGroup.add(Nuke(x0powerUp, y0powerUp, self.foodSize,
"nuke"))
elif (powerUp == "penetration") and (len(self.penetrationGroup) == 0):
self.penetrationGroup.add(Penetration(x0powerUp, y0powerUp,
self.foodSize, "penetration"))
elif ((powerUp == "invinsibility") and
(len(self.invinsibilityGroup) == 0)):
self.invinsibilityGroup.add(Invinsibility(x0powerUp, y0powerUp,
self.foodSize, "invinsibility"))
elif (powerUp == "speed") and (len(self.speedGroup) == 0):
self.speedGroup.add(Speed(x0powerUp, y0powerUp,
self.foodSize, "speed"))
elif (powerUp == "instaKill") and (len(self.instaKillGroup) == 0):
self.instaKillGroup.add(InstaKill(x0powerUp, y0powerUp,
self.foodSize, "instaKill"))
elif (powerUp == "decoy") and (len(self.decoyPowerUpGroup) == 0):
self.decoyPowerUpGroup.add(DecoyPowerUp(x0powerUp, y0powerUp,
self.foodSize, "decoyPowerUp"))
def nextRound(self):
self.zombieGroup.empty()
if (len(self.bulletGroup) != 0):
# kills all bullet sprites when round is changing
self.bulletGroup.empty()
if self.nuke:
self.botGroup.empty()
self.roundDelay += 1
self.clearPowerUps()
# delay between moment when round ends and food of the next round
# is placed
if (self.roundDelay == self.roundBegin // 2):
for i in range(self.foodNumber):
self.placeFood()
self.resetPowerUps()
# delay between moment when food spawns and zombies appear
# so the user has time to see where all the food has been placed
elif (self.roundDelay == self.roundBegin):
threshold = 3
thirteen = 13
self.roundDelay = 0
self.round += 1
# the number of zombies and the zombie speed are updated
self.getZombieNum()
self.getZombieSpeed()
if (((self.round > threshold) and
(self.bulletsToKillRange <= (2**2))) or (self.round > thirteen)):
self.bulletsToKillRange += 1
self.roundTrans = False
self.time = 0
minute = 60
self.secs = minute
if (self.coop):
while (len(self.botGroup)!= self.botNum):
self.placeBot()
self.newRound.play()
def resetPowerUps(self):
self.nuke = False
self.invinsibility = False
self.invinsibilityCount = 0
self.penetration = False
self.instaKill = False
self.penetrationCount = 0
self.instaKillCount = 0
self.speed = False
self.speedCount = 0
self.decoy = False
self.decoyCount = 0
def clearPowerUps(self):
self.nukeGroup.empty()
self.penetrationGroup.empty()
self.invinsibilityGroup.empty()
for soldier in iter(self.soldierGroup):
soldier.updateImage(self.invinsibility)
self.speedGroup.empty()
for soldier in iter(self.soldierGroup):
soldier.resetSpeed()
self.instaKillGroup.empty()
self.decoyPowerUpGroup.empty()
self.decoyGroup.empty()
def getZombieNum(self):
# every round, the number of zombies increases by one,
# unless the limit for the number of zombies has been reached
three = 3
if ((self.round > three) and not(self.decreased) and
(self.bulletsToKillRange == 2**2 + 1)):
self.zombieNum = 1
self.decreased = True
if (self.zombieNum < self.zombieMax):
self.zombieNum += 1
def getZombieSpeed(self):
three, four, five, eight = 3, 4, 5, 8
if (self.round <= three):
self.zombieSpeed = 2
elif (self.round > three) and (self.bulletsToKillRange <= 2**2):
self.zombieSpeed = five
if not(self.minDistIncreased):
self.minDistIncreased = True
for bot in iter(self.botGroup):
bot.increaseMinDistanceFromZombToMove()
else:
eight = 8
if (self.round == eight) and not(self.minDistIncreasedSecond):
self.minDistIncreasedSecond = True
for bot in iter(self.botGroup):
# this makes the bot not move if a zombie is within
# a certain distance from it, making the bot less likely to
# collide with a zombie and die
bot.increaseMinDistanceFromZombToMove()
self.zombieSpeed = eight
def gameOver(self):
self.game.mode = GameOver(self.game, self.round)
self.game.init()
def placeZombie(self):
works = False
while not(works):
works = True
moveBoardRow = random.randint(0, len(self.moveBoard) - 1)
moveBoardCol = random.randint(0, len(self.moveBoard[0]) - 1)
if (self.moveBoard[moveBoardRow][moveBoardCol] == 1):
works = False
else:
# realRow and realCol are on the grid on which
# the outer blocks lie
realRow = 1 + 2 * moveBoardRow
realCol = 1 + 2 * moveBoardCol
x0Cell, y0Cell = self.getCellTopLeft(realRow, realCol)
x0Zomb, y0Zomb = self.getZombieCoords(x0Cell,y0Cell)
# this prevents the zombie from spawning too close
# to the soldier, which would make the game too hard
for soldier in iter(self.soldierGroup):
if ((abs(x0Zomb - soldier.rect.left) <
self.spawningZombieLimit) or
(abs(y0Zomb - soldier.rect.top) <
self.spawningZombieLimit)):
works = False
for bot in iter(self.botGroup):
if ((abs(x0Zomb - bot.rect.left) <
self.spawningBotLimit) or
(abs(y0Zomb - bot.rect.top) <
self.spawningBotLimit)):
works = False
typ = "zombie"
maximum = 15
randNum = random.randint(1, maximum)
threshold = 3
if ((self.round > threshold) and (randNum == 1) and
(len(self.zombieGroup) != 0)):
typ = "wallZombie"
zombie = Zombie(1,1,1,1,1,"zombie")
count = 0
# ensures that there is always at least one regular zombie
for zomb in iter(self.zombieGroup):
if type(zomb) == type(zombie):
count += 1
if (count == 0):
typ = "zombie"
if (typ == "wallZombie"):
self.zombieGroup.add(WallZombie(x0Zomb, y0Zomb,
self.cellSize, self.zombieSpeed, self.bulletsToKillRange, typ))
else:
self.zombieGroup.add(Zombie(x0Zomb, y0Zomb,
self.cellSize, self.zombieSpeed, self.bulletsToKillRange, typ))
if pygame.sprite.groupcollide(self.botGroup, self.zombieGroup, False,
True):
self.placeZombie()
def getCellTopLeft(self, row, col):
x0 = (col * self.cellSize) - self.screenX0
y0 = (row * self.cellSize) - self.screenY0
return x0, y0
def getZombieCoords(self, x0Cell, y0Cell):
x0Zomb = x0Cell + self.cellSize * (1/2)
y0Zomb = y0Cell + self.cellSize * (1/2)
return x0Zomb, y0Zomb
def redrawAll(self, screen):
self.drawFloor(screen)
self.blockGroup.draw(screen)
self.drawPowerUps(screen)
self.foodGroup.draw(screen)
self.decoyGroup.draw(screen)
self.zombieGroup.draw(screen)
self.bulletGroup.draw(screen)
self.botGroup.draw(screen)
self.soldierGroup.draw(screen)
self.drawScore(screen)
def drawFloor(self, screen):
for row in range(1, self.rows-1):
for col in range(1, self.cols-1):
x0, y0 = self.getCellTopLeft(row, col)
screen.blit(self.image, (x0, y0))
def drawPowerUps(self, screen):
self.nukeGroup.draw(screen)
self.penetrationGroup.draw(screen)
self.invinsibilityGroup.draw(screen)
self.speedGroup.draw(screen)
self.instaKillGroup.draw(screen)
self.decoyPowerUpGroup.draw(screen)
def drawScore(self, screen):
black = (0, 0, 0)
red = (250, 40, 40)
pygame.draw.rect(screen, black, pygame.Rect(self.scoreBar))
rounds = "Round %s" % self.round
text = self.font.render(rounds, True, red)
left = self.scoreBar[0] + self.cellSize / 2
top = self.cellSize/2**2
screen.blit(text, [left, top])
starv = "Starving in %s" % self.secs
text = self.font.render(starv, True, red)
mult = 13/2
left = self.scoreBar[0] + self.cellSize * mult
top = self.cellSize/2**2
screen.blit(text, [left, top])
class Block(pygame.sprite.Sprite):
def __init__(self, x0, y0, cellSize):
super().__init__()
self.x0, self.y0, self.cellSize = x0, y0, cellSize
self.loadBlockSprite()
def loadBlockSprite(self):
# block image from http://mashthosebuttons.com/review/angry-video-game-
# nerd-adventures-review/
block = pygame.image.load("block.png").convert_alpha()
w, h = self.cellSize, self.cellSize
self.image = pygame.transform.scale(block, (w, h))
self.rect = pygame.Rect(self.x0, self.y0, w,h)
class Soldier(pygame.sprite.Sprite):
def __init__(self, x0, y0, cellSize):
super().__init__()
self.x0, self.y0, self.cellSize = x0, y0, cellSize
self.angle = 0
ratio = 3 / 4
self.loadSoldierSprite()
self.speedX = 0
self.speedY = 0
self.originalSpeed = 8
self.speed = self.originalSpeed
self.fasterSpeed = 20
self.image = self.originalImage
def loadSoldierSprite(self):
# soldier image from
# http://www.2dgameartguru.com/2012/04/top-down-view-soldier.html
soldier = pygame.image.load("soldier.png").convert_alpha()
invinsibleSoldier = (pygame.image.load("invinsibleSoldier.png").
convert_alpha())
w, h = self.cellSize, self.cellSize
self.originalImage = pygame.transform.scale(soldier, (w, h))
self.invinsibleSoldier = pygame.transform.scale(invinsibleSoldier,
(w, h))
self.rect = pygame.Rect(self.x0, self.y0, w, h)
def updateImage(self, invinsibility):
if invinsibility:
self.image = pygame.transform.rotate(self.invinsibleSoldier,
self.angle)
else:
self.image = pygame.transform.rotate(self.originalImage,
self.angle)
# the two functions below are used when the soldier takes the speed
# power up
def resetSpeed(self):
self.speed = self.originalSpeed
def increaseSpeed(self):
self.speed = self.fasterSpeed
def rotate(self, invinsibility):
# the original image is rotated every time, instead of the rotated image
# previously used, so the quality of the image is not lost
if invinsibility:
self.image = pygame.transform.rotate(self.invinsibleSoldier,
self.angle)
else:
self.image = pygame.transform.rotate(self.originalImage,
self.angle)
def getAngle(self):
return self.angle
def getSoldierCenter(self):
halfSize = (self.rect.right- self.rect.left) / 2
x = self.rect.left + halfSize
y = self.rect.top + halfSize
return x, y
def getSoldierCenterRowCol(self):
x, y = self.getSoldierCenter()
row, col = int(y // self.cellSize), int(x // self.cellSize)
return row, col
def direct(self, keyCode, invinsibility):
# moves soldier and rotates image of soldier in direction
# that corresponds to the arrow key pressed
if (keyCode == pygame.K_UP):
self.angle = 0
self.rotate(invinsibility)
self.speedY = -self.speed
self.speedX = 0
elif (keyCode == pygame.K_DOWN):
self.angle = 180
self.rotate(invinsibility)
self.speedY = self.speed
self.speedX = 0
elif (keyCode == pygame.K_LEFT):
self.angle = 90
self.rotate(invinsibility)
self.speedX = -self.speed
self.speedY = 0
elif (keyCode == pygame.K_RIGHT):
self.angle = 270
self.rotate(invinsibility)
self.speedX = self.speed
self.speedY = 0
def stop(self, keyCode):
# when an arrow key is released, the soldier stops moving in
# the direction it was moving
if (keyCode == pygame.K_UP) or (keyCode == pygame.K_DOWN):
self.speedY = 0
elif (keyCode == pygame.K_LEFT) or (keyCode == pygame.K_RIGHT):
self.speedX = 0
def move(self):
self.rect = self.rect.move(self.speedX, self.speedY)
def unmove(self):
# called when the soldier runs into a wall
self.rect = self.rect.move(-self.speedX, -self.speedY)
class Decoy(pygame.sprite.Sprite):
def __init__(self, x0, y0, cellSize):
super().__init__()
self.x0, self.y0, self.cellSize = x0, y0, cellSize
self.loadDecoySprite()
def loadDecoySprite(self):
# decoy image from
# http://www.2dgameartguru.com/2012/04/top-down-view-soldier.html
decoy = pygame.image.load("decoy.png").convert_alpha()
w, h = self.cellSize, self.cellSize
self.image = pygame.transform.scale(decoy, (w, h))
self.rect = pygame.Rect(self.x0, self.y0, w, h)
class Bot(pygame.sprite.Sprite):
def __init__(self, x0, y0, cellSize):
super().__init__()
self.x0, self.y0, self.cellSize = x0, y0, cellSize
self.angle = 0
self.loadBotSprite()
self.speedX = 0
self.speedY = 0
self.speed = 8
self.image = self.originalImage
self.moveCounter = 0
self.count = 0
self.moveLimit = 2 * self.cellSize / self.speed
self.minDistanceFromZombToMove = (((2 * self.cellSize) ** 2 +
(2* self.cellSize) ** 2) ** (1/2))
# gunshot sound from http://soundbible.com/2120-9mm-Gunshot.html
self.gunshot = pygame.mixer.Sound("gunshot.wav")
def increaseMinDistanceFromZombToMove(self):
self.count += 1
if self.count == 1:
self.minDistanceFromZombToMove = (((2**2 * self.cellSize) ** 2 +
(2**2 * self.cellSize) ** 2) ** (1/2))
else:
six = 6
self.minDistanceFromZombToMove = (((six * self.cellSize) ** 2 +
(six * self.cellSize) ** 2) ** (1/2))
def loadBotSprite(self):
# bot image from
# http://www.2dgameartguru.com/2012/04/top-down-view-soldier.html
bot = pygame.image.load("bot.png").convert_alpha()
w, h = self.cellSize, self.cellSize
self.originalImage = pygame.transform.scale(bot, (w, h))
self.rect = pygame.Rect(self.x0, self.y0, w, h)
def getBotCenter(self):
halfSize = (self.rect.right- self.rect.left) / 2
x = self.rect.left + halfSize
y = self.rect.top + halfSize
return x, y
def getBotCenterRowCol(self):
x, y = self.getBotCenter()
row, col = int(y // self.cellSize), int(x // self.cellSize)
return row, col
def getAngle(self, direct):
up, down, left, right = 0, 180, 90, 270
if direct == (1, 0):
return down
elif direct == (-1, 0):
return up
elif direct == (0, 1):
return right
elif direct == (0, -1):
return left
def rotate(self, angle):
self.image = pygame.transform.rotate(self.originalImage, angle)
def getBulletCoords(self, angle, bulletSize):
# function positions bullets in the right place when bot shoots
top, left, right, bottom = 0, 90, 270, 180
offset = self.cellSize // 2
incr = 10
x0, y0 = self.rect.left, self.rect.top
x1, y1 = self.rect.right, self.rect.bottom
if (angle == top):
bulletX0 = x0 + offset
bulletY0 = y0 - bulletSize
elif (angle == right):
bulletX0 = x1
bulletY0 = y0 + offset
elif (angle == left):
bulletX0 = x0 - bulletSize
bulletY0 = y0 + (self.cellSize - offset) - incr
elif (angle == bottom):
bulletX0 = x0 + (self.cellSize - offset) - incr
bulletY0 = y1
return bulletX0, bulletY0
def shoot(self, direct, bulletSize, bulletGroup, penetration, instaKill):
angle = self.getAngle(direct)
# bot image is rotated in the direction the bot is about to shoot
self.rotate(angle)
x0, y0 = self.getBulletCoords(angle, bulletSize)
self.gunshot.play()
bulletGroup.add(Bullet(x0, y0, angle, bulletSize, True,
penetration, instaKill))
def isTooClose(self, zombieGroup, decoy):
# determines whether at least one zombie is within a certain distance
# of the bot
# if a zombie is within a certain distance of the bot, the bot doesn't
# move, which makes it less likely for the bot to collide with the
# zombie and die
xCenter = self.rect.left + self.cellSize / 2
yCenter = self.rect.top + self.cellSize / 2
if not(decoy):
for zomb in iter(zombieGroup):
zombX0, zombY0 = zomb.rect.left, zomb.rect.top
zombCenterX, zombCenterY = (zombX0 + self.cellSize / 2, zombY0 +
self.cellSize / 2)
distance = (((zombCenterX - xCenter)**2 +
(zombCenterY - yCenter)**2)**(1/2))
if (distance < self.minDistanceFromZombToMove):
return True
return False
def update(self, brd, zombieGroup, bulletSize, bulletGroup, nuke,
penetration, decoy, instaKill):
botCenterRowCol = self.getBotCenterRowCol()
botBoardRowCol = (int((botCenterRowCol[0] - 1) // 2),
int((botCenterRowCol[1] - 1) // 2))
board = copy.deepcopy(brd)
# if nuke is True, there are no zombies to shoot
if (self.speedX == 0) and (self.speedY == 0) and not(nuke):
shoot = False
shoot, direct = self.isZombieInRange(botBoardRowCol, board,
zombieGroup, penetration)
# shoot is True if there a zombie in line with the bot
# (without walls in the way)
if shoot == True:
self.shoot(direct, bulletSize, bulletGroup, penetration,
instaKill)
# if nuke is true, there are no zombies for the bot to find
elif not(self.isTooClose(zombieGroup, decoy) or nuke):
moves = self.getMoves(botBoardRowCol, board, zombieGroup)
if moves != None and moves != []:
move = moves[0]
if (move == (-1, 0)):
angle = self.getAngle(move)
self.speedY = -self.speed
self.rotate(angle)
elif (move == (1, 0)):
angle = self.getAngle(move)
self.rotate(angle)
self.speedY = self.speed
elif (move == (0, -1)):
angle = self.getAngle(move)
self.rotate(angle)
self.speedX = -self.speed
elif (move == (0, 1)):
angle = self.getAngle(move)
self.rotate(angle)
self.speedX = self.speed
else:
self.moveCounter += 1
# ensures that bot only shoots or executes the backtracking
# algorithm when it is at an intersection of the grid model
# (the zombies and bots are modelled as moving on a grid)
self.rect = self.rect.move(self.speedX, self.speedY)
if (self.moveCounter == self.moveLimit):
self.speedX, self.speedY, self.moveCounter = 0, 0, 0
def isZombieInRange(self, botBoardRowCol, board, zombieGroup, penetration):
directions = [(-1,0), (1, 0), (0, -1), (0, 1)]
for direct in directions:
# bot checks all directions to determine if there is a zombie it can
# shoot
shoot = self.isZombieInRangeHelper(botBoardRowCol, board,
direct, zombieGroup, penetration)
if shoot != None:
return shoot, direct
return None, None
def isZombieInRangeHelper(self, botBoardRowCol, board, direct, zombieGroup,
penetration):
dRow, dCol = direct[0], direct[1]
botBoardRow, botBoardCol = botBoardRowCol[0], botBoardRowCol[1]
row, col = (botBoardRow + dRow, botBoardCol + dCol)
# we loop through all the cells in the grid, from the bot, in the
# direction direct, until we find a zombie
# if we hit a block the function returns None
# if (row, col) is off the board, the function returns None
while self.isInBoard(row, col, board):
if not(penetration) and (board[row][col] == 1):
break
else:
# realRow and realCol are on the grid on which
# the outer blocks lie
realRow = 1 + 2 * row
realCol = 1 + 2 * col
incr = self.cellSize / (2*2)
x0 = realCol * self.cellSize + incr
y0 = realRow * self.cellSize + incr
x1 = x0 + 2 * self.cellSize - incr
y1 = y0 + 2 * self.cellSize - incr
for zomb in iter(zombieGroup):
zombX0, zombY0 = zomb.rect.left, zomb.rect.top
zombX1, zombY1 = zomb.rect.right, zomb.rect.bottom
# the two lines of code below are from my 15-112 lab 1
# problem 2
# they check whether or not a given cell collides with
# any zombie in the zombieGroup
if (((x0 <= zombX0 <= x1) or (zombX0 <= x0 <= zombX1)) and
((y0 <= zombY0 <= y1) or (zombY0 <= y0 <= zombY1))):
return True
row, col = (row + dRow, col + dCol)
return None
def isInBoard(self, row, col, board):
rows, cols = len(board), len(board[0])
return not((row < 0) or (col < 0) or (row >= rows) or (col >= cols))
def getCenterPointRowCol(self, row, col):
x = (col + 1) * self.cellSize
y = (row + 1) * self.cellSize
return x, y
def getClosestZombieRowCol(self, zombieGroup):
zomb = self.getClosestZombie(zombieGroup)
if zomb == None:
return None, None
zombieRowCol = zomb.getZombieRowCol()
return zombieRowCol
def getClosestZombie(self, zombieGroup):
# finds the zombie closest to the bot
closestZomb = None
closestZombDist = None
zombie = Zombie(1,1,1,1,1,"zombie")
for zomb in iter(zombieGroup):
if type(zomb) == type(zombie):
# this ensures that the bot only finds regular zombies
# and not wall zombies
# we don't want the bot to find wall zombies because
# they are not always at a legal location for the bot
# (in the walls)
# the bots can still detect and shoot wall zombies
distance = self.getDistance(zomb)
if closestZomb == None:
closestZomb = zomb
closestZombDist = distance
elif (distance < closestZombDist):
closestZomb = zomb
closestZombDistance = distance
return closestZomb
def getDistance(self, zomb):
zombX0, zombY0 = zomb.rect.left, zomb.rect.top
botX0, botY0 = self.rect.left, self.rect.top
distance = ((zombX0 - botX0) ** 2 + (zombY0 - botY0) ** 2)**(1/2)
return distance
def getMoves(self, botLoc, brd, zombieGroup):
board = copy.deepcopy(brd)
zombRow, zombCol = self.getClosestZombieRowCol(zombieGroup)
if (zombRow, zombCol) == (None, None):
return None
zombieLoc = ((zombRow - 1)//2, (zombCol - 1)//2)
# in the backtracking algorithm, the bot tries to find a path
# leading to the closest zombie
directions = [(-1,0), (1, 0), (0, -1), (0, 1)]
moves = []
def getDirectionList(zombieLoc, botLoc):
# functon returns a list with directions in order of priority
# that the backtracking algorithm should check
# line below finds the direction of the zombie from the
# bot's location
direct = getDirection(zombieLoc, botLoc)
if direct == (1,1):
first = [(1,0),(0,1)]
rest = [(-1,0),(0,-1)]
randInd = random.randint(0,1)
directionList = [first[randInd], first[abs(randInd-1)],
rest[randInd], rest[abs(randInd-1)]]
elif direct == (-1,1):
first = [(-1,0),(0,1)]
rest = [(1,0),(0,-1)]
randInd = random.randint(0,1)
directionList = [first[randInd], first[abs(randInd-1)],
rest[randInd], rest[abs(randInd-1)]]
elif direct == (-1,-1):
first = [(-1,0),(0,-1)]
rest = [(1,0), (0,1)]
randInd = random.randint(0,1)
directionList = [first[randInd], first[abs(randInd-1)],
rest[randInd], rest[abs(randInd-1)]]
elif direct == (1,-1):
first = [(1,0),(0,-1)]
rest = [(-1,0),(0,1)]
randInd = random.randint(0,1)
directionList = [first[randInd], first[abs(randInd-1)],
rest[randInd], rest[abs(randInd-1)]]
elif direct == (1,0):
rest = [(0,-1),(0,1),(-1,0)]
randInd = random.randint(0,1)
directionList = [(1,0)]+ [rest[randInd], rest[abs(randInd-1)]]
elif direct == (-1,0):
rest = [(0,-1),(0,1),(1,0)]
randInd = random.randint(0,1)
directionList = [(-1,0)]+[rest[randInd], rest[abs(randInd-1)]]
elif direct == (0,1):
rest = [(1,0),(-1,0),(0,-1)]
randInd = random.randint(0,1)
directionList = [(0,1)]+ [rest[randInd], rest[abs(randInd-1)]]
elif direct == (0,-1):
rest = [(1,0),(-1,0),(0,1)]
randInd = random.randint(0,1)
directionList = [(0,-1)]+[rest[randInd], rest[abs(randInd-1)]]
return directionList
def getDirection(zombieLoc, botLoc):
moveVector = (zombieLoc[0]-botLoc[0], zombieLoc[1]-botLoc[1])
moveVectorX = moveVector[0]
moveVectorY = moveVector[1]
if moveVectorX != 0:
unitVectorX = int(moveVectorX / abs(moveVectorX))
else:
unitVectorX = 0
if moveVectorY != 0:
unitVectorY = int(moveVectorY / abs(moveVectorY))
else:
unitVectorY = 0
return (unitVectorX, unitVectorY)
def isLegal(row, col):
if ((row < 0 ) or (col < 0) or (row >= len(board)) or
(col >= len(board[0]))):
return False
else:
return (board[row][col] == -1)
def solve(botLoc):
if (botLoc == zombieLoc):
return moves
else:
# directions are ordered in order of priority that are
# most likely to be in the direction of the soldier
# ordering the directions to loop through optimizes the
# efficiency of the function
directions = getDirectionList(zombieLoc, botLoc)
for direct in range(len(directions)):
drow, dcol = directions[direct]
pRow, pCol = (botLoc[0] + drow), (botLoc[1] + dcol)
if isLegal(pRow, pCol):
moves.append(directions[direct])
board[pRow][pCol] = 0
solution = solve((pRow, pCol))
if solution != None:
return solution
moves.pop()
board[pRow][pCol] = -1
return None
return solve(botLoc)
class Zombie(pygame.sprite.Sprite):
def __init__(self, x0, y0, cellSize, zombieSpeed, bulletsToKillRange, typ):
super().__init__()
self.x0, self.y0, = x0, y0
self.cellSize = cellSize
self.typ = typ
self.loadZombieSprite()
self.image = self.originalImage
self.speed = zombieSpeed
self.speedX = 0
self.speedY = 0
self.moveCounter = 0
self.moveLimit = 2 * self.cellSize / self.speed
self.bulletsToKillRange = bulletsToKillRange
# self.life is the number of bullets a zombie will require
# to be killed
self.life = random.randint(1, self.bulletsToKillRange)
def loadZombieSprite(self):
# zombie image from
# https://opengameart.org/content/animated-top-down-zombie
angle = 90
x = "%s.png" % self.typ
zombie = pygame.image.load("%s.png" % self.typ).convert_alpha()
w, h = self.cellSize, self.cellSize
zombie = pygame.transform.scale(zombie, (w, h))
self.originalImage = pygame.transform.rotate(zombie, angle)
self.rect = pygame.Rect(self.x0, self.y0, w, h)
def damage(self):
self.life -= 1
if self.life <= 0:
self.kill()
def getZombieRowCol(self):
halfSize = (self.rect.left - self.rect.right) / 2
x = self.rect.left + halfSize
y = self.rect.top + halfSize
row, col = int(y // self.cellSize), int(x // self.cellSize)
return row, col
def rotate(self, angle):
self.image = pygame.transform.rotate(self.originalImage, angle)
def update(self, soldierBoardRowCol, brd, soldierCoords, decoy, decoyPos):
board = copy.deepcopy(brd)
if (self.speedX == 0) and (self.speedY == 0):
moves = self.getMoves(soldierBoardRowCol, board, decoy, decoyPos)
if moves != None and moves != []:
move = moves[0]
if (move == (-1, 0)):
angle = 0
self.speedY = -self.speed
self.rotate(angle)
elif (move == (1, 0)):
angle = 180
self.rotate(angle)
self.speedY = self.speed
elif (move == (0, -1)):
angle = 90
self.rotate(angle)
self.speedX = -self.speed
elif (move == (0, 1)):
angle = 270
self.rotate(angle)
self.speedX = self.speed
else:
self.moveCounter += 1
# ensures that zombie only executes the backtracking
# algorithm when it is at an intersection of the grid model
# (the zombies and bots are modelled as moving on a grid)
self.rect = self.rect.move(self.speedX, self.speedY)
if (self.moveCounter == self.moveLimit):
self.speedX, self.speedY, self.moveCounter = 0, 0, 0
def getMoves(self, soldierLoc, brd, decoy, decoyPos):
board = copy.deepcopy(brd)
zombRow, zombCol = self.getZombieRowCol()
zombieLoc = ((zombRow - 1)//2, (zombCol - 1)//2)
if decoy:
soldierLoc = decoyPos
directions = [(-1,0), (1, 0), (0, -1), (0, 1)]
moves = []
def getDirectionList(soldierPos, zombiePos):
# functon returns a list with directions in order of priority
# that the backtracking algorithm should check
# line below finds the direction of the soldier from the
# zombie's location
direct = getDirection(soldierPos, zombiePos)
if direct == (1,1):
first = [(1,0),(0,1)]
rest = [(-1,0),(0,-1)]
randInd = random.randint(0,1)
directionList = [first[randInd], first[abs(randInd-1)],
rest[randInd], rest[abs(randInd-1)]]
elif direct == (-1,1):
first = [(-1,0),(0,1)]
rest = [(1,0),(0,-1)]
randInd = random.randint(0,1)
directionList = [first[randInd], first[abs(randInd-1)],
rest[randInd], rest[abs(randInd-1)]]
elif direct == (-1,-1):
first = [(-1,0),(0,-1)]
rest = [(1,0), (0,1)]
randInd = random.randint(0,1)
directionList = [first[randInd], first[abs(randInd-1)],
rest[randInd], rest[abs(randInd-1)]]
elif direct == (1,-1):
first = [(1,0),(0,-1)]
rest = [(-1,0),(0,1)]
randInd = random.randint(0,1)
directionList = [first[randInd], first[abs(randInd-1)],
rest[randInd], rest[abs(randInd-1)]]
elif direct == (1,0):
rest = [(0,-1),(0,1),(-1,0)]
randInd = random.randint(0,1)
directionList = [(1,0)]+ [rest[randInd], rest[abs(randInd-1)]]
elif direct == (-1,0):
rest = [(0,-1),(0,1),(1,0)]
randInd = random.randint(0,1)
directionList = [(-1,0)]+[rest[randInd], rest[abs(randInd-1)]]
elif direct == (0,1):
rest = [(1,0),(-1,0),(0,-1)]
randInd = random.randint(0,1)
directionList = [(0,1)]+ [rest[randInd], rest[abs(randInd-1)]]
elif direct == (0,-1):
rest = [(1,0),(-1,0),(0,1)]
randInd = random.randint(0,1)
directionList = [(0,-1)]+[rest[randInd], rest[abs(randInd-1)]]
return directionList
def getDirection(soldierPos, zombiePos):
moveVector = (soldierPos[0]-zombiePos[0],soldierPos[1]-zombiePos[1])
moveVectorX = moveVector[0]
moveVectorY = moveVector[1]
if moveVectorX != 0:
unitVectorX = int(moveVectorX / abs(moveVectorX))
else:
unitVectorX = 0
if moveVectorY != 0:
unitVectorY = int(moveVectorY / abs(moveVectorY))
else:
unitVectorY = 0
return (unitVectorX, unitVectorY)
def isLegal(row, col):
if ((row < 0 ) or (col < 0) or (row >= len(board)) or
(col >= len(board[0]))):
return False
else:
return (board[row][col] == -1)
def solve(zombLoc):
if (zombLoc == soldierLoc):
return moves
else:
# directions are ordered in order of priority that are
# most likely to be in the direction of the soldier
# ordering the directions to loop through optimizes the
# efficiency of the function
directions = getDirectionList(soldierLoc, zombLoc)
for direct in range(len(directions)):
drow, dcol = directions[direct]
pRow, pCol = (zombLoc[0] + drow), (zombLoc[1] + dcol)
if isLegal(pRow, pCol):
moves.append(directions[direct])
board[pRow][pCol] = 0
solution = solve((pRow, pCol))
if solution != None:
return solution
moves.pop()
board[pRow][pCol] = -1
return None
return solve(zombieLoc)
class WallZombie(Zombie):
def __init__(self, x0, y0, cellSize, zombieSpeed, bulletsToKillRange, typ):
super().__init__(x0, y0, cellSize, zombieSpeed, bulletsToKillRange, typ)
# so the components combined make the resultant speed the same
# as self.speed
self.diagSpeed = self.speed * (2)**(1/2) / 2
mult = 3
self.moveCounter = mult * self.moveCounter
# wallZombie image from
# https://www.pinterest.com/pin/349943833527272089/
def getCellTopLeft(self, row, col):
x0 = (col * self.cellSize)
y0 = (row * self.cellSize)
return x0, y0
def update(self, soldierBoardRowCol, brd, soldierPos, decoy, decoyPos):
if (self.speedX == 0) and (self.speedY == 0):
zombiePos = (self.rect.left + self.cellSize/2, self.rect.top +
self.cellSize/2)
if decoy:
realRow = 1 + 2 * decoyPos[0]
realCol = 1 + 2 * decoyPos[1]
x0Cell, y0Cell = self.getCellTopLeft(realRow, realCol)
soldierPos = (x0Cell + self.cellSize), (y0Cell + self.cellSize)
direct = self.getDirection(soldierPos, zombiePos)
if (direct == (1, 1)):
angle = 225
self.speedX = self.diagSpeed
self.speedY = self.diagSpeed
self.rotate(angle)
elif (direct == (-1, 1)):
angle = 315
self.speedX = self.diagSpeed
self.speedY = -self.diagSpeed
self.rotate(angle)
elif (direct == (1, -1)):
angle = 135
self.speedX = -self.diagSpeed
self.speedY = self.diagSpeed
self.rotate(angle)
elif (direct == (-1, -1)):
angle = 45
self.speedX = -self.diagSpeed
self.speedY = -self.diagSpeed
self.rotate(angle)
elif (direct == (-1, 0)):
angle = 0
self.speedX = 0
self.speedY = -self.speed
self.rotate(angle)
elif (direct == (1, 0)):
angle = 180
self.rotate(angle)
self.speedX = 0
self.speedY = self.speed
elif (direct == (0, -1)):
angle = 90
self.rotate(angle)
self.speedX = -self.speed
self.speeY = 0
elif (direct == (0, 1)):
angle = 270
self.rotate(angle)
self.speedX = self.speed
self.speedY = 0
self.rect = self.rect.move(int(self.speedX), int(self.speedY))
else:
self.moveCounter += 1
self.rect = self.rect.move(self.speedX, self.speedY)
self.x0 += self.speedX
self.y0 += self.speedY
if (self.moveCounter == self.moveLimit):
self.speedX, self.speedY, self.moveCounter = 0, 0, 0
def getDirection(self, soldierPos, zombiePos):
moveVector = (soldierPos[0]-zombiePos[0],soldierPos[1]-zombiePos[1])
moveVectorX = moveVector[0]
moveVectorY = moveVector[1]
if (abs(moveVectorX) < self.cellSize/2):
unitVectorX = 0
else:
unitVectorX = int(moveVectorX / abs(moveVectorX))
if (abs(moveVectorY) < self.cellSize/2):
unitVectorY = 0
else:
unitVectorY = int(moveVectorY / abs(moveVectorY))
return (unitVectorY, unitVectorX)
class Bullet(pygame.sprite.Sprite):
def __init__(self, x0, y0, angle, bulletSize, botBullet, penetration,
instaKill):
super().__init__()
self.x0 = x0
self.y0 = y0
self.bulletSize = bulletSize
self.angle = angle
self.speed = 40
self.speedX, self.speedY = self.getSpeeds()
self.botBullet = botBullet
self.penetration = penetration
self.instaKill = instaKill
self.loadBulletSprite()
def loadBulletSprite(self):
# bullet image from
# https://code.tutsplus.com/tutorials/build-a-stage3d-shoot-em-up-
# interaction--active-11054
if self.penetration:
bullet = pygame.image.load("penetrationBullet.png").convert_alpha()
elif self.instaKill:
bullet = pygame.image.load("instaKillBullet.png").convert_alpha()
elif self.botBullet:
bullet = pygame.image.load("botBullet.png").convert_alpha()
else:
bullet = pygame.image.load("bullet.png").convert_alpha()
bullet = pygame.transform.scale(bullet, (self.bulletSize,
self.bulletSize))
self.image = pygame.transform.rotate(bullet, self.angle)
self.rect = pygame.Rect(self.x0, self.y0, self.bulletSize,
self.bulletSize)
def getSpeeds(self):
up, down, left, right = 0, 180, 90, 270
if (self.angle == up):
self.speedX = 0
self.speedY = -self.speed
elif (self.angle == down):
self.speedX = 0
self.speedY = self.speed
elif (self.angle == left):
self.speedX = -self.speed
self.speedY = 0
elif (self.angle == right):
self.speedX = self.speed
self.speedY = 0
return self.speedX, self.speedY
def update(self):
self.rect = self.rect.move(self.speedX, self.speedY)
class Food(pygame.sprite.Sprite):
def __init__(self, x0, y0, foodSize):
super().__init__()
self.x0 = x0
self.y0 = y0
self.foodSize = foodSize
self.loadSprite()
def loadSprite(self):
# food image from
# https://www.gamedevmarket.net/asset/fruits-pack-6027/
food = pygame.image.load("food.png").convert_alpha()
w, h = self.foodSize, self.foodSize
self.image = pygame.transform.scale(food, (w, h))
self.rect = pygame.Rect(self.x0, self.y0, w,h)
class PowerUp(pygame.sprite.Sprite):
def __init__(self, x0, y0, size, typ):
super().__init__()
self.x0 = x0
self.y0 = y0
self.size = size
self.typ = typ
self.loadSprite()
def loadSprite(self):
fileName = "%s.png" % self.typ
powerUp = pygame.image.load(fileName).convert_alpha()
w, h = self.size, self.size
self.image = pygame.transform.scale(powerUp, (w, h))
self.rect = pygame.Rect(self.x0, self.y0, w,h)
class Nuke(PowerUp):
def __init__(self, x0, y0, nukeSize, typ):
super().__init__(x0, y0, nukeSize, typ)
# nuke image from https://www.shutterstock.com/image-vector/set-vector-
#icons-radiation-hazardnuclear-135299120?src=Uh5xW6FIA8UGBQalWRlqLA-1-3
class Penetration(PowerUp):
def __init__(self, x0, y0, nukeSize, typ):
super().__init__(x0, y0, nukeSize, typ)
# penetration image from
# http://callofduty.wikia.com/wiki/Weapon_Proficiency
class Invinsibility(PowerUp):
def __init__(self, x0, y0, nukeSize, typ):
super().__init__(x0, y0, nukeSize, typ)
# invinsibility image from
# https://forum.blockland.us/index.php?topic=227785.0
class Speed(PowerUp):
def __init__(self, x0, y0, nukeSize, typ):
super().__init__(x0, y0, nukeSize, typ)
# speed image from
# http://cyrildavies.weebly.com/home/archives/03-2014
class InstaKill(PowerUp):
def __init__(self, x0, y0, nukeSize, typ):
super().__init__(x0, y0, nukeSize, typ)
# instaKill image from
# https://www.youtube.com/watch?v=UmqPbQpRcfQ
class DecoyPowerUp(PowerUp):
def __init__(self, x0, y0, nukeSize, typ):
super().__init__(x0, y0, nukeSize, typ)
# decoy power up image from
# http://www.rw-designer.com/icon-detail/5211
class GameOver(Mode):
def __init__(self, game, rnd):
super().__init__(game)
self.width, self.height = self.game.width, self.game.height
self.round = rnd
size = 100
self.gameOverFont = pygame.font.SysFont(None, size, True)
size = 40
self.roundsFont = pygame.font.SysFont(None, size, True)
self.white = (204, 195, 195)
def init(self):
self.counter = 0
self.time = 120
self.loadBackgroundImage()
def loadBackgroundImage(self):
# background image from http://www.meristation.com/noticias/la-historia
# -de-call-of-duty-zombies-acabara-con-el-proximo-dlc/2139143
background = pygame.image.load("background.png").convert_alpha()
w, h = self.width, self.height
self.background = pygame.transform.scale(background, (w, h))
def mousePressed(self, x, y):
pass
def keyPressed(self, keyCode, modifier):
pass
def keyReleased(self, keyCode, modifier):
pass
def timerFired(self, dt):
self.counter += 1
# the gameover screen is displayed for a certain amount of time
if (self.counter == self.time):
self.game.mode = StartGame(self.game)
self.game.init()
def redrawAll(self, screen):
screen.blit(self.background, (0, 0))
self.drawGameOver(screen)
self.drawRounds(screen)
def drawGameOver(self, screen):
xRatio, yRatio = (1/3), (1/3)
text = "Game Over"
text = self.gameOverFont.render(text, True, self.white)
left, top = (xRatio * self.width), (yRatio * self.height)
screen.blit(text, [left, top])
def drawRounds(self, screen):
xRatio, yRatio = (9/24), (38/75)
incr = 18
if (self.round == 1):
text = "You Survived 1 Round"
else:
text = "You Survived %s Rounds" % self.round
text = self.roundsFont.render(text, True, self.white)
left, top = (xRatio * self.width - incr), (yRatio * self.height)
screen.blit(text, [left, top])
def runGame():
ratio = 8/15
width = 1200
height = int(width * ratio)
Game(width, height).run()
runGame() |
a25fb1ff8655cf4287abdaea6ad93841729991f2 | adqz/interview_practice | /algo_expert/p32_find_nth_node_from_end.py | 1,587 | 3.921875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
def generate_linked_list_from_iterable(iterable, visualize = False):
if not iterable:
return None
for i, val in enumerate(iterable):
if i == 0:
head = Node(val)
curr = head
else:
curr.next = Node(val)
curr = curr.next
if visualize:
print_linked_list(head)
return head
def print_linked_list(head):
curr = head
while curr:
print(curr.data, '-> ', end='')
curr = curr.next
print('None')
def find_nth_from_last(head, n):
# 1. Set slow and fast pointer at index 0 and n in linked list
slow = head
counter = 0
while head and head.next and counter < n:
head = head.next
counter += 1
# Edge Case: If length of linked list is < n
if counter < n:
return None
else:
fast = head
# 2. Move slow and fast until fast reaches last node. Return slow at this point as it is n nodes away
while fast != None:
fast = fast.next
slow = slow.next
return slow
if __name__ == "__main__":
head = generate_linked_list_from_iterable([1,4,2], True)
ans = find_nth_from_last(head, 1)
print(ans.data)
print()
head = generate_linked_list_from_iterable([4,1,4,2], True)
ans = find_nth_from_last(head, 2)
print(ans.data)
print()
head = generate_linked_list_from_iterable([1,2,3,4,5,6], True)
ans = find_nth_from_last(head, 4)
print(ans.data)
print() |
fc7f8008b297d1528997bead2ffdba050bc6ecd9 | efoppiano/ballenato | /ordenar.py | 8,450 | 3.921875 | 4 | """
Modulo que recibe los programas de la aplicacion analizada y ordena las
funciones alfabeticamente, y las guarda en la carpeta "funciones".
"""
import os
from universales import obtener_comentario_multilinea
import re
#Variables que se usan a lo largo del programa
CARPETA_FUNCIONES_ORDENADAS = "funciones"
COMILLAS_DOBLES = chr(34) * 3
COMILLAS_SIMPLES = chr(39) * 3
TAM_TABULACION = 4
def leer_unificado(arch):
"""
[Autor: Elian Daniel Foppiano]
[Ayuda: Lee una linea del archivo y la devuelve convirtiendo las
comillas triples simples en comillas triples dobles y las
tabulaciones por 4 espacios.]
"""
"""
Parametros
----------
arch : archivo, modo lectura
Returns
-------
str
Siguiente linea de arch, con los caracteres convertidos
"""
"""
Esta funcion simplifica el problema del
parseo de funciones, ya que si se mantuvieran
las tabulaciones y las comillas simples, en cada
verificacion deberian considerarse todas las
posibilidades. Otra ventaja es que, al momento
de imprimir el codigo de una aplicacion, es una
buena practica que todas las funciones apliquen un
mismo criterio para este tipo de cuestiones. Pero
de no ser asi, la funcion lo soluciona
"""
linea = arch.readline()
#Si no es una linea en blanco, le agrego
#el salto de linea al final si no tiene (linea final)
if linea:
linea = linea.rstrip() + "\n"
linea = linea.replace(COMILLAS_SIMPLES, COMILLAS_DOBLES)
linea = linea.replace("\t", " " * TAM_TABULACION)
return linea
def buscar_invocacion(dir_archivo):
"""
[Autor: Elian Daniel Foppiano]
[Ayuda: Devuelve la primera invocacion a funcion que encuentre en
el programa y que se realice por fuera de cualquier bloque de
funcion (funcion principal del programa)]
"""
"""
Precondiciones
--------------
El archivo al que hace referencia dir_arch debe contener al menos
una invocacion a funcion
Parametros
----------
dir_archivo : str
Ruta de acceso del programa en el cual se debe buscar la
invocacion a funcion
Returns
-------
str
Nombre de la primera funcion que se invoca en el bloque
principal del programa
"""
"""
Para la creacion del arbol de invocaciones es
fundamental que exista una funcion principal.
Si no existe, no se cumplen las hipotesis iniciales
y el programa responderia de manera incorrecta
"""
invocacion = None
with open(dir_archivo) as arch:
linea = arch.readline()
while linea and not invocacion:
#Salteo los comentarios multilinea
#para evitar falsos positivos
if linea.startswith((COMILLAS_SIMPLES, COMILLAS_DOBLES)):
obtener_comentario_multilinea(linea, arch)
"""
Busco la posible invocacion
con una expresion regular.
Debe ser una palabra que no este
precedida por espacios en blanco, y
seguida de un parentesis abierto
"""
invocacion = re.findall(r"^\w*\(", linea)
linea = arch.readline()
#Me aseguro de que se encontro la funcion principal,
#de lo contrario, el programa termina
assert invocacion != [], "Error: No se encontro una funcion principal."
#Devuelvo la invocacion sin el parentesis final
invocacion = invocacion[0][:-1]
return invocacion
def listar_funciones_codigo(arch_entrada, principal):
"""
[Autor: Elian Daniel Foppiano]
[Ayuda: Crea una lista en el que cada elemento es el codigo de una
funcion definida en arch_entrada. Devuelve la lista ordenada
alfabeticamente por nombre de la funcion. Si la funcion principal
se encuentra en arch_entrada, se le agrega el marcador principal.]
"""
"""
Parametros
----------
arch_entrada : archivo, modo lectura
principal : str
Nombre de la funcion a la que se le debe agregar el
marcador
Returns
-------
lista de str
Cada str contiene la firma y codigo de una funcion. La
lista esta ordenada alfabeticamente por los nombres de las
funciones
"""
funciones = []
linea = leer_unificado(arch_entrada)
while linea:
#Salteo los comentarios multilinea
#que estan por fuera de cualquier
#funcion, para evitar falsos positivos
if linea.startswith((COMILLAS_SIMPLES, COMILLAS_DOBLES)):
obtener_comentario_multilinea(linea, arch_entrada)
linea = leer_unificado(arch_entrada)
elif linea.startswith("def "):
#Si la funcion es la principal,
#la guardo con el marcador
if linea[4:linea.find("(")] == principal:
funcion = "def $" + linea[4:]
else: funcion = linea
linea = leer_unificado(arch_entrada)
#Mientras se siga en la funcion,
#copio las lineas
while linea.startswith((" ", "\n")):
#Guardo la linea si no esta en blanco
if linea.strip(): funcion += linea
linea = leer_unificado(arch_entrada)
#Agrego la funcion a la lista de funciones
funciones.append(funcion)
#No es un comienzo de funcion
#ni un comentario multilinea
else:
linea = leer_unificado(arch_entrada)
#Ordeno las funciones segun la primera
#linea de cada una (firma), reemplazando
#el marcador en la funcion principal
funciones.sort(key = lambda funcion: funcion.split("\n")[0].replace("$", ""))
return funciones
def generar_dir(dir_arch, carpeta, extension):
"""
[Autor: Elian Daniel Foppiano]
[Ayuda: Recibe la ruta de acceso de un programa y devuelve la ruta
de un archivo del mismo nombre que se encuentra en la carpeta
indicada, con la extension recibida como parametro.]
"""
"""
Parametros
----------
dir_arch : str
Ruta del archivo
carpeta : str
Ruta de la carpeta en la que se quiere generar el archivo
extension : str
Extension con la que debe guardarse el archivo, sin el "."
Returns
-------
str
Ruta del archivo que se encuentra en la carpeta indicada
"""
nombre_python = os.path.basename(dir_arch)
#Elimino la extension
nombre_sin_extension = nombre_python[:nombre_python.find(".")]
nombre_archivo = nombre_sin_extension + f".{extension}"
dir_arch = os.path.join(carpeta, nombre_archivo)
return dir_arch
def eliminar_archivos_viejos(carpeta):
"""
[Autor: Elian Daniel Foppiano]
[Ayuda: Elimina los archivos de la carpeta recibida.]
"""
"""
Parametros
----------
carpeta : str
Ruta de la carpeta de la cual se quieren eliminar los
archivos
"""
path_arch_viejos = os.listdir(carpeta)
for path in path_arch_viejos:
path_abs = os.path.join(carpeta, path)
os.remove(path_abs)
def generar_arch_ordenados(programas):
"""
[Autor: Elian Daniel Foppiano]
[Ayuda: Genera los archivos con las funciones ordenadas
alfabeticamente y las guarda en la carpeta "funciones".]
"""
"""
Parametros
----------
programas : archivo, modo lectura
Contiene las rutas de los programas de la aplicacion que
se quiere ordenar
"""
#Elimino los archivos viejos para que
#no interfieran en el analisis actual
eliminar_archivos_viejos(CARPETA_FUNCIONES_ORDENADAS)
#Busco la funcion principal para
#poder agregarle el marcador
dir_programa_principal = programas.readline().rstrip()
principal = buscar_invocacion(dir_programa_principal)
programas.seek(0)
#Recorro la lista de programas
modulo = programas.readline().rstrip()
while modulo:
#Genero la ruta del archivo
#de reemplazo (carpeta "funciones")
copia = generar_dir(modulo, CARPETA_FUNCIONES_ORDENADAS, "txt")
with open(modulo) as entrada, open(copia, "w") as salida:
#Genero una lista de cadenas que
#contienen el codigo de las funciones
l_funciones = listar_funciones_codigo(entrada, principal)
#Copio las cadenas en el archivo
#de reemplazo
for funcion in l_funciones:
salida.write(funcion)
modulo = programas.readline().rstrip() |
6b22adfb04db88227df162667a2bc6b640ae2426 | Mukito/pythonProject | /desafio034.py | 345 | 3.671875 | 4 | sal = float(input('Digite o valor do seu Salario R$ '))
if (sal > 1250):
au10 = (sal * 10) /100
t1 = sal + au10
print('Aumento de 10%, no valor de R${:.2f}, total = R${:.2f}'.format(au10, t1))
else:
au15 = (sal * 15) /100
t2 = sal + au15
print('Aumento de 15%, no valor de R${:.2f}, total = R${:.2f} '.format(au15, t2)) |
7f52d8f406301ac1eb80fb98d5c1687c934a919a | Shuailong/Leetcode | /solutions/reverse-integer.py | 1,206 | 3.84375 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
reverse-integer.py
Created by Shuailong on 2016-01-15.
https://leetcode.com/problems/reverse-integer/.
"""
'''
Note1: Python sys.maxint = 2**64-1
Note2: Solution and Solution1 are both accepted. Solution is quicker.
'''
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
neg = False
if x < 0:
x = -x
neg = True
s = str(x)[::-1]
if neg:
s = '-' + s
s = int(s)
MAX = 2**31-1
if s > MAX or s < -MAX:
return 0
return s
class Solution1(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
MAX = 2**31-1
res = 0
neg = False
if x < 0:
x = -x
neg = True
while x != 0:
res = res * 10 + x % 10
x /= 10
if neg:
res = -res
if res > MAX or res < -MAX-1:
return 0
return res
def main():
solution = Solution()
print solution.reverse(-123456789)
if __name__ == '__main__':
main()
|
0869cc92817463cb24aad89de27f963781420a31 | moreirafelipe/univesp-alg-progamacao | /S5/V2/exercicio2.py | 454 | 3.515625 | 4 | def quick_sort(v,ini,fim):
meio = (ini + fim) // 2
pivo = v[meio]
i = ini
j = fim
while i < j:
while v[i] < pivo:
i += 1
while v[j] > pivo:
j -= 1
if i <= j:
v[i], v[j] = v[j], v[i]
i += 1
j -= 1
if j > ini:
quick_sort(v, ini, j)
if i < fim:
quick_sort(v,i,fim)
return v
v = [22,33,35,12,37,86,92,57]
ini = 0
fim = len(v)-1 |
a66db743b99c3a8b850fba84c8b8266db22a09e1 | sbgonenc/Origins | /Assignments/HW4.3.py | 1,126 | 3.53125 | 4 | genelist = ['GPR139 ', 'YAP1', 'RASGEF1B', 'PAH', 'PLCB2', 'GAPDH', 'SST']
lengthlist = [1613, 2393, 2277, 4122, 4616, 1875, 618]
def gene_dict():
dictionary = {}
for idx, genes in enumerate(genelist):
dictionary[genes] = int(lengthlist[idx])
return dictionary
#print(gene_dict())
def compare(num):
mkeys = []
toplam = 0
value_input = num
for keys in gene_dict():
if gene_dict()[keys] > value_input:
mkeys.append(keys)
toplam += gene_dict()[keys]
return mkeys, toplam
def interface():
command = input("Please enter a length (Type \'exit\' to quit)\n")
if command.isnumeric():
if int(command) <= 0:
print("Not a valid length!")
return interface()
num = int(command)
genes, sums= compare(num)[0], compare(num)[1]
if genes == []:
print("There is no gene which is that long")
return interface()
print("Genes whose length is greater than {} are".format(num))
for each in genes:
print(each)
print("The sums of these genes are ", sums)
return interface()
elif command.upper() == "EXIT":
return None
else:
print("Couldn't recognize the input.")
return interface()
interface() |
b8cbcdf59e74e9b27d9f948b4de0f36eba637737 | HughesZhang73/Python-Master | /Python-Interview-Leetcode/JZ-offer/JZ-05.py | 969 | 3.90625 | 4 | # coding=utf-8
from typing import List
# # 做法1:列表复制
#
# class Solution:
#
# def replaceSpace(self, s: str) -> str:
# for i in s:
# temp.append(i)
# for i in temp:
# if i == ' ':
# temp_index = temp.index(' ')
# temp.remove(i)
# temp.insert(temp_index, '%20')
# for i in temp:
# ans += i
# return ans
# 做法二:使用双指针进行列表的复制
class Solution:
def replaceSpace(self, s: str) -> str:
temp = ''
for i in range(len(s)):
if s[i] == ' ':
temp += '%20'
else:
temp += s[i]
return temp
#
# # 解法三:线性自己遍历赋值
# class Solution:
# def replaceSpace(self, s: str) -> str:
# return '%20'.join(s.split(' '))
if __name__ == '__main__':
ss = Solution()
print(ss.replaceSpace("hello world"))
|
3124d7ec96b8c50c35a7551e461087669c4e9536 | itsjunqing/fit1008-introduction-to-computer-science | /source_code/dp/dp_lec.py | 1,781 | 4.59375 | 5 | def longest_positive_sequence(the_list):
"""
Function that given a list, it returns the longest number of positive numbers.
If it returns 3, then there exists 3 consecutive positive numbers.
@param the_list: an array of integers
@complexity: best-case and worst-case is O(N) where N is the length of the list
this happens when the loop iterates the entire given list to compute
the number of consecutive positive numbers and store them in a memory
@return: longest number of positive numbers
"""
memory = [0] * len(the_list)
# base case
if the_list[0] > 0:
memory[0] = 1
# counter to keep track of the longest count of positive numbers
longest_length = memory[0]
# dynamic approach
for i in range(1, len(the_list)):
if the_list[i] > 0:
memory[i] = 1 + memory[i-1]
if memory[i] > longest_length:
longest_length = memory[i]
print(memory)
print(longest_length)
return longest_length
longest_positive_sequence([1,2,0,5,1,7,8,9,0,1,0,0,-5,-9,-7,1])
def max_subsequent_sum(the_list):
"""
Function that returns the maximum sum of consecutive numbers in a list.
@param the_list: an array with integers
@return: maximum sum of consecutive numbers in the list
"""
memory = [0] * len(the_list)
memory[0] = the_list[0]
for i in range(1, len(the_list)):
memory[i] = max(the_list[i], the_list[i] + memory[i-1])
print(memory)
return max(memory)
print(max_subsequent_sum([1,2,0,-4,1,2,96,-1,-100,99,0,0,-5,-9,-7,25]))
print(max_subsequent_sum([90,90,0,-200,1,2,96,-1,-100,99,0,0,-5,-9,-7,25]))
def A(num):
array = [0] * (num+1)
array[0] = 1
array[1] = 1
return A_aux(num, array, 2)
def A_aux(num, array, k):
if k > num:
return array
else:
array[k] = array[k-1]+ (2*array[k-2])
return A_aux(num, array, k+1)
A(6) |
2aead53b6eadcff8e4da37c3c73cd921bc87aa53 | soumyarooproy/leetcode_solutions | /code/python/kth-largest-element-in-an-array.py | 614 | 3.53125 | 4 | # 02/19/2018
# Time : O(n*lgk)
# Space : O(n)
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# Standard technique using a head
# - maintain a list of k largest elements using a min-heap
# - return the top of the heap at the end
import heapq
min_heap = []
for x in nums:
heapq.heappush(min_heap, x)
if len(min_heap) > k: # maintain min_heap size of k
heapq.heappop(min_heap)
return min_heap[0]
|
1093c30a7f3dc253443f1b56cb9eeaf3252a80b4 | Ran-oops/python | /zuoye3/tes1/new2.py | 1,043 | 3.8125 | 4 | '''
i = 100
if i < 4:
print('it works!')
else:
print('it is bad')
'''
'''
today=7
if today==1:
print('meat')
elif today==2:
print('bread')
elif today==3:
print('potato')
elif today==4:
print(tomato)
elif today==5:
print('chicken')
elif today==6:
print('1')
else:
print('2')
grade=76
if grade==100:
print('66666')
elif grade>=85:
print('1')
elif grade>=75:
print('2')
elif grade>=60:
print('3')
else:
print('4')
'''
'''
i=1
j=2
result=i+j
print(result)
var=350.1
print(newvar=int(var))
'''
'''
var=True
newvar=int(var)
print(newvar)
'''
'''
var=True
newvar=complex(var)
print(newvar)
'''
'''
var=0.0
newvar=bool(var)
print(newvar)
'''
var={'han','yang','shao'}
print(type(var))
newvar=list(var)
print(newvar)
'''
#list type
lists=['小辣椒','花露水','大鲨鱼','250']
print(lists)
'''
#tuple types
tuples=('huanghuahua','damuqu','lilulu')
print(tuples)
'''
'''
#dictation types
dicts={'1':'xiaoming','2':'dazui','3':'meinv'}
print(dicts)
#set types
sets={'laoganma','latiao','mayinglong','qingliangyou'}
print(sets)
''' |
e4057433d4a3e39b20e03fd505b6350931842d55 | longbefer/python_learn | /Trial/demo.py | 1,418 | 3.515625 | 4 | # file operator
import time
# open the file stream
# @param "file_name" 文件名
# @param mode 文件读写方式
# @param encoding 编码方式
# @more 其他参数可以使用 help(open)来获取
# @return 返回文件流
fo = open('Python/1_if_else.py', mode='r', encoding = 'utf-8')
# read the file stream
print("file name is: \n" + fo.name)
# read all file
# @return 返回整个文章的字节流
print(fo.read())
# get the point position
print('指针当前位置'+str(fo.tell()))
# set the point position
# seek(offset, [whence])
# @param offset 光标位置
# @param whence 默认为0,只能为0,1,2
# @example 使用seek(0,0)表示将光标置于文档开头
# 使用seek(0,2)表示将光标移至文档末尾
fo.seek(0, 0)
end = fo.seek(0, 2) # 移动至文档末尾
print('指针当前位置'+str(fo.tell()))
fo.seek(0,0) # 移动至文档开头
# read a line
print(fo.readline())
auto = input('是否开启自动翻页')
if auto == 'Y':
while True:
for i in range(3):
print(fo.readline())
time.sleep(2)
if fo.tell() == end:
break
else:
con = 'n'
while True:
if con=='n':
for i in range(3):
print(fo.readline())
else:
print('请输入n')
if fo.tell() == end:
break
con = input('请输入下一页')
# close the file stream
fo.close() |
f37ea65d2ea44ab0ef948cca36e24d2248f9b565 | Touchfl0w/Algorithm-Practices | /basic-ADT/list/ordered_list/ordered_list.py | 2,729 | 3.984375 | 4 | class Node():
"""链表中的节点,包括数据域和指针域;使用单链表实现"""
def __init__(self, data):
self.data = data
self.next = None
def get_data(self):
return self.data
def set_next(self, next_node):
#python内变量为引用类型,可视作指针
self.next = next_node
def get_next(self):
return self.next
class OrderedList():
"""有序列表"""
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def size(self):
#排除特殊情况
count = 0
node = self.head
while node != None:
count += 1
node = node.get_next()
return count
def remove(self, item):
"""
1、找到则删除,未找到不做任何操作
2、删除节点关键是定位相邻节点;左节点可以用previous表示,右节点用current.get_next()表示
3、所以两个变量previous与current至关重要
4、删除头结点要分类讨论
"""
found = False
current = self.head
previous = None
while current != None and not found:
if current.get_data() == item:
#found相当于指示器,相当于break
found = True
#previous为None:删除头结点
if previous == None:
self.head = current.get_next()
else:
previous.set_next(current.get_next())
else:
previous = current
current = current.get_next()
def search(self, item):
current = self.head
#trigger1
found = False
#trigger2
stop = False
#current is not None既表示当前列表非空,也是判断条件:遍历到了list末尾;双关
while current is not None and not found and not stop:
if item == current.get_data():
#找到目标值,触发trigger1,退出循环
found = True
else:
if item < current.get_data():
#由于list顺序排列,一旦当前考察值大于目标值,触发trigger2,退出循环
stop = False
else:
#自增项;只有当前值小于目标值才自增
current = current.get_next()
return found
def add(self, item):
#1、找到合适位置,记录在current、previous中
current = self.head
previous = None
stop = False
while current is not None and not stop:
if current.get_data() > item:
stop = True
else:
#只有trigger:stop未触发情况下才自增
previous = current
current = current.get_next()
temp_node = Node(item)
if current == self.head:
temp_node.set_next(current)
self.head = temp_node
else:
temp_node.set_next(current)
previous.set_next(temp_node)
if __name__ == '__main__':
mylist = OrderedList()
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
mylist.add(54)
print(mylist.size())
print(mylist.search(93))
print(mylist.search(100))
|
3a64a50a83bfaa49f3a1a168f6db7c6b95ba3432 | hjalves/project-euler | /problems1-25/problem10.py | 270 | 3.640625 | 4 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Project Euler - Problem 10
Summation of primes
"""
def is_prime(n):
return all(n % i != 0 for i in range(2, int(n**0.5)+1))
def primes(max):
return filter(is_prime, range(2, max))
print(sum(primes(2000000)))
|
d9226b0491beb72e1e7d2fbca84aaabc18f241c3 | abhinavs-27/leetcode | /CountingBits.py | 360 | 3.53125 | 4 | #Given a non negative integer number num. For every numbers i in
#the range 0 ≤ i ≤ num calculate the number of 1's in their binary
#representation and return them as an array.
class Solution:
def countBits(self, num: int) -> List[int]:
ret = [0]
for i in range(1,num+1):
ret.append(ret[i>>1] + (i&1))
return ret
|
f884ffb7ef0e596a26f61887dd4920966f32678e | rodrigoaml/iGordonServer | /api/services/getdate.py | 354 | 3.703125 | 4 | from datetime import datetime
from pytz import timezone
def get_date():
"""Returns today's date in format MM-DD-YY"""
# Format for date output
date_format = "%m/%d/%y %I:%M %p"
# Datetime in Eastern timezone
eastern = timezone('US/Eastern')
eastern_today = datetime.now(eastern)
return eastern_today.strftime(date_format)
|
707bab761e34e43ac55a6eb15b72d248a77453e3 | benbrattain/Data-Structures-Fall-2015 | /a7.py | 3,818 | 3.796875 | 4 |
#-----------------------------------------------------------------------------
# binary heap as discussed in class: each node has at most 2 chidren
#Assuming you want a Min-Heap based off of the functions below. Implemented it this way.
class B_Heap :
def __init__ (self) :
self.elems = [None]
self.size = 0
def __repr__ (self) :
return repr(self.elems[1:])
def isEmpty (self) :
return self.size == 0
def getSize (self) :
return self.size
def findMin (self) :
self.minHeapify(1)
return self.elems[1]
def minHeapify(self, index) :
if index == 0 or index >= self.size:
raise IndexError('Invalid index.')
minimum = self.findMinIndex(index)
if not minimum == index :
self.swapElements(index,minimum)
self.minHeapify(minimum) #continues the heapify progress to make sure the old parent is actually the min
def swapElements(self, oldIndex, newIndex) :
oldParent = self.elems[oldIndex]
newParent = self.elems[newIndex]
self.elems[oldIndex] = newParent
self.elems[newIndex] = oldParent
def findMinIndex(self, index) :
left = 2 * index
right = 2 * index + 1
if left <= self.size and self.elems[left] < self.elems[index] :
minimum = left
else :
minimum = index
if right <= self.size and self.elems[right] < self.elems[minimum] :
minimum = right
return minimum
def buildMinHeap(self) :
self.size = len(self.elems) - 1
length = len(self.elems) / 2
for i in range(length, 0) :
self.minHeapify(i)
def insert (self,k) :
self.elems.insert(1,k)
self.size += 1
self.minHeapify(1)
def extractMin (self) :
if self.size < 1 :
raise SizeError('Your heap is too small!')
minimum = self.elems[1]
self.elems[1] = self.elems[self.size]
self.size -= 1
self.minHeapify(1)
return minimum
#-----------------------------------------------------------------------------
# d-ary heap: each node has at most d-children
class D_Heap :
def __init__ (self,d) :
self.elems = [None]
self.size = 0
self.d = d
def __repr__ (self) :
return repr(self.elems[1:])
def isEmpty (self) :
return self.size == 0
def getSize (self) :
return self.size
def findMin (self) :
self.minHeapify(1)
return self.elems[1]
def insert (self,k) :
self.elems.insert(1,k)
self.size += 1
self.minHeapify(1)
def extractMin (self) :
if self.size < 1 :
raise SizeError('Your heap is too small!')
minimum = self.elems[1]
self.elems[1] = self.elems[self.size]
self.size -= 1
self.minHeapify(1)
return minimum
#------------------------------------------------------------------------------
# Implementing binary heap using trees; swap subtrees to maintain shape!
class B_Heap_Tree () : pass
class Empty (B_Heap_Tree) :
def __repr__ (self) : return '_'
def isEmpty (self) : pass
def getSize (self) : pass
def findMin (self) : pass
def insert (self,k) : pass
def extractMin (self) : pass
class Node (B_Heap_Tree) :
def __init__ (self,val,left,right) :
self.val = val
self.left = left
self.right = right
def __repr__ (self) :
return '[{},{},{}]'.format(self.val,self.left,self.right)
def isEmpty (self) : pass
def getSize (self) : pass
def findMin (self) : pass
def insert (self,k) : pass
def extractMin (self) : pass
#-----------------------------------------------------------------------------
|
22d0bfaf81dccd0d2aee82dbc124729a5ce1c1fc | code-tamer/Library | /Business/KARIYER/PYTHON/Python_Temelleri/break-continue.py | 973 | 4.03125 | 4 | name = 'Tamer Şahin'
# for letter in name:
# print(letter)
# for letter in name:
# if letter == 'a':
# break
# print(letter)
# for letter in name:
# if letter == 'e':
# break
# print(letter)
# for letter in name:
# if letter == 'e':
# continue
# print(letter)
# x = 0
# while x < 5:
# print(x)
# x += 1
# x = 0
# while x < 5:
# if x == 2:
# break
# print(x)
# x += 1
# x = 0
# while x < 5:
# x += 1
# if x == 2:
# continue
# print(x)
#1 1-100'e kadar sayıların toplamını yazalım:
# x = 1
# result = 0
# while x <= 100:
# result += x
# x += 1
# print(f'Toplam: {result}') => 0-100'e kadar bütün sayıların toplamını verir,
# Ancak biz sadece tek sayıların toplamını istediğimiz için;
# x = 0
# result = 0
# while x <= 100:
# x += 1
# if x %2 ==0:
# continue
# result += x
# print(f'Tek Sayılar Toplamı: {result}') |
8fea58cdd528f3fb8ea2e2f0995888a52e099a52 | frank-quoc/hackerrank_python | /interview-preparation-kit/warm-up/counting-valleys/answer.py | 993 | 3.65625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def countingValleys(steps, path):
pos = [0]
val_count = 0
for step in range(steps):
if path[step] == 'U':
cur_pos = pos[step] + 1
pos.append(cur_pos)
elif path[step] == 'D':
cur_pos = pos[step] - 1
pos.append(cur_pos)
for i in range(len(pos) - 1):
if pos[i] == 0 and pos[i+1] == -1:
val_count += 1
return val_count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
steps = int(input().strip())
path = input()
result = countingValleys(steps, path)
fptr.write(str(result) + '\n')
fptr.close()
# Better Answer
# def countingValleys(steps, path):
# position = 0
# valleys = 0
# for step in range(steps):
# position += 1 if path[step] == 'U' else -1
# if path[step] == 'U' and position == 0:
# valleys += 1
# return valleys
|
5960d0e2302e5d21e14f769a6f02db5804a7d7f8 | chr1sbest/ctci | /python/2_Linked_Lists/2_7.py | 1,718 | 4.53125 | 5 | """
2.7
Implement a function to check if a linked list is a palindrome.
"""
from classes import ListFactory
from copy import deepcopy
# Solution 1
def iter_palindrome(llist):
"""
Reverse a linked list iteratively with a stack.
Time complexity: O(n)
Space complexity: O(n)
"""
stack = []
node = llist.head
while node != None:
stack.append(node.data)
node = node.nextNode
return True if stack == stack[::-1] else False
# Solution 2 (INCOMPLETE!)
def rec_palindrome(llist):
"""
Determine if a linked list is a palindrome in place using recursion.
Time complexity: O(n)
Space complexity: O(n)
"""
node1, node2 = llist.head, deepcopy(llist.head)
return node1 == recursiveReverse(node2)
def recursiveReverse(node, last=None):
"""
Reverse a linked list in place recursively.
"""
if node is None:
return last
nextNode = node.nextNode
node.nextNode = last
return recursiveReverse(nextNode, node)
if __name__ == "__main__":
# Iterative
values1, values2 = [0, 5, 4, 3, 4, 5, 0], [1, 2, 3, 4, 5]
llist1, llist2 = ListFactory(values1), ListFactory(values2)
pal1, pal2 = iter_palindrome(llist1), iter_palindrome(llist2)
print "Iterative: {0} palindrome? {1}".format(values1, pal1)
print "Iterative: {0} palindrome? {1}".format(values2, pal2)
#Recursive
values3, values4 = [3, 5, 6, 9, 0], [1, 2, 3, 4, 5, 4, 3, 2, 1]
llist3, llist4 = ListFactory(values3), ListFactory(values4)
pal3, pal4 = rec_palindrome(llist3), rec_palindrome(llist4)
print "Recursive: {0} palindrome? {1}".format(values3, pal3)
print "Recursive: {0} palindrome? {1}".format(values4, pal4)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.