blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
4c95f5127cb8304fa3d62ec5ef52ea4f943bcc75 | JAlsko/pyCompiler | /tests/test35.py | 104 | 3.734375 | 4 | x = 3
if (x + 4 == 7):
print x
else:
print 0
if (x + -3 == 0):
y = 4
print y
else:
y = 1
print y
|
a54bca0c2d12a8d133fd5684b7091d6515150e7e | jamesroberthershaw/factorial-digits | /factorial-digits.py | 602 | 3.8125 | 4 | import numpy as np
import sys
if(len(sys.argv)>2):#in case the user has inputted too many arguments
print("Too many arguments provided by user, please try again")
elif(len(sys.argv)==1):#in case the user has not inputted any arguments
print("No number provided by user, please try again")
else:#user inputted command correctly
user_input = int(sys.argv[1])
n = np.math.factorial(user_input)
x = [(n//(10**i))%10 for i in range(np.math.ceil(np.math.log(n, 10))-1, -1, -1)] #Fill array x with digits of factorial
factorial_sum = sum(x)
print(factorial_sum)
|
c35039d477752ba56912ddcb69d27e4c8eb1eaac | nicholasbarnette/ftp-server | /server/utils.py | 2,512 | 3.9375 | 4 | COMMANDS = ["USER", "PASS", "TYPE", "SYST", "NOOP", "QUIT", "PORT", "RETR"]
# Test if the command is valid
def validateCommand(cmd):
"""Validates a command
Args:
cmd (string): any command as a string
Returns:
string: an error message if the command is invalid
"""
if not (len(cmd) != 0 and cmd.upper() in COMMANDS):
# Command is 3-4 characters long
if len(cmd) == 3 or len(cmd) == 4:
return "502 Command not implemented.\r\n"
return "500 Syntax error, command unrecognized.\r\n"
return ""
def validateType(param):
"""Validates a type-code parameter
Args:
param (string): type-code paramerter that needs validation
Returns:
boolean: whether or not the type-code parameter is valid
"""
return param.upper() in ["A", "I"]
def validateStringParameter(param):
"""Validates a string parameter to ensure it is valid. Primarily used for `USER` and `PASS` commands.
Args:
param (string): any string parameter
Returns:
boolean: whether or not the string parameter is valid
"""
return isinstance(param, str) and len(param) != 0
def validateStringCharacters(param):
"""Validates that all characters in a string parameter are valid ASCII charaters (excluding '*').
Args:
param (string): any string parameter
Returns:
boolean: whether or not the string contains valid ASCII characters
"""
for char in param:
if ord(char) > 127 or ord(char) < 0 or char == "*":
return False
return True
def validatePort(param):
"""Validates that the port follows the proper format (xxx,xxx,xxx,xxx,xxx,xxx).
Args:
param (string): a port to validate
Returns:
boolean: whether or not the port is valid
"""
# Splits the port sections
portArray = param.split(",")
# Check if there are the correct
if not (len(portArray) == 6):
return False
goodPort = True
# Check if the port number is valid
for pNum in portArray:
if len(pNum) == 0 or int(pNum) >= 256 or int(pNum) < 0:
goodPort = False
return goodPort
def convert2bytes(no):
"""Converts a number to its byte format
Args:
no ([type]): [description]
Returns:
[bytearray]: [description]
"""
result = bytearray()
result.append(no & 255)
for _i in range(3):
no = no >> 8
result.append(no & 255)
return result
|
bdeb54567ccc430367439f4c6afe1f1d1bf3348a | ht-evth/computational-mathematics | /lab9/main.py | 2,823 | 3.5 | 4 | import sympy
import integral
FILENAME_FUNC = 'func1.txt'
FILENAME_START_END_STEP = 'ses1.txt'
def loadFuncFromFile(filename):
""" считать функцию в виде строки из файла """
try:
file = open(filename)
res = file.readline()
file.close
return res
except FileNotFoundError:
print('FileNotFoundError: ' + filename)
return None
def loadStartEndStep(filename):
""" загрузить отрезок и шаг из файла """
try:
f = open(filename)
line = f.readline()
f.close()
res = line.split(' ')
return float(res[0]), float(res[1]), float(res[2])
except:
print('Error')
return None, None, None
def finput(msg):
while True:
try:
num = float(input(msg))
break
except ValueError:
pass
return num
def main():
# считываем функцию из файла
# и старт, стоп, шаг из файла
func = loadFuncFromFile(FILENAME_FUNC)
start, end, step = loadStartEndStep(FILENAME_START_END_STEP)
# выводим функцию и отрезок
print('Заданная функция: f(x) = {} на отрезке [ {} ; {} ]'.format(func, start, end))
print('Точное значение = ', sympy.integrate(func, ('x', start, end)))
# считываем кол-во шагов
#print('\n*Постоянный шаг интегрирования.')
#step = finput('Введите кол-во шагов: ')
## вычисляем интегралы с постоянным шагом
#rect, trap, simpson = integral.constStep(start, end, step, func)
## выводим результаты
#print('\nМетод средних прямоугольников: \t',rect)
#print('Метод трапеции: \t\t\t\t', trap)
#print('Метод Симпсона: \t\t\t\t', simpson)
print('\n*Автоматический шаг интегрирования.')
# запрос ввода точности
e = finput('Точность: ')
# вычисление интегралов с заданной точностью
rectAutoStep, trapAutoStep, simpsonAutoStep, stepsRect, stepsTrap, stepsSimpson = integral.autoStep(start, end, e, func)
print('\nМетод средних прямоугольников: {}\nКол-во шагов: {}'.format(rectAutoStep, stepsRect))
print('\nМетод трапеции: {}\nКол-во шагов = {}'.format(trapAutoStep, stepsTrap))
print('\nМетод Симпсона: {}\nКол-во шагов = {}'.format(simpsonAutoStep, stepsSimpson))
if __name__ == "__main__":
main() |
da451eb9b2ad03a021cebaa935eefb18e94a3ef5 | successgilli/python | /multTable.py | 433 | 3.75 | 4 | # print 2 * table
def printLine(table, num, error=False):
print(f"{table} * {num} = {table*num}") if error == False else print(f"\033[0;30;41m{table} * {num} = {2*num}\033[0m")
for num in range(1,13):
try:
if num == 4: raise Exception('incorrect multiplication')
printLine(2, num)
except Exception:
printLine(3,num, True)
else: print("\U0001F606")
x = [1,2,3,4]
print([1 + i for i in x if i>2]) |
2d768ad137a6f97d1e386c733c5ce4304de3d281 | lennox-davidlevy/practice | /6 Misc/word_search_ii.py | 558 | 4.0625 | 4 | # Given an m x n board of characters and a list of strings words, return all words on the board.
# Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
# Example 1:
# Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
# Output: ["eat","oath"]
# Example 2:
# Input: board = [["a","b"],["c","d"]], words = ["abcb"]
# Output: []
|
864c37ad08e067adf7881e159ee388e68ce1c8bf | nlin24/python_algorithms | /Sorting.py | 4,330 | 4.21875 | 4 | '''
Implement sorting algorithms per https://interactivepython.org/runestone/static/pythonds/SortSearch/sorting.html
'''
def bubbleSort(aList):
for passNum in range(len(aList) -1, 0, -1):
for index in range(passNum):
if aList[index] > aList[index + 1]:
tmp = aList[index]
aList[index] = aList[index + 1]
aList[index + 1] = tmp
return aList
# Enhanced bubble sort, stopping when no element has been exchagned
def shortBubbleSort(alist):
exchanged = False
for passNum in range(len(alist)-1,0,-1):
exchanged = False
for i in range(passNum):
if alist[i] > alist[i+1]:
tmp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = tmp
exchanged = True
if exchanged == False:
return alist
def selectionSort(alist):
for i in range(len(alist)-1, 0, -1 ):
maxIndex = 0
for j in range(1,i+1):
if alist[maxIndex] < alist[j]:
maxIndex = j
tmp = alist[i]
alist[i] = alist[maxIndex]
alist[maxIndex] = tmp
def insertionSort(alist):
for index in range(1,len(alist)):
currentValue = alist[index]
currentPosition = index
while currentPosition > 0 and currentValue < alist[currentPosition-1]:
alist[currentPosition] = alist[currentPosition-1]
currentPosition = currentPosition - 1
alist[currentPosition] = currentValue
def shellSort(alist):
# first pick the sublist size. In this example we split the list in two
sublistCount = len(alist) // 2
while sublistCount > 0:
for startPosition in range(sublistCount):
gapInsertionSort(alist,startPosition, sublistCount)
print("After increment of size", sublistCount, "The list is ", alist)
sublistCount = sublistCount // 2
def gapInsertionSort(alist, start, gap):
for i in range(start+gap, len(alist), gap):
currentValue = alist[i]
currentPosition = i
while currentPosition >= gap and currentValue < alist[currentPosition-gap]:
alist[currentPosition] = alist[currentPosition-gap]
currentPosition = currentPosition - gap
alist[currentPosition] = currentValue
def mergeSort(alist):
print("[x] Splitting",alist)
if len(alist) > 1:
mid = len(alist) // 2
leftHalf = alist[:mid]
rightHalf = alist[mid:]
mergeSort(leftHalf)
mergeSort(rightHalf)
i = 0 # index for left half
j = 0 # index for right half
k = 0 # index for merging list
# merge the two halves
while i < len(leftHalf) and j < len(rightHalf):
if leftHalf[i] > rightHalf[j]:
print("Pick from right half while merge from both right and left halves:", rightHalf[j])
alist[k] = rightHalf[j]
j = j + 1
else:
print("Pick from left half while merge from both right and left halves:", leftHalf[i])
alist[k] = leftHalf[i]
i += 1
k += 1
while i < len(leftHalf):
print("Merges left only:", leftHalf[i])
alist[k] = leftHalf[i]
i += 1
k += 1
while j < len(rightHalf):
print("Merges right only:", rightHalf[j])
alist[k] = rightHalf[j]
j += 1
k += 1
print("[o] Merging ", alist)
def testMergeSort():
#alist = [54,26,93,17,77,31,44,55,20]
alist = [3,2,1,4]
mergeSort(alist)
print(alist)
def testShellSort():
alist = [54,26,93,17,77,31,44,55,20]
shellSort(alist)
print(alist)
def testInsertionSort():
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)
def testSelectionSort():
alist = [54,26,93,17,77,31,44,55,20]
selectionSort(alist)
print(alist)
def testBubbleSort():
alist = [54,26,93,17,77,31,44,55,20]
bubbleSort(alist)
clist=[1,3,2,4,5]
shortBubbleSort(clist)
bubbleSort(clist)
print(alist)
print(clist)
if __name__ == "__main__":
#testBubbleSort()
#testSelectionSort()
#testInsertionSort()
#testShellSort()
testMergeSort() |
a3d3e5687165d0514db4ea6f98bcebeba620f0fb | eshim/Algorithms | /InsertionSort.py | 932 | 3.875 | 4 | """
Insertion Sort
Take the last value of a list and compare it to each element
of the sorted sublist and places it accordingly until there
are no more elements of the given list.
Worst Case Performance: O(n^2) comparisons and swaps
Best Case Performance: O(n) comparisons, O(1) swaps
Average Case Performance: O(n^2) comparisons and swaps
"""
def insertionSort(inlist):
inlistLength = len(inlist)
for i in range(inlistLength):
sorting_value = inlist[i]
j = i - 1
while j >= 0 and inlist[j] > sorting_value:
inlist[j+1] = inlist[j]
j -= 1
inlist[j+1] = sorting_value
return inlist
def insertionSort2(inlist):
inlistLength = len(inlist)
for i in range(inlistLength):
sorting_value = inlist[i]
for j in range(i - 1, -1, -1):
if inlist[j] > sorting_value:
inlist[j+1] = inlist[j]
inlist[j+1] = sorting_value
return inlist
# test
mylist = [0,10,3,2,11,22,40,-1,5]
print insertionSort(mylist) |
16dca826781c4256df098920a0cfd5a64461b0c0 | workingpayload/Hash-Cracker | /Hash cracker.py | 804 | 3.890625 | 4 | import hashlib
print("***************************PASSWORD CRACKER***************************")
pass_found = 0
input_hash = input("Enter the hashed password:- ")
pass_doc = input("\nEnter wordlist path:- ")
try:
pass_file = open(pass_doc,'r')
except:
print("Error:")
print(pass_doc, "is not found. \nPlease give the path of file correctly.")
quit()
for word in pass_file:
enc_word = word.encode('utf-8')
hash_word = hashlib.md5(enc_word.strip())
digest = hash_word.hexdigest()
if digest == input_hash:
print("Password Found. \nThe password is:",word)
pass_found = 1
break
if not pass_found:
print("Password is not found in the", pass_doc, "file")
print('\n')
print("***************************Thank You**************************") |
08d42cfe9358316a3d50c49b6f400c041f92b5ac | br80/zappy_python | /06_game/snake.py | 735 | 3.5625 | 4 | from enemy import Enemy
import random
class Snake(Enemy):
def __init__(self, row, col, game):
super().__init__("SNAKE", row, col, 1000, 0.5, game)
self.energy = 3
def wait(self):
# Snakes store energy whenever they wait
super().wait()
self.energy += 1
# Some randomization in how long snakes will store energy.
self.should_wait = self.energy <= random.randint(1, 5)
def action(self):
# Snakes will move multiple times in a quick burst,
# waiting when they run out of energy.
self.random_move()
self.frame_to_act += int(1 * self.move_speed)
self.energy -= 1
if self.energy <= 0:
self.should_wait = True
|
b5fd561b1bbb06de3d58832535a21415c5fb5233 | shamoldas/pythonBasic | /DataScience/pandas/Different2Column.py | 440 | 3.875 | 4 | import pandas as pd
# Create a DataFrame
df1 = { 'Name':['George','Andrea','micheal',
'maggie','Ravi','Xien','Jalpa'],
'score1':[62,47,55,74,32,77,86],
'score2':[45,78,44,89,66,49,72]}
df1 = pd.DataFrame(df1,columns= ['Name','score1','score2'])
print("Given Dataframe :\n", df1)
# getting Difference
df1['Score_diff'] = df1['score1'] - df1['score2']
print("\nDifference of score1 and score2 :\n", df1)
|
aa59f848d9b28b496b5159ff17aa17ef4c24ac0d | nn98/Algorithm | /src/BaekJoon/Simple_Implementation/P11772.py | 108 | 3.515625 | 4 | t = int(input())
num = 0
for i in range(t):
n = int(input())
num += (n // 10) ** (n % 10)
print(num) |
8b28ff6c7e303a9c83ac5cfde96022bf0b6cb3e0 | sidv/Assignments | /Ramya_R/Ass27Augd24/cluster.py | 631 | 3.5625 | 4 | import json
import requests
import pandas as pd
import matplotlib.pyplot as plt
#Got url from data.gov.in
url = "https://api.data.gov.in/resource/ee35f072-4d80-4b41-8c17-fd74414907be?api-key=579b464db66ec23bdd000001cdd3946e44ce4aad7209ff7b23ac571b&format=json&offset=0&limit=10"
#Requesting the server using GET type
res = requests.request("GET",url)
data = res.json()
data_records = data['records'] #Fetching records key from response
#creating dataframe from json
df = pd.DataFrame(data_records)
print(df)
print(df.info()) #printing columns and other info
dfl = df.loc[:, ['clusterno', 'clustername', 'centroid']]
print(dfl)
|
808184cb678948142e3f15f48d971ffd4562275b | here0009/LeetCode | /Python/RangeSumQuery2D-Immutable.py | 3,479 | 3.875 | 4 | """
Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
Example:
Given matrix = [
[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]
]
sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12
Note:
You may assume that the matrix does not change.
There are many calls to sumRegion function.
You may assume that row1 ≤ row2 and col1 ≤ col2.
"""
class NumMatrix:
"""
Thought: use an accumulated matirx
so the result is right-bottom + left-top - top-right - left-bottom
"""
def __init__(self, matrix):
if matrix is None or not matrix:
return
self.acc_matrix = [[0]*self.c for _ in range(self.r)]
for i in range(self.r):
for j in range(self.c):
self.acc_matrix[i][j] = matrix[i][j]
for i in range(1,self.r): #1st col
self.acc_matrix[i][0] += self.acc_matrix[i-1][0]
for j in range(1,self.c): #1st row
self.acc_matrix[0][j] += self.acc_matrix[0][j-1]
for i in range(1,self.r):
for j in range(1,self.c):
self.acc_matrix[i][j] += self.acc_matrix[i-1][j] + self.acc_matrix[i][j-1] - self.acc_matrix[i-1][j-1]
# for row in self.acc_matrix:
# print(row)
def get_val(self,i,j):
if i<0 or j<0 : #or (i==0 and j==0)
return 0
else:
return self.acc_matrix[i][j]
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
if self.r == 0 or self.c == 0:
return 0
return self.get_val(row2, col2) + self.get_val(row1-1, col1-1) - self.get_val(row2, col1-1) - self.get_val(row1-1, col2)
class NumMatrix:
def __init__(self, matrix):
if matrix is None or not matrix:
return
self.row,self.col = len(matrix), len(matrix[0])
self.acc_matrix = [[0]*(self.col+1) for _ in range(self.row+1)]
for i in range(1,self.row+1):
for j in range(1,self.col+1):
self.acc_matrix[i][j] = matrix[i-1][j-1] + self.acc_matrix[i-1][j] + self.acc_matrix[i][j-1] - self.acc_matrix[i-1][j-1]
# for row in self.acc_matrix:
# print(row)
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
if self.row == 0 or self.col ==0:
return 0
return self.acc_matrix[row2+1][col2+1] + self.acc_matrix[row1][col1] - self.acc_matrix[row1][col2+1] - self.acc_matrix[row2+1][col1]
# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# param_1 = obj.sumRegion(row1,col1,row2,col2)
# Your NumMatrix object will be instantiated and called as such:
matrix = [[3, 0, 1, 4, 2],[5, 6, 3, 2, 1],[1, 2, 0, 1, 5],[4, 1, 0, 1, 7],[1, 0, 3, 0, 5]]
obj = NumMatrix(matrix)
# param_1 = obj.sumRegion(row1,col1,row2,col2)
print(obj.sumRegion(2, 1, 4, 3))
print(obj.sumRegion(1, 1, 2, 2))
print(obj.sumRegion(1, 2, 2, 4))
matrix = [[]]
obj = NumMatrix(matrix)
print(obj.sumRegion(0,0,0,0))
# ["NumMatrix","sumRegion","sumRegion","sumRegion"]
# matrix = [[[[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]],
# [2,1,4,3],[1,1,2,2],[1,2,2,4]] |
afa126ed970b46c2dc3ad6bb9dd452cc449fbd76 | Ramyaveerasekar/python_programming | /sqr.py | 93 | 3.890625 | 4 | num1=int(input("enter the number"))
num2=int(input("enter the number"))
print(num1**num2)
|
7d3e150122d2f7dff5d9c40ded061da68c394051 | linmounong/leetcode | /2017/530.py | 736 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
state = [None, None]
foo(root, state)
return state[1]
def foo(node, state):
if not node:
return
foo(node.left, state)
if state[0] is None:
state[0] = node.val
else:
diff = node.val - state[0]
state[0] = node.val
if state[1] is None:
state[1] = diff
else:
state[1] = min(state[1], diff)
foo(node.right, state)
|
f7ec7d9135c5c02ad7be923931a9428d34683b1f | reeha-parkar/python | /generators.py | 1,029 | 4.28125 | 4 | '''
# In such an example, we store all the values and then access them
# If there are so many values, there will be MemoryError
x = [i for i in range(10)]
for el in x:
print(el)
'''
'''
# But you can use something like this, which will take each value and then print (one value at a time)
for i in range(10):
print(i)
'''
'''
# Generator method:
class Gen:
def __init__(self, n):
self.n = n
self.last = 0
def __next__(self):
return self.next()
def next(self):
if self.last == self.n:
raise StopIteration()
rv = self.last ** 2
self.last += 1
return rv
g = Gen(10)
while(True):
try:
print(next(g))
except StopIteration:
break
'''
# Using the yield keyword:
def gen(n):
for i in range(n):
yield i**2 # will pause the function, so we have all info of it
# return will top the function
g = gen(100)
#for i in g:
# print(i)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
|
b0cb66c7963f68f86c54211e46204d07dfcdbdb2 | DipendraDLS/Python_OOP | /14.Thread_&_Multithreading/19.Thread_Synchronization_Semaphore.py | 2,902 | 3.796875 | 4 | '''
- Semaphore : This is one of the oldest synchronization primitives in the history of computer scicence,
invented by the early Dutch computer scientist Edsger W. Dijkstra.
A semaphore manages an internal counter which is decremented by each acquire() call and
incremented by each release() call.
The counter can never go below zero; when acquire() finds that it is zero, it blocks waiting
until some other thread calls release().
It's usually better to use the BoundedSemaphore class, which considers it to be an error to call
release more often than you have called acquire.
'''
from threading import BoundedSemaphore, Thread, current_thread, Semaphore
class Flight(Thread):
def __init__(self, availabe_seats):
self.available_seats = availabe_seats
self.l = Semaphore(2) # Seamaphore() is class in threading and here '2' means the limit of thread that can lock the resources at a time.
# self.l = BoundedSemaphore(2) # BoundedSemaphore() ma chai exactly jati limit diyeko huncha teti choti nai release garna parcha limit vanda badi release() garyo vani error auncha.
#print(self.l) # self.l object ho
def reserve(self, needed_seat):
#lock maintain gareko
self.l.acquire() # acquire() call hunda semaphore() ma diyeko thread ko limnit '1' le ghatcha.
print(self.l._value) # self.l.value le semaphore ko yeuta private varaiable 'value' vanni ma j chatyo print dincha
print('Available Seats: ', self.available_seats)
if (self.available_seats >= needed_seat):
name = current_thread().name
print(f'{needed_seat} seat is alloted for {name}')
self.available_seats -= needed_seat
else:
print('Sorry! All seats has alloted')
self.l.release() # jati choti lock acquire gareko huncha teti choti nai release garna parni huncha.
self.l.release() # Semaphore() ma jati limit deko cha teti nai choti release garna parcha, yedi release() limit vanda ni dherai choti release() garyo vani ni error chai aundaina.
# BoundedSemaphore() ma chai exactly jati limit diyeko huncha teti choti nai release garna parcha limit vanda badi release() garyo vani error auncha.
f = Flight(2)
t1 = Thread(target=f.reserve, args=(1,), name='Raman')
t2 = Thread(target=f.reserve, args=(1,), name='Baman')
t3 = Thread(target=f.reserve, args=(1,), name='Sonam')
t1.start()
t2.start()
t3.start()
# Main Thread bydefault huni garda cha so tyo main thread bich ma execute navai last ma execute hoss vanera join() method use gareko
t1.join()
t2.join()
t3.join()
print('Main Thread') |
160824fdc53caef4297f6f093625ad3d3dec9b48 | Aesthemic/text-rpg | /game.py | 16,065 | 3.5 | 4 | # Work-in-progress text-based game.
import os
from pathlib import Path
import sys
# Used for save files and other configuration files.
import json
# Importing custom modules.
import get
import put
import common
# This function displays the main menu for the game. The user is able to start or load a game, view credits, edit game-wide settings, and exit the game from here.
def main_menu():
common.clear_screen()
print(" _____ _ ____________ _____ ")
print("|_ _| | | | ___ \\ ___ \\ __ \\")
print(" | | _____ _| |_ | |_/ / |_/ / | \\/")
print(" | |/ _ \\ \\/ / __| | /| __/| | __ ")
print(" | | __/> <| |_ | |\\ \\| | | |_\\ \\")
print(" \\_/\\___/_/\\_\\\\__| \\_| \\_\\_| \\____/\n\n")
print("1. New Game")
print("2. Load Game")
print("3. Credits")
print("4. Help")
print("5. Exit Game")
selection = input("> ")
# As it turns out, Python lacks a switch-case system. Odd. If / elif / else it is then.
if selection == "1":
start_game()
elif selection == "2":
load_game()
elif selection == "3":
credits()
elif selection == "4":
game_help("start")
elif selection == "5":
common.clear_screen()
sys.exit(0)
elif selection == "318":
secret_menu()
else:
print("Incorrect selection. Please choose one of the options.")
print("Press any key to continue.")
input("?")
main_menu()
# Displays credits related to development of the game.
def credits():
common.clear_screen()
print("This game engine was developed by Aesthemic.")
print("Github: https://github.com/Aesthemic/text-rpg")
print("Twitter: https://www.twitter.com/aesthemic")
print("Discord: Aesthemic#0573")
print("IRC: Aesthemic in #lounge on irc.digibase.ca")
print("Email: aesthemic@digitalcyon.com")
print("Press any key to continue.")
input("?")
main_menu()
# This function will display the in-game main menu. From here, they have a number of different options to progress the game.
def game_menu():
common.clear_screen()
print("Game Menu")
with open("data/locations.json", 'r') as f:
location_data = json.load(f)
f.close()
curr_loc_id = character_data["travel"]
curr_loc_nm = location_data[curr_loc_id]["text-name"]
print("You're currently in " + str(curr_loc_nm) + ".")
print("Select an Option")
print("1. Travel")
print("2. Explore")
print("3. Shopping")
print("4. Stats")
print("5. Inventory")
print("6. Help")
print("7. Save Game")
print("8. Exit Game")
selection = input("> ")
if selection == "1":
travel_menu()
elif selection == "2":
explore()
elif selection == "3":
shop_menu()
elif selection == "4":
view_stats("player", character_data["character_name"])
elif selection == "5":
print("This game is still under construction.")
print("Press any key to continue.")
selection = input("> ")
game_menu()
elif selection == "6":
game_help("game")
elif selection == "7":
save_game()
elif selection == "8":
main_menu()
else:
print("Incorrect selection. Please choose from one of the options.")
print("Press any key to continue.")
selection = input("> ")
game_menu()
# Function to save the game to a JSON file. Files are stored in the 'save' folder.
def save_game():
common.clear_screen()
print(character_data["character_name"])
character_name = character_data["character_name"]
savename = "save/" + character_name + ".json"
with open(savename, 'w') as f:
json.dump(character_data, f)
f.close()
print("You successfully saved the game.")
print("Press return to continue.")
input("?")
game_menu()
# Function to load the game from a JSON file. Files are stored in the 'save' folder.
def load_game():
common.clear_screen()
print("Please type the name of the save file you would like to load.")
print("Save files:")
global character_data
for files in os.walk('save'):
for filename in files:
if ".json" in str(filename):
print(str(filename)[2:-7])
character_name = input("> ")
character_filename = "save/" + character_name + ".json"
with open(character_filename, 'r') as f:
character_data = json.load(f)
f.close()
if character_data is None:
print("Invalid character name. Please choose one from the list.")
print("Press return to continue.")
input("?")
load_game()
print("Save loaded.")
print("Press return to continue.")
input("?")
game_menu()
# This function starts the process of creating a new character.
def start_game():
common.clear_screen()
print("Welcome to this strange world.")
print("May I ask your name?")
character_name = input("> ")
print(f"Hello, {character_name}, it is a pleasure to meet you.")
character_filename = "save/" + character_name + ".json"
character_file = Path(character_filename)
if len(character_name) > 20:
common.clear_screen()
print("Your name needs to be less than 20 characters. Please choose another name.")
print("Press any key to continue.")
input("?")
start_game()
elif character_file.is_file():
common.clear_screen()
print("There is already a character with that name. You'll have to choose another one.")
print("Press enter to continue.")
input("?")
start_game()
else:
global character_data
character_data = {"character_name":character_name,"level":1,"current_health":100,"current_magic":100,"attributes":{"health":100,"magic":100,"strength":10,"dexterity":10,"endurance":10,"agility":10,"intelligence":10,"spirit":10,"vitality":10,"luck":0},"temp_attributes":{"health":0,"magic":0,"strength":0,"dexterity":0,"endurance":0,"agility":0,"intelligence":0,"spirit":0,"vitality":0,"luck":0},"item_attributes":{"health":0,"magic":0,"strength":0,"dexterity":0,"endurance":0,"agility":0,"intelligence":0,"spirit":0,"vitality":0,"luck":0},"progress":{"experience":0,"experience_to_level":100},"currencies":{"gold":0,"honor":0},"items":{},"bank":{},"quests":{},"travel":"starting-village"}
character_filename = "save/" + character_name + ".json"
with open(character_filename, 'x') as f:
json.dump(character_data, f)
game_menu()
# Function to view the stats of either the playable character or an NPC.
# a = 'npc' or 'player' depending on whether the target is the playable character or an NPC.
# b = name of the character or NPC.
def view_stats(a, b):
if a == "player":
common.clear_screen()
character_filename = "save/" + b + ".json"
with open(character_filename, 'r') as f:
character_data = json.load(f)
f.close()
print("Character stats for: " + character_data["character_name"])
print("Basic Information:")
print("Level: " + str(get.level("player", b)))
print("Health: " + str(get.health("player", b)) + " \\ " + str(get.atr("player", b, "health")))
print("Magic: " + str(get.magic("player", b)) + " \\ " + str(get.atr("player", b, "magic")))
print("Experience: " + str(get.exp(a, b)) + " \\ " + str(get.toexp(a, b)))
print("Strength: " + str(get.atr("player", b, "strength")))
print("Dexterity: " + str(get.atr("player", b, "dexterity")))
print("Endurance: " + str(get.atr("player", b, "endurance")))
print("Agility: " + str(get.atr("player", b, "agility")))
print("Intelligence: " + str(get.atr("player", b, "intelligence")))
print("Spirit: " + str(get.atr("player", b, "spirit")))
print("Vitality: " + str(get.atr("player", b, "vitality")))
print("Luck: " + str(get.atr("player", b, "luck")))
print("Press enter to continue.")
input("?")
game_menu()
else:
common.clear_screen()
npc_filename = "save/" + b + ".json"
with open(npc_filename, 'r') as f:
npc_data = json.load(f)
f.close()
print("Character stats for: " + npc_data["character_name"])
print("Basic Information:")
print("Experience: " + str(get.exp(a, b)) + " \\ " + str(get.toexp(a, b)))
print("Press enter to continue.")
input("?")
game_menu()
# This function provides an in-game help menu for the player. To some extent, I feel like this could be improved upon. I'll have to look into a better way to handle the in-game help files.
def game_help(a):
common.clear_screen()
print("Help Menu")
print("Which topic would you like help with?")
print("1. How to Play")
print("2. Menus")
print("3. Attributes")
print("4. Combat")
print("5. Bug Report")
print("Press return to return to previous menu.")
selection = input("> ")
if selection == "1":
game_help_general(a)
elif selection == "2":
game_help_menues(a)
elif selection == "3":
game_help_attributes(a)
elif selection == "4":
game_help_combat(a)
elif selection == "5":
game_help_bug(a)
else:
if a == "game":
game_menu()
elif a == "combat":
combat_menu()
elif a == "start":
main_menu()
else:
main_menu()
# This help screen gives the player information on what the game is about and how to play.
def game_help_general(a):
common.clear_screen()
print("The main objective of the game is to explore the world and defeat the four major bosses.")
print("Over the course of the game you'll recruit new characters to help you, find new gear, and complete quests to unlock new abilities.")
print("Press return to continue.")
input("?")
game_help(a)
# This help screen explains what all of the primary menus do.
def game_help_menus(a):
common.clear_screen()
print("This help menu is coming soon.")
print("Press return to continue.")
input("?")
game_help(a)
# This help screen gives the player information on what the different attributes in the game do.
def game_help_attributes(a):
common.clear_screen()
print("Health: This is how much damage you can take before your character dies.")
print("Magic: This is how much magic you can use. Spells in the game take magic to cast.")
print("Strength: This influences how much damage you deal with physical attacks. The higher the strength, the more damage you deal.")
print("Dexterity: This determines your chance to hit an enemy. The higher the dexterity, the better the chance to hit.")
print("Endurance: This determines how much physical damage you can absorb. The higher the endurance, the less damage you take from physical attacks.")
print("Agility: This determines your chance to dodge an incoming attack. The higher the agility, the better the chance that a physical attack will miss you.")
print("Intelligence: This determines how powerful your attack spells are. The higher the intelligence, the more potent your attack spells are.")
print("Spirit: This determines how much magic you receive when you level up. Increase this to improve your health.")
print("Vitality: This determines how much health you receive when you level up. Increase this to improve your magic.")
print("Luck: This determines your chance for lucky things to happen. Don't think too much about it. :)")
print("Press return to continue.")
input("?")
game_help(a)
# This help screen gives the player information on what combat is like.
def game_help_combat(a):
common.clear_screen()
print("This menu is under construction since the combat system is under construction.")
print("Press return to continue.")
input("?")
game_help(a)
# This help screen gives the player information on how to file a bug report.
def game_help_bug(a):
common.clear_screen()
print("If you've run into a bug, please send an email to aesthemic@inpixelit.com.")
print("Thank you for helping with testing the game.")
print("Press return to continue.")
input("?")
game_help(a)
# :)
def secret_menu():
common.clear_screen()
print("Welcome to the secret menu! This doesn't do anything right now, but feel free to make yourself at home.")
print("Press return to go back to the main menu.")
input("?")
main_menu()
# Function used to allow players to travel to new areas.
def travel_menu():
common.clear_screen()
curr_loc_id = character_data["travel"]
curr_loc_nm = location_data[curr_loc_id]["text-name"]
travel_to = location_data[curr_loc_id]["travel"]
print("You're currently in " + curr_loc_nm + ".")
print("Where would you like to go?")
for key in travel_to:
print(location_data[key]["text-name"] + " - Level: " + str(location_data[key]["area-level"]))
print("Type the name of the area you would like to go.")
print("If you change your mind, simply type nothing and hit return.")
selection = input("> ")
selection = selection.lower()
selection = selection.replace(" ", "-")
if selection in location_data[curr_loc_id]["travel"]:
character_data["travel"] = selection
common.clear_screen()
print("You have successfully traveled to " + location_data[selection]["text-name"] + ".")
print("Press return to continue.")
input("?")
game_menu()
else:
common.clear_screen()
print("Invalid selection.")
print("Press return to continue.")
input("?")
game_menu()
# Function used to allow players to explore the area they are in.
def explore():
common.clear_screen()
curr_loc_id = character_data["travel"]
if location_data[curr_loc_id]["explore"] == 0:
print("You explore the area, yet find nothing. It seems there isn't much to see here. Try traveling somewhere else.")
print("Press return to continue.")
input("?")
game_menu()
else:
print("This part of the game is currently under construction.")
print("Press return to continue.")
input("?")
game_menu()
# Function used to allow players to buy from shops and sell items. I feel like this could be simplified. I'll look into it at some point, but it works for now. I think.
def shop_menu():
common.clear_screen()
curr_loc_id = character_data["travel"]
with open("data/shops.json", 'r') as f:
shops_data = json.load(f)
f.close()
with open("data/locations.json", 'r') as f:
location_data = json.load(f)
f.close()
if not location_data[curr_loc_id]["shops"]:
print("There are no shops here to find.")
print("Try visiting a town or village.")
print("Press return to continue.")
input("?")
game_menu()
else:
print("Please choose from the following shops by number.")
shop_number = 1
for shops in location_data[curr_loc_id]["shops"]:
print(str(shop_number) + ". " + shops_data[shops]["text-name"])
shop_number = shop_number + 1
selection = input("> ")
if selection.isdigit() == False:
common.clear_screen()
print("Your selection should be a number.")
print("Example: 1")
print("Press return to continue.")
input("?")
shop_menu()
selection = int(selection)
all_shops = location_data[curr_loc_id]["shops"]
shop_names = all_shops.keys()
shop_number = len(all_shops.keys())
if selection < 1:
print("You've selected an invalid shop.")
print("Press return to continue.")
input("?")
shop_menu()
elif selection <= shop_number:
selection = selection - 1
selection = list(shop_names)[selection]
go_shop(selection)
else:
common.clear_screen()
print("You've selected an invalid shop.")
print("Press return to continue.")
input("?")
shop_menu()
# Function to enable players to buy and sell items from a shop. Still need to work on this.
def go_shop(id):
common.clear_screen()
with open("data/shops.json", 'r') as f:
shops_data = json.load(f)
f.close()
print(shops_data[id]["text-name"])
print(shops_data[id]["text"])
print("What would you like to do?")
print("1. Buy Item")
print("2. Sell Item")
print("3. Return to Town")
selection = input("> ")
if selection == "1":
buy_item(id)
elif selection == "2":
sell_item(id)
elif selection == "3":
game_menu()
def buy_item(id):
common.clear_screen()
with open("data/shops.json", 'r') as f:
shops_data = json.load(f)
f.close()
with open("data/items.json", 'r') as f:
items_data = json.load(f)
f.close()
print("Which item would you like to buy?")
item_list = shops_data[id]["inventory"]
item_number = 1
for key in item_list:
print(str(item_number) + ". " + items_data[key]["text-name"] + ": " + str(shops_data[id]["inventory"][key]))
selection = input("> ")
# Will continue working on this later to see if the player has the gold to buy the item or not and whether they selected a valid item to purchase.
game_menu()
def sell_item(id):
common.clear_screen()
with open("data/items.json", 'r') as f:
items_data = json.load(f)
f.close()
game_menu()
# Have to actually invoke the main menu for it to show up.
main_menu() |
cd2c71a798c6f82ca08f59c5325db889771da90c | Kanac/Python | /outwitted steven.py | 73 | 3.765625 | 4 | lista = [1,2,3,4,5]
for x in range(len(lista)):
print (lista[x+1])
|
177d9f501c1481f70ff26147cdf9bbb5e025679f | jcorn2/Project-Euler | /prob10.py | 397 | 4.09375 | 4 | def isPrime(n):
#all even numbers except 2 aren't prime
if(n != 2 and n % 2 == 0):
return False
#checks if an odd number is a factor and thus n is not prime
for i in range(3,n // 2 + 1,2):
if(n % i == 0):
return False
return True
#list of primes
primes = [2]
#get primes below 2 million
for i in range(3,2000000,2):
print(i)
if(isPrime(i)):
primes.append(i)
print(sum(primes))
|
a800360276b7aa61472726d8c9c9889715699556 | ali35351/pythonw | /pythonw/tutoCalendar.py | 685 | 4.09375 | 4 | import calendar
print(calendar.weekheader(2)) # returns weekheader with length 2
print(calendar.firstweekday()) # prints 0 for monday
print(calendar.month(2020, 1)) # returns calendar of a month in calendar format
print(calendar.monthcalendar(2020, 1)) # returns calendar of a month in list format
print(calendar.calendar(2020)) # returns calendar of a year in calendar format
for i in range(1, 12): # returns calendar of a year in list format
print(calendar.monthcalendar(2020, i))
print(calendar.weekday(2020, 2, 28)) # returns weekday of a date
print(calendar.isleap(2020)) # returns true if 2020 is leap year
print(calendar.leapdays(2000, 2021)) # not included 2021
|
005551da399cfc45920540c135844077b89148e2 | joohee/DailyCoding | /Python/pdf/python_for_secret_agents/bit_byte_calculator.py | 1,398 | 3.765625 | 4 | class Calculator:
def __init__(self):
pass
def to_bits(self, v):
#print("to_bits")
b = []
for i in range(8):
# var i is unused.
b.append(v&1)
v >>= 1
#print("v", v)
return tuple(reversed(b))
def to_byte(self, b):
#print("to_byte")
v = 0
for bit in b:
#print("[before] v bit", v, bit)
v = (v << 1) | bit
#print("[after] v", v)
return v
def bit_sequence(self, list_of_tuples):
for t8 in list_of_tuples:
for b in t8:
yield b
def byte_sequence(self, bits):
byte = []
for n, b in enumerate(bits):
if n % 8 == 0 and n != 0:
yield self.to_byte(byte)
byte = []
byte.append(b)
yield self.to_byte(byte)
if __name__ == "__main__":
num = input("insert number:")
calc = Calculator()
bit_array = calc.to_bits(int(num))
print("bit_array", bit_array)
v = calc.to_byte(bit_array)
assert int(num) == v
# the arugment of bit_sequence function should be list of tuples.
list_of_bits = list(calc.bit_sequence([bit_array]))
print("bit_sequence", list_of_bits)
list_of_bytes = list(calc.byte_sequence(list_of_bits))
print("byte_sequence", list_of_bytes)
|
144e33323fc8618c612bc3dd7325669e74f467ee | Tevitt-Sai-Majji/fun-coding- | /navie pattren search algorithm.py | 512 | 3.828125 | 4 | #navie pattren search algorithm
def search(txt,ptt):
#txt is the text file and ptt is the string pattren
n=len(txt)
m=len(ptt)
for i in range(n-m+1):
#lehgth of txt file - pattren len
j=0
#to know letter count matched
while(j<m):
if txt[i+j]!=ptt[j]:
break#not equal break
else:
j+=1#equal incrmnt
if j==m:
print("pattren found at : ",i)
txt="AAABAAABBBABAABA"
ptt="AABA"
search(txt,ptt)
|
2e2d97227377a6a5e482daf634b8fd2a0403ef2c | mawillcockson/leetcode | /monthly_challenges/2020-06/w1-2_delete_node_linked_list.py | 1,473 | 4.21875 | 4 | """
Constraints:
- The linked list will have at least two elements.
- All of the nodes' values will be unique.
- The given node will not be the tail and it will always be a valid node of the linked list.
- Do not return anything from your function.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from typing import Any, Optional
# class ListNode:
# def __init__(self, x: Any):
# self.val = x
# self.next: Optional[ListNode] = None
class Solution:
def deleteNode(self, node: ListNode) -> None:
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
if not node.next:
return None
while node.next.next:
node.val = node.next.val
node = node.next
# This is just to satisfy mypy
if not node.next:
return None
node.val = node.next.val
node.next = None
# Submitted: https://leetcode.com/submissions/detail/348828725/?from=/explore/challenge/card/june-leetcoding-challenge/539/week-1-june-1st-june-7th/3348/
# I feel so dumb:
# class Solution:
# def deleteNode(self, node):
# """
# :type node: ListNode
# :rtype: void Do not return anything, modify node in-place instead.
# """
# node.val = node.next.val
# node.next = node.next.next
|
232c2e34761556ba52c0976fb4ccc07b642a4b39 | Divij-berry14/Python-with-Data-Structures | /Hashset.py | 1,165 | 3.515625 | 4 | class Bucket:
def __init__(self):
self.bucket=[]
def update(self,key):
found=False
for i, k in enumerate(self.bucket):
if key==k:
self.bucket[i]=key
found=True
break
if not found:
self.bucket.append(key)
def get(self,key):
for k in self.bucket:
if k==key:
return True
return False
def remove(self,key):
for k in self.bucket:
if k==key:
del k
class HashSet:
def __init__(self):
self.key_space=2096
self.hash_table=[Bucket() for i in range(self.key_space)]
def add(self,key):
index = key % self.key_space
self.hash_table[index].update(key)
def remove(self, key):
hash_key = key % self.key_space
self.hash_table[hash_key].remove(key)
def contains(self, key):
hash_key = key % self.key_space
return self.hash_table[hash_key].get(key)
ob = HashSet()
ob.add(1)
ob.add(3)
print(ob.contains(1))
print(ob.contains(2))
ob.add(2)
print(ob.contains(2))
ob.remove(2)
print(ob.contains(2))
|
6672b10b52bfb059cbaced6f8b2ec79ad7379c63 | shoaibrayeen/Python | /Sorting Algorithm/mergeTwoSortedLists.py | 1,383 | 4.65625 | 5 | def mergeTwoSortedLists(list1,list2,list3=[],index1=0,index2=0) :
'''
Objective : To merge two sorted lists into a 3rd list in sorted order
Input Parametrs :
list1 : First sorted list
list2 : Second sorted list
list3 : Merge sorted list of list1 and list2
index1 : Using for indexing of list1
index2 : Using for indexing of list2
Return Values : Merge Sorted list
'''
# Approach : Merge two sorted lists into a 3rd list using recursion
if ( index1 == len(list1) and index2 == len(list2) ) :
return list3
elif ( index1 == len(list1) or index2 == len(list2)) :
if ( index1 == len(list1)) :
list3.extend(list2[index2:])
return mergeTwoSortedLists(list1,list2,list3,index1,len(list2))
else :
list3.extend(list1[index1:])
return mergeTwoSortedLists(list1,list2,list3,len(list1),index2)
elif ( list1[index1] < list2[index2] ) :
list3.append(list1[index1])
return mergeTwoSortedLists(list1,list2,list3,index1+1,index2)
else :
list3.append(list2[index2])
return mergeTwoSortedLists(list1,list2,list3,index1,index2+1)
list1=[1,3,5,7]
list2=[1,2,3,4,6,8]
list3=mergeSortedLists(list1,list2)
print('1st Sorted List\t:\t', list1)
print('2nd Sorted List\t:\t', list2)
print('Merge Sorted List:\t', list3)
|
cc43ee6c762b8c44626312b55b2101ea58a1a4ca | dev-gupta01/C-Programs | /python/classes_and_objects.py | 761 | 3.921875 | 4 | class Robot:
def __init__(self,name,color,age):
self.name=name
self.color=color
self.age=age
def intro(self):
print("My name is: "+self.name)
print("My color is: "+self.color)
print("My age is: ",end="")
print(self.age)
print()
r1=Robot("Devashish","Red",20)
r2=Robot("Shubhashish","White",19)
r3=Robot("Nita","Yellow",42)
r1.intro()
r2.intro()
r3.intro()
class Person:
def __init__(self,n,p,i):
self.name=n
self.personality=p
self.is_sitting=i
def sit_down(self):
self.is_sitting=True
def stand_up(self):
self.is_sitting=False
p1=Person("Rajat","Normal",False)
p2=Person("Adi","Rich",True)
p1.robot=r1
p2.robot=r2
p1.robot.intro() |
74d36e60c227022c23cbd148434b2674811de178 | ather1/Pensions | /Python/Flight.py | 1,127 | 3.84375 | 4 | class Flight:
def __init__(self, origin,destination,duration):
self.origin = origin
self.destination = destination
self.duration = duration
self.Passengers = []
def Print_info(self):
print(f"The origin is: {self.origin}" )
print(f"The destination is: {self.destination}" )
print(f"The duration is: {self.duration} ")
for passenger in self.Passengers:
print(f"Passenger {passenger.name}")
else:
print("No passengers")
def delay(self,delay):
self.duration += delay
def add_passenger(self,newpassenger):
self.Passengers.append(newpassenger)
class Passenger:
def __init__(self, name):
self.name = name
def main():
f = Flight(origin="New York", destination= "Paris", duration=540)
p1= Passenger(name="Bod Jones")
p2= Passenger(name="Dave Smith")
f.duration += 10
f = Flight(origin="London", destination= "Paris", duration=60)
f.delay(100)
f.add_passenger(p1)
f.add_passenger(p2)
f.Print_info()
if __name__ == "__main__":
main()
|
29b73f8ee36f71edba6980a009bbbc5999ef526e | ijf8090/Python_the_hard_way_examples | /.github/workflows/ex18.py | 561 | 3.640625 | 4 | def print_two(*args):
arg1,arg2 = args
print("arg1: %r, arg2: %r" %(arg1,arg2))
def print_three(*args):
arg1,arg2, arg3 = args
print("arg1: %r, arg2: %r, arg3: %r" %(arg1,arg2, arg3))
def print_two_again(arg1, arg2):
print("arg1: %r, arg2: %r" %(arg1,arg2))
def print_one(arg1):
print("arg1: %r " % arg1)
def print_none():
print("I got nothing")
def print_none_2():
print("I STILL got nothing")
print_two("Ian", "Finlay")
print_two_again("Finlay", "Ian")
print_three("Ian", "Joseph", "Finlay")
print_one("Fisrt arg")
print_none();print_none_2();
|
e1689bda43a62123f8d50417fe05401a8134d0ef | chenhh/Uva | /uva_11308_set.py | 1,321 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Authors: Hung-Hsin Chen <chenhh@par.cse.nsysu.edu.tw>
License: GPL v2
status: AC
difficulty: 1
https://uva.onlinejudge.org/external/113/11308.pdf
"""
from collections import defaultdict
def main():
n_binder = int(input())
for _ in range(n_binder):
binder_name = input().strip()
n_ingredient, n_receipt, budget = list(map(int, input().split()))
prices = defaultdict(int)
for _ in range(n_ingredient):
ingredient, price = input().split()
prices[ingredient] = int(price)
costs = defaultdict(int)
for _ in range(n_receipt):
receipt_name = input().strip()
costs[receipt_name] = 0
k = int(input())
for _ in range(k):
ingredient, requirement = input().split()
costs[receipt_name] += prices[ingredient] * int(requirement)
# print
print(binder_name.upper())
# sort by cost first (ascending) then by cake name
sorted_data = sorted(costs.items(), key=lambda k: (k[1], k[0]))
if sorted_data[0][1] > budget:
print("Too expensive!")
else:
for name, cost in sorted_data:
if cost <= budget:
print(name)
print()
if __name__ == '__main__':
main()
|
c62f9e0154df7f00a5d8f1c8c4fae6e234a097fa | mbuhot/mbuhot-euler-solutions | /python/problem-055.py | 1,585 | 4.125 | 4 | #! /usr/bin/env python3
description = '''
Lychrel numbers
Problem 55
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).
Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.
How many Lychrel numbers are there below ten-thousand?
'''
def lychrel(x):
for i in range(0, 50):
reversedigits = int(str(x)[::-1])
x = x + reversedigits
isPalendrome = str(x) == str(x)[::-1]
if isPalendrome: return False
return True
assert(not lychrel(47))
assert(not lychrel(349))
assert(lychrel(4994))
print(sum(1 for x in range(0, 10000) if lychrel(x)))
|
2145718e2b07813b6293893d8d39a88ed7b4993f | vlad-ki/5_lang_frequency | /lang_frequency.py | 683 | 3.78125 | 4 | import re
from collections import Counter
def load_data(filepath):
with open(filepath) as file_handler:
return file_handler.read()
def text_replace(text):
text = text.replace('-\n', '')
text = text.replace('\n', ' ')
r_ex = re.compile(r'[\w]{3,}')
words = r_ex.findall(text)
return words
def get_most_frequent_words(text, count):
words = text_replace(text)
return Counter(words).most_common(count)
if __name__ == '__main__':
filepath = input('Введите путь к файлу: ')
top_words = get_most_frequent_words(load_data(filepath), 10)
for word, count in top_words:
print('{}: {}\n'.format(word, count))
|
6b628e9a2f9cfeea262d920a4678abe280df0632 | AlexeyTolpinskiy/Python_H | /HW-1.5.py | 782 | 3.953125 | 4 | #6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.
# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
# ребуется определить номер дня, на который общий результат спортсмена составить не менее b километров.
# Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня.
a = 2
b = 3
days = 1
while a < b:
a = a + a/10
days +=1
print(days)
|
541accc2a677b916215f08265c395733d4fd07de | burningskies42/advent_of_code | /day5/puzzle1.py | 855 | 3.734375 | 4 |
def assign_seat(half, seat_range):
range_len = len(seat_range)
if half in ["F", "L"]:
return seat_range[:int(range_len/2)]
elif half in ["B", "R"]:
return seat_range[int(range_len/2):]
def deduce_seat(boarding_pass_str):
seat_row = list(range(128))
seat_col = list(range(8))
for l in boarding_pass_str[:7]:
seat_row = assign_seat(l, seat_row)
for l in boarding_pass_str[7:]:
seat_col = assign_seat(l, seat_col)
return 8*seat_row[0] + seat_col[0]
all_boarding_passes = open("input.txt", "r").read().split("\n")
all_boarding_passes = sorted(list(map(deduce_seat, all_boarding_passes)))
puzzle1 = all_boarding_passes[-1]
print(f"puzzle1: {puzzle1}")
puzzle2 = set(range(all_boarding_passes[0], all_boarding_passes[-1])) - set(all_boarding_passes)
print(f"puzzle2: {list(puzzle2)[0]}")
|
8e351c48251a9e1f721f6986c6e24fa4e06c297e | huskydj1/CSC_630_Machine_Learning | /Python Crash Course/sorting.py | 1,777 | 3.640625 | 4 | import random
import numpy as np
from numpy.lib.function_base import insert
import time
def is_sorted(list):
for i in range(len(list)-1):
if (list[i] > list[i+1]):
return False
return True
def bogosort(list):
while True:
random.shuffle(list)
if is_sorted(list):
return list
def insertionsort(list):
for i in range(1, len(list)):
j = i-1
next = list[i]
while next < list[j] and j > -1:
list[j+1] = list[j]
j -= 1
list[j+1] = next
return list
def mergesort(list):
if len(list) < 20:
return insertionsort(list)
else:
first = list[0:len(list)//2]
second = list[len(list)//2:len(list)]
first = mergesort(first)
second = mergesort(second)
output = []
firstpointer = 0
secondpointer = 0
while (firstpointer < len(list)//2 and secondpointer < (len(list)+1)//2):
if (first[firstpointer] > second[secondpointer]):
output.append(second[secondpointer])
secondpointer += 1
else:
output.append(first[firstpointer])
firstpointer += 1
while (firstpointer < len(list)//2):
output.append(first[firstpointer])
firstpointer += 1
while (secondpointer < (len(list)+1)//2):
output.append(second[secondpointer])
secondpointer += 1
return output
list = [i for i in range(500000)]
random.shuffle(list)
list2 = list
merge_start = time.time()
mergesort(list)
merge_end = time.time()
print(f'Merge: {merge_end-merge_start}')
sort_start = time.time()
list2.sort()
sort_end = time.time()
print(f'Sort: {sort_end-sort_start}')
|
f652b82d8d45709300ea2101a59e74dcd7ab1a76 | mksk1999/guvi-problem | /a7.py | 87 | 3.546875 | 4 | s=input()
a=s[::-1]
if(a==s):
print(s[:-1])
else:
print(s)
|
e74a39eb0fe988f48654485e9d7e579d8c85f701 | ilkersenerr/PythonOdevler | /odev3.py | 1,109 | 3.71875 | 4 | class Ogrenci:
def __init__(self, ogrenciAdi, ogrenciSoyadi, ogrenciSinifi):
self.ogrenciAdi = ogrenciAdi
self.ogrenciSoyadi = ogrenciSoyadi
self.ogrenciSinifi = ogrenciSinifi
class Soru:
def NetSayisi(dogru, yanlis):
return dogru - yanlis * 0.25
def Hesapla(net):
return net * 2
if __name__ == "__main__":
ogrenci = Ogrenci(
input("Öğrenci adını giriniz: "),
input("Öğrenci soyadını giriniz: "),
input("Öğrenci sınıfını giriniz: "),
)
net = Soru.NetSayisi(
int(input("Doğru sayısını giriniz: ")),
int(input("Yanlış sayısını giriniz: "))
)
puan = Soru.Hesapla(net)
print(f"\nÖğrenci adı: {ogrenci.ogrenciAdi}" + \
f"\nÖğrenci soyadı: {ogrenci.ogrenciSoyadi}" + \
f"\nÖğrenci sınıfı: {ogrenci.ogrenciSinifi}" + \
f"\nNet sayısı: {net}" + \
f"\nPuan: {puan}") |
7c7dd392a9a956568df1fc8ef042a295ca471aa6 | jeandy92/Python | /ExerciciosCursoEmVideo/Mundo_3/ex103.py | 410 | 3.703125 | 4 | def ficha(nome='<Desconhecido>', gols=0):
print(f"O jogador {nome} fez {gols} gol(s) no Campeonato")
# Programa Principal
nome_jogador = str(input("Nome do Jogador: ")).title()
qtd_gols = str(input("Quantos gols foram marcados:"))
if qtd_gols.isnumeric():
qtd_gols = int(qtd_gols)
else:
qtd_gols = 0
if nome_jogador.strip() == '':
ficha(gols=qtd_gols)
else:
ficha(nome_jogador, qtd_gols)
|
7a5d2f83beab8d82d2c9e728a2755d6f7d36b9e6 | zzy0119/test | /mytest/test11_map.py | 138 | 3.734375 | 4 | # -*- coding:utf-8 -*-
def f(x):
return x * x
r = map(f, [1,2,3,4,5,6])
print(list(r))
r = map(str, [1,2,3,4,5,6])
print(list(r)) |
6875cce26577e2298da42931626e8d58a2e052c5 | 99002500/diabetiespredictonAI | /diabetes.py | 493 | 3.59375 | 4 | # This program detects if someone has diabeties or not
# import the libraries
import pandas as pd
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from PIL import Image
import streamlit as st
# Create a title and a subtitle
st.write("""
# Diabetes detection
Detect if someone has diabetes using machine learning and python
""")
# Open and display an image
image = Image.open("diabetes.png")
|
2bfb589c995320b7b593fa2c1c7d596d11f08d14 | Aasthaengg/IBMdataset | /Python_codes/p03997/s953606614.py | 73 | 3.53125 | 4 | a, b, h = (int(input()) for _ in range(3))
s = (a + b) * h // 2
print(s)
|
b4df4f4ace6ba16bb78256842e390b9829b48ff9 | wendful/hello-world | /my python/xr.py | 71 | 3.515625 | 4 | num= int(input("请输入一个数:"))
print(int(str(num)[::-1]))
|
dc3b64ab33cd89df999179b40a1138b82f2d0681 | michaelstresing/python_fundamentals | /07_file_io/07_02_writing.py | 426 | 4 | 4 | '''
Write a script that reads in the contents of words.txt and writes the contents in reverse
to a new file words_reverse.txt.
'''
wordlist = []
with open('words.txt', 'r') as fin:
for word in fin:
word = word.rstrip()
wordlist.append(word)
# print(wordlist)
wordlist.reverse()
with open('reversewords.txt', 'w') as fout:
for word in wordlist:
fout.write(f"{word}\n")
|
b7eef7493e186d9492e9e306510df287164390da | ryoichi551124/PythonBasic | /q11.py | 261 | 3.890625 | 4 | def reverse_order(num):
num_list =[]
str_num = str(num)
reverse_num = str_num[::-1]
for i in reverse_num:
num_list.append(i)
sepa_num_list = ' '.join(num_list)
print(f'"{sepa_num_list}"')
reverse_order(7536)
reverse_order(123) |
31ab431eecdf0ba408e286b1e6b894a0953f3706 | enzoprogrammer/mi_primer_programa | /lista_string_contador.py | 435 | 3.953125 | 4 | lista_usuario= []
lista_conteo= []
operar= "SI"
while operar != "NO":
string_usuario= input("Dime un frase para agregar a mi lista: ")
lista_usuario.append(string_usuario)
operar= input("Desea seguir agregando frases? Si/No :").upper()
if operar != "SI" and operar != "NO":
operar=input("Por favor escriba si o no! :").upper()
for dato in lista_usuario:
lista_conteo.append(len(dato))
print(lista_conteo) |
34402fdbcde9e9a639f7425ffa60a1a5ed6fc4b2 | jhonnjc15/holbertonschool-higher_level_programming | /0x0B-python-input_output/12-pascal_triangle.py | 945 | 3.875 | 4 | #!/usr/bin/python3
"""Module that list of lists of integers
representing the Pascal’s triangle
"""
def pascal_triangle(n):
"""Finds pascal triangle numbers up to n
Args:
n (int): the depth of pascal's triangle
"""
pascal_list = [[1]]
if n <= 0:
return []
else:
for i in range(1, n):
row_list = []
for j in range(i + 1):
try:
if j - 1 >= 0:
row_list.append(pascal_list[i - 1][j] +
pascal_list[i - 1][j - 1])
else:
raise IndexError()
except IndexError:
if j == 0:
row_list.append(pascal_list[i-1][j] + 0)
else:
row_list.append(0 + pascal_list[i-1][j-1])
pascal_list.append(row_list)
return pascal_list
|
fccd439af11a6b5a2e097cc6621c29b432f9043e | Daisy0828/Search | /tarray.py | 1,668 | 3.671875 | 4 | from searchproblem import SearchProblem
import numpy as np
# The transition array search problem, implemented as a SearchProblem
# States are array configurations.
# Read the assignment handout for details.
class TArray(SearchProblem):
def __init__(self, length):
self.start_state = TArray.random_start(length)
self.length = length
###### SEARCH PROBLEM IMPLEMENTATION ######
def get_start_state(self):
return self.start_state
def is_goal_state(self, state):
return state == tuple(np.arange(self.length).tolist())
def get_successors(self, state):
successors = [state[::-1]]
state = list(state)
for i in range(len(state)):
for j in range(i + 1, len(state)):
new_state = state.copy()
temp = new_state[j]
new_state[j] = new_state[i]
new_state[i] = temp
new_state = tuple(new_state)
successors += [new_state]
costs = [1 for i in range(len(successors))]
return dict(list(zip(successors, costs)))
@staticmethod
def random_start(length):
"""
Given the length of the transition array, produces a random start state.
"""
return tuple(np.random.permutation(length).tolist())
@staticmethod
def display_array(state):
"""
display the array in the state
"""
return state
@staticmethod
def print_path(track_path):
"""
Takes in a list of arrays and print the path separated by newlines.
"""
for b in track_path:
print(TArray.display_array(b))
|
b55468deaddeebfd91444c37e82f6fa12b91ecbf | jedzej/tietopythontraining-basic | /students/urtnowski_daniel/lesson_06_dicts_tuples_sets_args_kwargs/snakify_lesson_8.py | 950 | 4.21875 | 4 | #!/usr/bin/env python3
"""
snakify_lesson_8.py: Solutions for 2 of problems defined in:
Lesson 8. Functions and recursion
(https://snakify.org/lessons/functions/problems/)
"""
__author__ = "Daniel Urtnowski"
__version__ = "0.1"
def capitalize(lower_case_word):
first_char_ascii_value = ord(lower_case_word[0])
if first_char_ascii_value < ord('a') or first_char_ascii_value > ord('z'):
return lower_case_word
diff = ord('a') - ord('A')
first_letter_modified = chr(first_char_ascii_value - diff)
return first_letter_modified + lower_case_word[1:]
def uppercase():
words = input().split(' ')
for i in range(len(words)):
words[i] = capitalize(str(words[i]))
print(' '.join(words))
def reverse_the_sequence():
number = int(input())
if number != 0:
reverse_the_sequence()
print(number)
def main():
uppercase()
reverse_the_sequence()
if __name__ == '__main__':
main()
|
31e20d805a0e05803091fcbe86dc77219434a640 | zhangsanjin3355/zxpython | /36-函数的嵌套调用应用.py | 134 | 3.578125 | 4 | def print_line():
print("-"*50)
def print_5_line():
i=1
while i<5:
print_line()
i+=1
print_5_line()
|
6f05d194330d0d1604e6aa6259f135ad274211df | sornaami/luminarproject | /Flow Controls/looping stmnts/pgm number is prime.py | 243 | 4.03125 | 4 | #prime number checking
number=int(input("enter number"))
flg=0
for i in range(2,number):
if(number%i==0):
flg=1
break
else:
flg=0
if(flg>0):
print("not prime")
else:
print("prime number") |
17142bd444f94370a2e59fb0c8f630f183b7b2ee | gustavocrod/neural_networks | /artificial_neuron_networks/artificial_neuron/artificial_neuron.py | 2,197 | 3.6875 | 4 | import abc
import numpy as np
import math
class ArtificialNeuron(object):
__metaclass__ = abc.ABCMeta
"""
Classe abstrata
Adaline:
equacao de ajuste obtida para a saida linear
Perceptron:
equacao de ajuste obtida para a saida do nodo apos a aplicacao da funcao de ativacao
"""
def __init__(self, meta, previsores):
self.weights = np.array([2 * np.random.random() - 1, 2 * np.random.random() - 1,
2 * np.random.random() - 1, 2 * np.random.random() - 1])
self.target = np.array(meta) # saida esperada
self.learnTax = 0.0025 # taxa de aprendizado - eta
self.precisionTax = 0.000001 # taxa de precisao
self.previsores = np.array(previsores) # vetores de entradas com x[0] = bias
@abc.abstractmethod
def ActivationFunction(self, sum):
"""
perceptron -> f(x){ 1 se w . x + b >= 0
{ -1 senao
adaline -> regra delta para gradiente descendente - minimos quadrados
-> tanh(x)
:param sum: recebe o valor do somatorio - saida calculada
:return: retorna o valor de ativacao
"""
pass
@abc.abstractmethod
def Train(self):
pass
def ShowWeights(self):
"""
mostra o vetor de pesos atual
:return:
"""
print("Pesos: ", self.weights)
def UpdateWeigth(self, error, previsores):
"""
atualiza os n pesos sinapticos do neuronio (weights)
1. peso(k+1) = peso(k) + (taxaDeAprendizagem * erro * input[i])) ==== perceptron
2. peso(k+1) = peso(k) + (taxaDeAprendizagem * (valorDesejado - sum) * input[i] ) ==== adaline
"""
for i in range(len(self.weights)):
self.weights[i] += self.learnTax * error * previsores[i]
def Sum(self, reg):
"""
representa o somatorio da formula
:param reg: um registro da matriz, e.g (1, -1)
:return: retorna o somatorio de p(i) * w(i) + bias
"""
return reg.dot(self.weights) # produto escalar
|
881e4d96d01adb16225f48502ff230a93a20d3be | kod3r/search-script-scrape | /scripts/100.py | 967 | 3.515625 | 4 | # The California city whose city manager earns the most total wage per population of its city in 2012
import csv
import requests
from io import BytesIO
from zipfile import ZipFile
YEAR = 2012
def foosalary(row):
return float(row['Total Wages']) / int(row['Entity Population'])
url = 'http://publicpay.ca.gov/Reports/RawExport.aspx?file=%s_City.zip' % YEAR
print("Downloading:", url)
resp = requests.get(url)
with ZipFile(BytesIO(resp.content)) as zfile:
fname = zfile.filelist[0].filename # 2012_City.csv
rows = zfile.read(fname).decode('latin-1').splitlines()
# first 4 lines are Disclaimer lines
managers = [r for r in csv.DictReader(rows[4:]) if r['Position'].lower() == 'city manager'
and r['Total Wages']]
topman = max(managers, key = foosalary)
print("City: %s; Pay-per-Capita: $%s" % (topman['Entity Name'], int(foosalary(topman))))
# City: Industry; Pay-per-Capita: $465
|
bd24883cc575e9d23ba64fdc1ce551fe5004b8c7 | karthikavijayan9696/Training | /pythontask/task10.py | 495 | 4.125 | 4 | count = int(input('How many of you liked the post: '))
names = []
if count == 0:
print('Nobody likes this')
else:
print(f'Enter names of {count} who liked the post ')
for i in range(count):
names.append(input())
if count == 1:
print(f'{names[0]} likes this')
elif count == 2:
print(f'{names[0]} and {names[1]} likes this')
elif count == 3:
print(f'{names[0]},{names[1]} and {names[2]} likes this')
else:
print(f'{names[0]},{names[1]} and {count-2} others likes this') |
c982eaea1105c7e8488b5cb025451260bf3abbde | tanvir-ux/simpleNeuralNetwork | /neuralNetwork.py | 734 | 3.609375 | 4 | weight = 0.1
def neural_network(input,weight):
prediction = input*weight;
return prediction
number_of_toes = [8.5,9.5,10,9]
input = number_of_toes[0]
pred = neural_network(input,weight)
print(pred)
# output should be 0.8500000000000001
#because pred = 8.5 * 0.1
#multiple inputs
def w_sum(a,b):
assert(len(a) == len(b))
output = 0
for i in range(len(a)):
output += (a[i] * b[i])
return output
weights = [0.1,0.2,0]
def neural_network(input,weights):
pred = w_sum(input,weights)
return pred
toes = [8.5,9.5,9.9,9.0]
wlrec = [0.65,0.8,0.8,0.9]
nfans = [1.2,1.3,0.5,1.0]
input = [toes[0],wlrec[0],nfans[0]]
pred = neural_network(input,weights)
print(pred)
# output should be 0.9800000000000001 |
05b665b56c7967868c3c848293efad8e0b334f99 | eamonyates/pp25_guessing_game_two_solutions | /PP25_GuessingGameTwo.py | 1,428 | 3.90625 | 4 | import time, math
def start():
print ('\nThink of a number between 1 and 100')
time.sleep(1)
print ('Don\'t tell me what it is...')
time.sleep(1.5)
numberList = list(range(1, 101))
number = math.ceil(len(numberList) / 2)
counter = 1
return (numberList, number, counter)
def computerNumberGuess():
x = start()
numberList = x[0]
number = x[1]
counter = x[2]
while True:
guessResult = str(input('\nIs it higher, lower or equal to ' + str(number) + \
'? \n(H for higher, L for lower, E for equal. Type \'EXIT\' at any point to leave): '))
if guessResult.lower() == 'exit':
break
elif guessResult.lower() == 'h':
numberList = list(range(number + 1, (numberList[-1] + 1)))
number += math.ceil(len(numberList) / 2)
counter += 1
elif guessResult.lower() == 'l':
numberList = list(range(numberList[0], number))
number -= math.ceil(len(numberList) / 2)
counter += 1
elif guessResult.lower() == 'e':
print ('\nYou were thinking of the number ' + str(number) + '.')
time.sleep(1)
print ('This was found in ' + str(counter) + ' guesses.')
time.sleep(1.5)
pass
playAgain = str(input('\nWould you like to play again? \n(Y for yes, N for no): '))
if playAgain.lower() == 'y':
x = start()
numberList = x[0]
number = x[1]
counter = x[2]
continue
else:
break
if __name__ == '__main__':
computerNumberGuess()
|
40dd00ca6410a7d84011851e7cfb058462cc2ffb | wangpeihu/algorithm017 | /Week_03/Construct_Binary_Tree_form_Preorder_and_Inorder_Traversal.py | 1,870 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
'''
#第一种方法:递归
if len(inorder) == 0:
return None
root = TreeNode(preorder[0])
mid = inorder.index(preorder[0])
root.left = self.buildTree(preorder[1:mid + 1], inorder[:mid])
root.right = self.buildTree(preorder[mid + 1:], inorder[mid + 1:])
return root
'''
'''
#第二种方法:递归
def buildTreeHelper(pre_left, pre_right, in_left, in_right):
if pre_left > pre_right:
return None
preroot = pre_left
root = TreeNode(preorder[preroot])
#获取根节点在中序遍历列表中的下标
inroot = index[preorder[preroot]]
size_of_left_subtree = inroot - in_left
#递归构造左右子树
root.left = buildTreeHelper(pre_left + 1, pre_left + size_of_left_subtree, in_left, inroot - 1)
root.right = buildTreeHelper(pre_left + size_of_left_subtree + 1, pre_right, inroot + 1, in_right)
return root
n = len(preorder)
#字典生成式
index = {element:i for i, element in enumerate(inorder) }
return buildTreeHelper(0, n-1, 0, n-1)
'''
#第三种方法
def build(stop):
if inorder and inorder[-1] != stop:
root = TreeNode(preorder.pop())
root.left = build(root.val)
inorder.pop()
root.right = build(stop)
return root
preorder.reverse()
inorder.reverse()
return build(None) |
5348764de1b27b68a5145456b8e820572145c2af | AlexisPA19/Analisis-de-algoritmos | /MatEnCad.py | 3,603 | 3.578125 | 4 | from tkinter import ttk
from tkinter import*
class MultMat:
def __init__(self,window):
self.wind = window
self.wind.title('Multiplicación de Matrices en cadena')
#Creating a Frame Container
frame = Frame(self.wind)
frame.grid(row = 0, column = 0, columnspan = 3, pady = 20)
#NumMat Input
Label(frame, text = 'Número de matrices: ').grid(row = 1, column = 0)
self.numMat = Entry(frame)
self.numMat.focus()
self.numMat.grid(row = 1, column = 1)
#Button
ttk.Button(frame, text = 'Aceptar',command =self.dimenMat).grid(row = 1, column = 3)
#Creating input size mat
def dimenMat(self):
tam = int(self.numMat.get())
frame1 = LabelFrame(self.wind, text = 'Matrices')
frame1.grid(row = 1, column = 0, columnspan = 3, pady=20)
self.fila = []
self.columna = []
for x in range(tam):
Label(frame1, text = 'M{}→'.format(x)).grid(row = x+1, column = 0)
Label(frame1, text = 'Fila: ').grid(row = x+1, column = 1)
Label(frame1, text = 'Columna: ').grid(row = x+1, column = 3)
self.fila.append(Entry(frame1))
self.columna.append(Entry(frame1))
self.fila[x].grid(row = x+1, column = 2)
self.columna[x].grid(row = x+1, column = 4)
ttk.Button(frame1, text = 'Calcular',command =self.table).grid(row = tam+1, column = 2)
def table(self):
tam = int(self.numMat.get())
frame2 = LabelFrame(self.wind, text = 'Tabla')
frame2.grid(row = tam+2, column = 0)
SUB = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉")
self.table = []
for i in range(tam+1):
self.table.append([])
for j in range(tam+1):
self.table[i].append(Label(frame2,font="arial36",bg="#EEE0DE",relief="ridge",pady=30,padx=30,text=" "))
self.table[i][j].grid(row = i, column = j)
for i in range(tam+1):
for j in range(tam-i):
self.table[j+i+1][i].config(text=" X ")
for i in range(1,tam+1):
self.table[i][0].config(text="M{}".format(i-1))
self.table[0][i].config(text="M{}".format(i-1))
self.table[i][i].config(text=" X ")
for i in range(1,tam+1):
for j in range(tam-i):
self.table[i][j+i+1].config(text=" Z ")
for x in range(tam):
print("Fila{}:{} Columna{}:{}".format(x,int(self.fila[x].get()),x,int(self.columna[x].get())))
self.multmatcad()
def multmatcad(self):
tam = int(self.numMat.get())
self.tamMatList = []
for i in range(tam):
self.tamMatList.append((int(self.fila[i].get()),int(self.columna[i].get())))
print(self.tamMatList)
listM=[]
for i in range(tam):
listM.append([])
for j in range(tam):
listM[i].append(None)
for i in range(tam):
listM[i][i]=0
for i in range(tam):
for j in range(tam-i-1):
listM[i][j+i+1] =
for i in range(tam):
for j in range(tam):
print(listM[i][j],end=" ")
print("\n")
if __name__ == '__main__':
window = Tk()
application = MultMat(window)
window.mainloop() |
a90b6cc432f22d1c6d2ec122cd8daa16b45b09c9 | DiegoPorfirio01/PYTHON-BASICO-40H | /NOMECONTAGEM.py | 451 | 3.859375 | 4 | frase = str(input('Qual seu nome completo?')).strip()
print('O seu nome completo em maiuscula é {}'.format(frase.upper()))
print('O seu nome completo em minusculas é {}'.format(frase.lower()))
print('O SEU NOME COMPLETO TEM {} LETRAS '.format(len(frase) - frase.count(' ')))
#print(' O SEU PRIMEIRO NOME TEM {}' .format(frase.find(' ')))
separa = frase.split()
print('Seu primeiro nome é {} e ele tem {} letras'.format(separa[0] , len(separa[0])))
|
912012775ff30eb425d2683d3d3019f6623b8ac4 | DSawtelle/ScammerSpammer | /scammerSpammer.py | 6,998 | 3.75 | 4 | """ Author: Daniel J. Sawtelle
*** Purpose: Bombard the given URL with randomized form return data
***
*** Source: https://www.youtube.com/watch?v=UtNYzv8gLbs
"""
import os
import random
import string
import json
import time
import requests
""" Function - Return a string object of a date formatted as specified
*** start: First date possible to select
*** end: Last date possible to select
*** format: Structure of the date string being returned
*** prop: Proportion of the distance to jump into the specified date range
***
*** Source: https://stackoverflow.com/questions/553303/generate-a-random-date-between-two-other-dates
"""
def str_time_prop(start, end, format, prop):
#Retrieve the start and end dates as a time object
stime = time.mktime(time.strptime(start, format))
etime = time.mktime(time.strptime(end, format))
#Evaluate the proportion of the date range to jump to
ptime = stime + prop * (etime - stime)
#Return a string object of the date tracked
return time.strftime(format, time.localtime(ptime))
#Seed the random instance for generating data for the bombardment
random.seed = (os.urandom(1024))
#URL of the address to spam with data
url = 'AddressOfScammerGoesHere'
"""---------------- Main Function : Bombard the URL with randomized data ----------------"""
#Get an object of the list of names (first and last), streets, and companies to use for data spamming
fNames = json.loads(open('FirstNames.json').read())
lNames = json.loads(open('LastNames.json').read())
street = json.loads(open('StreetNames.json').read())
company = json.loads(open('CompanyNames.json').read())
country = json.loads(open('USVariations.json').read())
na = json.loads(open('NAVariations.json').read())
#Track the number of data bombardments done during this script call
dataCount = 1
while True:
#Generate a random city/state pairing
state = random.choice(json.loads(open('StateAbbreviations.json').read()))
city = random.choice(json.loads(open('StateCities\\'+ state + 'Cities.json').read()))
#Person Information
PName = random.choice(fNames) + ' ' + random.choice(lNames)
PAppartmentNumber = str(random.randint(1, 999))
if random.choice([True, False]):
PAppartmentNumber = random.choice(na)
PAddress = str(random.randint(1, 10000)) + ' ' + random.choice(street)
PCity = city
PState = state
PZip = ''.join(random.choice(string.digits) for i in range(5))
PCountry = random.choice(country)
PPhoneNumber = '(' + ''.join(random.choice(string.digits) for i in range(3)) + ') ' + ''.join(random.choice(string.digits) for i in range(3)) + '-' + ''.join(random.choice(string.digits) for i in range(4))
#Employer Information
EName = random.choice(company)
EEIN = ''.join(random.choice(string.digits) for i in range(2))
if random.choice([True, False]):
EEIN = ''.join(random.choice(string.ascii_letters)) + EEIN
if random.choice([True, False]):
EEIN = EEIN + '-'
EEIN = EEIN + ''.join(random.choice(string.digits) for i in range(7))
if random.choice([True, False]):
EEIN = EEIN + ''.join(random.choice(string.digits))
EAddress = ''.join(random.choice(string.digits) for i in range(4)) + ' ' + random.choice(street)
ECity = city
EState = state
EZip = PZip[:3] + ''.join(random.choice(string.digits) for i in range(2))
ECountry = random.choice(country)
EPhoneNumber = '(' + ''.join(random.choice(string.digits) for i in range(3)) + ') ' + ''.join(random.choice(string.digits) for i in range(3)) + '-' + ''.join(random.choice(string.digits) for i in range(4))
#Government/Financial Information
EDOB = str_time_prop('01/01/1970', '12/31/2011', '%m/%d/%Y', random.random())
ESSN = ''.join(random.choice(string.digits) for i in range(3)) + '-' + ''.join(random.choice(string.digits) for i in range(2)) + '-' +''.join(random.choice(string.digits) for i in range(4))
EDLNumber = 'D' + ''.join(random.choice(string.digits) for i in range(8))
EState = state
EDLIssueDate = str_time_prop('01/01/1970', '12/31/1970', '%m/%d/%Y', random.random())[:-4] + str(int(EDOB[-4:]) + random.randrange(16, 35))
EDLExpireDate = EDOB[:-4] + str(int(EDOB[-4:]) + 6)
if state == 'AZ':
EDLExpireDate = EDOB[:-4] + str(int(EDOB[-4:]) + 65)
AGI = ''.join(str(random.randint(1, 99))) + ',' + ''.join(random.choice(string.digits) for i in range(3)) + '.' + ''.join(random.choice(string.digits) for i in range(2))
if random.choice([True, False]):
AGI = '$' + AGI
if random.choice([True, False]):
AGI = str(random.randint(0, 87986)) + '.' + ''.join(random.choice(string.digits) for i in range(2))
if random.choice([True, True, False, False, False]):
notApp = random.choice(na)
EName = notApp
EEIN = notApp
EAddress = random.choice(na)
ECity = notApp
EState = notApp
EZip = notApp
ECountry = notApp
AGI = random.choice([notApp, "0"])
if random.choice([True, False, False, False]):
EName = random.choice(["Self", "Self Employed", "self empl.", "self employed"])
AGI = ''.join(str(random.randint(1, 4))) + ',' + ''.join(random.choice(string.digits) for i in range(3)) + '.' + ''.join(random.choice(string.digits) for i in range(2))
if random.choice([True, False]):
AGI = '$' + AGI
if random.choice([True, False]):
AGI = str(random.randint(0, 4999)) + '.' + ''.join(random.choice(string.digits) for i in range(2))
#Send the data bombardment to the URL
requests.post(url, allow_redirects=False, data={
'textfield' : PName,
'textfield2' : PAppartmentNumber,
'textfield3' : PAddress,
'textfield4' : PCity,
'textfield5' : PState,
'textfield6' : PZip,
'textfield7' : PCountry,
'textfield8' : PPhoneNumber,
'textfield9' : EName,
'textfield18': EEIN,
'textfield10': EAddress,
'textfield11': ECity,
'textfield12': EState,
'textfield13': EZip,
'textfield14': ECountry,
'textfield15': EPhoneNumber,
'textfield16': EDOB,
'textfield17': ESSN,
'textfield19': EDLNumber,
'textfield20': EState,
'textfield22': EDLIssueDate,
'textfield23': EDLExpireDate,
'textfield21': AGI,
'Submit': 'UAccess - CARES Fund'
})
#Display general random bombardment information sent this generation
print(str(dataCount) + ' Sending Data - ')
print(' Name : ' + PName)
print(' Apartment: ' + PAppartmentNumber)
print(' Address : ' + PAddress)
print(' City : ' + PCity)
print(' State : ' + PState)
print(' Zip Code : ' + PZip)
print(' Country : ' + PCountry)
print(' Phone : ' + PPhoneNumber)
print(' Employer : ' + EName)
print(' EIN : ' + EEIN)
print(' Address : ' + EAddress)
print(' City : ' + ECity)
print(' State : ' + EState)
print(' Zip : ' + EZip)
print(' Country : ' + ECountry)
print(' Phone : ' + EPhoneNumber)
print(' DOB : ' + EDOB)
print(' SSN : ' + ESSN)
print(' DL Number: ' + EDLNumber)
print(' DL Issued: ' + EDLIssueDate)
print(' DL Expire: ' + EDLExpireDate)
print(' AGI : ' + AGI)
#Increment the Bombardment Count
dataCount = dataCount + 1 |
7a8ea8c18c205fc3c8ef0fbafe4f692451458899 | cwavesoftware/python-ppf | /ppf-ex04/even.py | 100 | 4.125 | 4 | print("Enter number?")
num = int(input())
is_even = (num % 2) == 0
print("Number is even: ",is_even) |
bbf07cae1eaa68d596894f1614340627a77055f4 | meggangreen/advent-code-2018 | /files/day-20.py | 6,954 | 3.78125 | 4 | """ Let's make some trees """
# this is "implement jsonify"
import re
from collections import deque
# class Section:
# """ A section of the route in which there are no deviations -- ie each node,
# a letter, has only one child -- because I think it will save in counting.
# 'children' is a list of Sections.
# """
# def __init__(self, doors): #, start, children=None):
# self.data = doors
# # self.start = float('inf') * -1
# # self.len = len(self.data)
# self.children = None
# def locate(self, start):
# self.start = start
# def adopt(self, children):
# if not self.children:
# self.children = []
# self.children.extend(children)
# # self.children.sort(key=lambda child: child.start)
# class Route:
# """ The tree of Sections """
# def __init__(self, root):
# self.root = root
# def find_most_doors_no_repeat(self, to_visit=None):
# """ DFS shortest path to farthest end """
# path = deque()
# doors = 0
# if not to_visit:
# to_visit = [self.root]
# while to_visit:
# section = to_visit.pop()
# if section.children:
# to_visit.extend(section.children)
# route = Route(section)
# doors += route.find_most_doors_no_repeat(to_visit)
# else:
# import pdb; pdb.set_trace()
# path.appendleft(section)
# doors += section.len
# return doors
# def walk_through_doors(section):
# pass
def remove_skip(puzzle_in):
match = re.search(skip, puzzle_in)
if match:
puzzle_in = puzzle_in[:match.span()[0]] + puzzle_in[match.span()[1]:]
return puzzle_in
# def find_next_closer(puzzle_in):
# match = re.search(closer, puzzle_in)
# if match:
# return match.start()
# def find_last_closer(puzzle_in):
# matches = [m for m in re.finditer(closer, puzzle_in)]
# if matches:
# return matches[-1].start()
# def find_penult_closer(puzz_in):
# matches = [m for m in re.finditer(closer, puzzle_in)]
# if matches:
# return matches[-2].end()
# def find_opener(puzzle_in):
# match = re.search(opener, puzzle_in)
# if match:
# return match.end() # + 1
# def explore(puzzle_in):
# sections = []
# # if there is a path to skip, skip it
# if puzzle_in[-1] == '|':
# return
# start = find_opener(puzzle_in)
# if not start:
# sections.extend([Section(r) for r in puzzle_in.split('|')])
# else:
# # import pdb; pdb.set_trace()
# # this is not finding my last ')'
# end = find_last_closer(puzzle_in)
# to_explore = puzzle_in[start:end]
# sections.extend([Section(r) for r in puzzle_in[:start-1].split('|')])
# parent = sections.pop()
# if parent == 'EEN':
# print("\n\n\nPARENT: EEN\n\n\n")
# # import pdb; pdb.set_trace()
# parent.adopt(explore(to_explore))
# sections.append(parent)
# return sections
# def balance_parens(puzz_in):
# sections = []
# start = None
# end = -1
# for i, p in enumerate(puzz_in):
# if p == '(':
# import pdb; pdb.set_trace()
# start = end + 1 # 0 if not end else end + 1
# end = i
# sections.append(puzz_in[start:end])
# if p == ')':
# import pdb; pdb.set_trace()
# start = end + 1
# end = i
# children = [Section(char) for char in puzz_in[start:end].split('|')]
# # only gets preceeding parents
# parent_level = [Section(char) for char in sections.pop().split('|')]
# parent_level[-1].adopt(children)
# def make_edges_list(puzz_in, i=0):
# sections = []
# children = []
# mid = -1
# start = mid + 1
# mid = find_opener(puzz_in)
# dle = find_penult_closer(puzz_in)
# end = find_last_closer(puzz_in)
# before = puzz_in[start:mid]
# after = puzz_in[dle:end]
# for b in before.split('|'):
# i += 1
# sections.append(Section(str(i), sect))
# for group in (before, after):
# next_level = puzz_in[mid+1:dle]
# for g in group.split('|')
# to_section = before.split('|')
# for sect in to_section:
# i += 1
# sections.append(Section(str(i), sect))
# children, i = make_edges_list(next_level, i)
# sections[-1].adopt(children)
# to_section = after.split('|')
# for sect in to_section:
# if sect:
# i += 1
# sections.append(Section(str(i), sect))
# return sections, i
class Node:
def __init__(self, data):
self.data = data
self.children = []
def parse_nested_string(puzzle_input):
# returns list of lists
symbs = '(|)'
if not puzzle_input:
return []
result = []
node = None
i = -1
# import pdb; pdb.set_trace()
while i < len(puzzle_input):
i += 1
if puzzle_input[i] not in symbs:
if not node:
node = Node(puzzle_input[i])
result.append(node)
else:
child = Node(puzzle_input[i])
node.children.append(child)
node = child
# key = str(i) # puzzle_input[i]
# if key:
elif puzzle_input[i] == '(':
# key = ''.join(key)
result.append(parse_nested_string(puzzle_input[i+1:]))
# result.append({key: value})
# key = []
elif puzzle_input[i] == '|':
# if puzzle_input[i+1] == ')':
# key = []
# return result
# # i += 1
# continue
node = None
# key = ''.join(key)
# value = []
# result.append({key: value})
# key = []
elif puzzle_input[i] == ')':
key = ''.join(key)
value = []
result.append({key: value})
key = []
return result
###################
if __name__ == '__main__':
skip = re.compile(r'\([\w\|]+\|\)')
opener = re.compile(r'\(')
closer = re.compile(r'\)') # re.compile(r'\)[\w]*$')
level = '()'
with open('day-20.txt', 'r') as file:
puzzle_input = file.read().strip()[1:-1]
# get rid of optional paths early
# print(len(puzzle_input)) # 14323
while True:
puzzle_length = len(puzzle_input)
puzzle_input = remove_skip(puzzle_input)
if puzzle_length == len(puzzle_input):
break
with open('day-20-clean.txt', 'w') as file:
file.write(puzzle_input)
# print(len(puzzle_input)) # 11418
# root = explore(puzzle_input)[0]
# route = Route(root)
|
54c17bed0fddc3a04215d9b0e5b2143059b0dfdf | alexDx12/gb_python | /lesson_8/exercise_1.py | 1,789 | 3.75 | 4 | """
1) Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде
строки формата «день-месяц-год». В рамках класса реализовать два метода. Первый, с
декоратором @classmethod. Он должен извлекать число, месяц, год и преобразовывать их тип
к типу «Число». Второй, с декоратором @staticmethod, должен проводить валидацию числа,
месяца и года (например, месяц — от 1 до 12). Проверить работу полученной структуры на
реальных данных.
"""
class Data:
def __init__(self, data_string):
self.data_string = data_string
@classmethod
def data_execution(cls, data_string):
data_list = data_string.split('-')
new_list = [int(i) for i in data_list]
print(f'Число: {new_list[0]}\nМесяц: {new_list[1]}\nГод: {new_list[2]}')
@staticmethod
def data_validation(data_string):
data_list = data_string.split('-')
new_list = [int(i) for i in data_list]
if new_list[0] < 1 or new_list[0] > 31:
print('День введён некорректно.')
if new_list[1] < 1 or new_list[1] > 12:
print('Месяц введён некорректно.')
if new_list[2] < 2000 or new_list[1] > 2021:
print('Год введён некорректно.')
data_1 = '06-04-2005'
data_2 = '00-00-1900'
Data.data_execution(data_1)
Data.data_validation(data_1)
Data.data_execution(data_2)
Data.data_validation(data_2)
|
3f98f4c9009e4cb5d8710f7267f9f6cb57fa67dd | tiduswr/Algoritimos_P1_UEPB_CCEA_CAMPUS_VII | /Lista 02/lista02ex13.py | 1,482 | 3.828125 | 4 | #Deixando o programa amigavel:
print('=' * 50)
print('{:^50}'.format('Banco 24hrs'))
print('='*50)
valor = int(input('Quanto você deseja sacar? R$ '))
print('')
#Nomeando variaveis:
total = valor
ced = 100
totced = 0
#Tive que aprender esse código novo, pois eu não estava conseguindo fazer de outra forma que foi explicada na aula:
while True:
#Ele vai passar por esse If se o Valor Total for maior ou igual ao da cédula e adicionar mais 1 ao contador na cedula:
if total >= ced:
total = total - ced
totced = totced + 1
#Quando ele esgotar as possibilidades com uma das cedulas ele vai printar quantas cedulas ele conseguiu tirar do total e qual era o valor da cedula:
else:
if totced > 0:
print('Você recebera {} cédula(as) de R$ {}'.format(totced,ced))
#Depois ele vai trocar os valores da cedula até conseguir zerar o valor total informado no inicio do programa:
if ced == 100:
ced = 50
elif ced == 50:
ced = 20
elif ced == 20:
ced = 10
elif ced == 10:
ced = 5
elif ced == 5:
ced = 1
#É muito importante zerar as cedulas no final, pois se não o programa vai misturar a quantidade de todas as cedulas:
totced = 0
#Quando ele conseguir zerar o valor total ele vai parar o looping:
if total == 0:
break
#Abaixo é somente uma linha para deixar o programa mais amigavel:
print('\nObrigado por usar nosso Banco 24hrs!\n')
print('=' * 50)
print('{:^50}'.format('Volte Sempre!'))
print('='*50) |
da433c9f5c17fd0e7c77d4f95011740e73804d60 | Ashwinbicholiya/Python | /Python/assignment/30numpy.py | 189 | 4.0625 | 4 | #add 2 arrays using forloop
from numpy import *
arr1=array( [1,2,3,4])
arr2=array([1,2,3,4])
arr3= empty(4,int)
for i in range(len(arr1)):
arr3[i] = (arr1[i] + arr2[i])
print(arr3) |
0a653bbbfa79a08a206d4c141d0b5eea0514ff61 | Shaaman331/Dev-Aprender-Aulas | /Aula10.recebendo_dadds_usuario.py | 602 | 4.28125 | 4 | ''''
Função Input
* O input()função permite a entrada do usuário.
* Use o parâmetro prompt para escrever uma mensagem antes da entrada:
Função Int
* O int()função converte o especificado valor em um número inteiro
* Converte uma string em valor inteiro
'''
print('Função Input')
print('Enter your name:')
x = input()
print('Hello, ' + x)
print()
x = input('Enter your name:')
print('Hello, ' + x)
print(input('Onde vocẽ mora ?'))
print()
print('Função Int')
x = int(3.5)
print(x)
print()
buscar_paginas = int(input('Quantas páginas buscar?'))
print(type(buscar_paginas))
|
36917421e0461f2c37ab18ad7879c9bddd9c3080 | danielcz007/pycharm2021project0416 | /practice/5python常见数据结构.py | 2,134 | 3.921875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2021/1/24 21:33
# @Author : Daniel
'''
列表
定义:
- python中可以通过组合一些值,得到多种复合数据类型
- 列表是其中最常见的数据结构
- 列表通过
元组: () 元素不可修改
字典:键值对 {}
集合:用 set() 关键字创建 {}
'''
list_test = ['a', 'b', 'c', 'n', 'd', 1, 2, 3, 4, 5, 7, 8, 1, 'c', 'a', 0]
list_int = [1, 2, 5, 9, 7, 66, 0, 5, 0, 3, 9]
seq_test = (1, 4, 7, 3, 2, 77, 'a', 'df')
''' list 练习
# 序号 函数
# len(list)
print(len(list_test))
# 表元素个数
# max(list) 列表必须是数字
print(max(list_int), list_int)
# 回列表元素最大值
# min(list)
print(min(list_int), list_int)
# 回列表元素最小值
# list(seq)
# 元组转换为列表
print(list(seq_test), seq_test)
# list.append(obj)
# 列表末尾添加新的对象
list_test.append("append")
print(list_test)
# list.count(obj)
# 计某个元素在列表中出现的次数
print(list_test.count(1))
print(list_int.count(0))
# list.extend(seq)
# 列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
list_test.extend(seq_test)
print(list_test)
# list.index(obj)
# 列表中找出某个值第一个匹配项的索引位置
print(list_test.index(1))
# list.insert(index, obj)
# 对象插入列表
list_int.insert(10, "ten")
print(list_int)
list_int[10] = 10
print(list_int)
# list.pop([index=-1])
# 除列表中的一个元素(默认最后一个元素),并且返回该元素的值
print(list_int.pop())
print(list_int)
# list.remove(obj)
# 除列表中某个值的第一个匹配项
list_test.remove(1)
print(list_test)
# list.reverse()
#
# 反向列表中元素
print("===========")
list_int.reverse()
print(list_int)
# list.sort( key=None, reverse=False)
# 原列表进行排序
list_int.sort()
print(list_int)
list_int.reverse()
print(list_int)
# list.copy()
# 制列表
list_int_copy = list_int.copy()
print(list_int_copy)
# list.clear()
# 空列表
list_int_copy.clear()
print(list_int_copy)
# for x in [1, 2, 3]:
# print(x, end=" ")
'''
|
4ba6229ceedd91e9b77aa6e9112ddecf2817040e | stuffyUdaya/Python | /1-9-17/shiftarrayvalues.py | 181 | 3.796875 | 4 | arr = [3,5,7,8]
for x in range(len(arr)-1,0):
arr[x] = arr[x+1]
print arr
# def shift(arr):
# arr.pop(0)
# arr.append(0)
# return arr
# print shift([1,2,3,4])
|
d911e033ddcfe181e169173a05c298c5e26f8584 | Reid-Norman/100-Days-of-Code | /Day 12/GuessTheNumberGame-v2.py | 1,559 | 4.125 | 4 | from random import randint
from art import logo
def set_difficulty():
'''A function which returns the number of attempts associated with the chosen difficulty'''
if input("Choose a difficulty. Type 'easy' or 'hard': \n").lower() == "hard":
return 5
else:
return 10
def answer_checker(guess, answer, turns):
'''A function to compare the user's guess against the answer and print the appropritate text.'''
if answer < guess:
print("Too high. \nGuess Again.")
return turns - 1
elif answer > guess:
print("Too low. \nGuess Again.")
return turns - 1
else:
print(f"You got it! The answer was {answer}.")
def game():
# Print intro text
print(logo)
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
# Choose number & difficulty
rand_num = randint(1, 100)
attempts_left = set_difficulty()
guessed_num = 0
# Loop through the game
while guessed_num != rand_num:
print(f"You have {attempts_left} attempts remaining to guess the number.")
guessed_num = int(input("Make a guess: "))
attempts_left = answer_checker(guessed_num, rand_num, attempts_left)
if attempts_left == 0:
print("You've run out of guesses, you lose.")
return
#The return ends the function(and therefore the while loop) and returns the print.
elif guessed_num != rand_num:
print("Guess again.")
game()
|
61810d5b99c3cfc456f9e24affd85ced270102c4 | MIsmailKhan/Project-Euler | /061.py | 1,948 | 3.65625 | 4 | import time
import math
from itertools import permutations
start = time.time()
# Fairly verbose solution
# Note: Create functions to create more elegant code
def triangle_numbers(index,start=1):
result = []
for n in xrange(start,index):
result.append((n*(n+1))/2)
return result
def square_numbers(index,start=1):
return [n**2 for n in range(start,index+1)]
def pentagonal_numbers(index,start=1):
result = []
for n in xrange(start,index):
result.append((n*(3*n - 1))/2)
return result
def hexagonal_numbers(index,start=1):
result = []
for n in xrange(start,index):
result.append(n*(2*n - 1))
return result
def heptagonal_numbers(index,start=1):
result = []
for n in xrange(start,index):
result.append((n*(5*n - 3))/2)
return result
def octagonal_numbers(index,start=1):
result = []
for n in xrange(start,index):
result.append(n*(3*n - 2))
return result
def main():
triangle = triangle_numbers(141,45)
square = square_numbers(99,32)
pentagonal = pentagonal_numbers(82,26)
hexagonal = hexagonal_numbers(71,23)
heptagonal = heptagonal_numbers(64,21)
octagonal = octagonal_numbers(59,19)
perms = list(permutations([triangle,square,pentagonal,hexagonal,heptagonal,octagonal]))
for perm in perms:
for entry_0 in perm[0]:
for entry_1 in perm[1]:
if str(entry_0)[-2:] == str(entry_1)[:2]:
for entry_2 in perm[2]:
if str(entry_1)[-2:] == str(entry_2)[:2]:
for entry_3 in perm[3]:
if str(entry_2)[-2:] == str(entry_3)[:2]:
for entry_4 in perm[4]:
if str(entry_3)[-2:] == str(entry_4)[:2]:
for entry_5 in perm[5]:
if str(entry_4)[-2:] == str(entry_5)[:2] and str(entry_5)[-2:] == str(entry_0)[:2]:
print(entry_0,entry_1,entry_2,entry_3,entry_4,entry_5)
return (entry_0 + entry_1 + entry_2 + entry_3 + entry_4 + entry_5)
elapsed = time.time() - start
print ("%s found in %s seconds" % (main(),elapsed)) #0.1s
|
511f4ccee9469fffde6e9b69f90c61205c6a53a6 | zalanh/learn-python | /ifstate5.py | 287 | 3.9375 | 4 | print("Want to hear a dirty joke?")
age = 12
if age == 12:
print("A pig fell in the mud !")
else:
print("Shh. It's a secret.")
print("Want to hear a dirty joke?")
age = 8
if age == 12:
print("A pig fell in the mud !")
else:
print("Shh. It's a secret.")
|
3941d5c36a798696d051d618b4eef108791a11c4 | wardaddy24/Python_Sorting-Searching | /binarysearch.py | 615 | 3.953125 | 4 | def bsearch(a,key):
start=0
end=len(a)-1
while(start<=end):
mid=int((start+end)/2)
if a[mid]==key:
return mid
elif a[mid]>key:
end=mid-1
elif a[mid]<key:
start=mid+1
a=[]
x=int(input("Enter the number of elements you wish to enter:"))
a=list(map(int,input().split()))[0:x]
a.sort()
print(a)
key=int(input("Enter the number you wish to search:"))
index=bsearch(a,key)
if index!=None:
print("Element Found at index:",index,",position:",index+1)
else:
print("Not found")
|
08cd8e545d34d33db2fc4501e7a1231bd3d29332 | MarcPartensky/Pygame-Geometry | /pygame_geometry/materialform.py | 11,679 | 3.53125 | 4 | from .materialpoint import MaterialPoint
from .abstract import Form,Point,Vector
from .material import Material
from .motion import Motion
from .force import Force
from . import materialpoint
from . import force
from . import colors
import math
import copy
class MaterialForm(Material,Form):
"""A material form is a form that is composed of material points and act
according to them only by linking them. However, it's not really useful in
practice because manipulating the material points directly is not an easy
task."""
def null():
"""Return the null material form."""
return MaterialForm([],[])
def random(corners=[-1,-1,1,1],n=5):
"""Create a random material form."""
form=Form.random(corners,n=n)
return MaterialForm.createFromForm(form)
def createFromForm(form):
"""Create a material form using a Form instance."""
return MaterialForm([MaterialPoint.createFromAbstract(point) for point in form.points])
def __init__(self,points,fill=False,point_mode=0,point_radius=0.01,point_width=2,side_width=1,point_color=colors.WHITE,side_color=colors.WHITE,area_color=colors.WHITE):
"""Create a material form."""
self.points=points
self.fill=fill
self.point_mode=point_mode
self.point_radius=point_radius
self.point_width=point_width
self.area_color=area_color
self.point_color=point_color
self.side_width=side_width
self.side_color=side_color
def __str__(self):
"""Return the string representation of the material form."""
return "mf("+",".join([str(p) for p in self.points])+")"
#Abstract
def getAbstract(self):
"""Return the object under a Form by conversion."""
return Form([p.getAbstract() for p in self.points])
def setAbstract(self,form):
"""Set the abstract representation of the material form to a form."""
self.__dict__=MaterialForm.createFromForm(form).__dict__
def delAbstract(self,form):
"""Set the abstract representation of the material form to null."""
self.__dict__=MaterialFrom.null().__dict__
def getCompleteForm(self,point_mode=None,point_radius=None,point_width=None,side_width=None,fill=None,area_color=None,point_color=None,side_color=None):
"""Return the object under a Form type by conversion."""
if not point_mode: point_mode=self.point_mode
if not point_radius: point_radius=self.point_radius
if not point_width: point_width=self.point_width
if not side_width: side_width=self.side_width
if not fill: fill=self.fill
if not area_color: area_color=self.area_color
if not point_color: point_color=self.point_color
if not side_color: side_color=self.side_color
points=[point.abstract for point in self.points]
return Form(points,fill=fill,
point_mode=point_mode,point_radius=point_radius,
point_width=point_width,side_width=side_width,
point_color=point_color,side_color=side_color,
area_color=area_color)
def getPosition(self):
"""Return the position of the center of the material form."""
return self.form.center.position
def getAbstractPoints(self):
"""Return all the abstract points of the object."""
return self.abstract.points
#Next
def getNext(self,dt):
"""Return the form after a duration dt."""
points=[p.getNext(dt) for p in self.points]
m=copy.deepcopy(self)
m.points=points
return m
#Motion
def getMotion(self):
"""Return the motion of the object."""
return Motion.average([point.motion for point in self.points])
def setMotion(self,nm):
"""Set the motion of the object."""
m=self.getMotion()
delta=nm-m
for point in self.points:
point.motion+=delta
def delMotion(self):
"""Set the motion to null."""
self.motion=Motion.null()
def show(self,context):
"""Show the form on the context."""
self.getCompleteForm().show(context)
def showNext(self,context,dt=1):
"""Show the next form on the context."""
self.getNext(dt).abstract.show(context)
def showMotion(self,context):
"""Show the motion on a context."""
self.motion.velocity.show(context,self.position)
self.motion.acceleration.show(context,self.position)
def showSteps(self,context):
"""Show the steps of the material form."""
for point in self.points:
point.showStep(context)
def showAll(self,context):
"""Show all the components of the points of the material form."""
self.getCompleteForm().show(context)
self.center.showAll(context)
for point in self.points:
point.showAll(context)
def update(self,t=1):
"""Update the form by updating all its points."""
for point in self.points:
point.update(t)
def rotate(self,angle=math.pi,center=Point.origin()):
"""Rotate the form by rotating its points."""
for point in self.points:
point.rotate(angle,center)
def getMass(self):
"""Calculate the mass of the form using its area and the mass of the material_points that define it."""
"""The way used to calculate it is arbitrary and should be improved."""
mass=sum([point.getMass() for point in self.points])
mass*=self.abstract.area
return mass
def __getitem__(self,index):
"""Return the material point of number 'index'."""
return self.points[index]
def __setitem__(self,index,point):
"""Return the material point of number 'index'."""
self.points[index]=point
def getCollisionInstant(self,other,dt=1):
"""Return the instant of the collision the material form with the other object."""
def getPointSteps(self,dt=1):
"""Return the segments that correspond to the steps the points of the
material form made during the time 'dt'."""
return [p.getStep(dt) for p in self.points]
def __or__(self,other):
"""Determine the points of intersections of the material point and another material object."""
if isinstance(other,MaterialForm): return self.crossMaterialForm(other)
def crossMaterialForm(self,other):
"""Return the material point of intersection between two material forms."""
f1=self.abstract
f2=other.abstract
points=f1.crossForm(f2)
return [MaterialPoint.createFromAbstract(point) for point in points]
def getTrajectory(self,dt=1):
"""Return the segments that are defined by the trajectory of each point."""
return [Segment(p.getPoint(dt),p.getNextPoint(dt)) for p in self.points]
#Center
def getCenter(self):
"""Return the material center of the form."""
return MaterialPoint.average(self.points)
def setCenter(self,nc):
"""Set the center of the material form."""
ac=self.getCenter()
v=Vector.createFromTwoPoints(nc,ac)
for point in self.points:
point+=v
def delCenter(self):
"""Set the center to the origin."""
self.setCenter(Point.origin())
#Position
def getPosition(self):
"""Return the position of the center of the material form."""
v=Vector.average([point.position for point in self.points])
v.color=colors.GREEN
return v
def setPosition(self,position):
"""Set the position of the material form to the given position."""
self.setCenter(position)
def delPosition(self):
"""Set the position of the material form to the origin."""
self.setCenter(Point.origin())
#Velocity
def getVelocity(self):
"""Return the velocity of the center of the material form."""
v=Vector.average([point.velocity for point in self.points])
v.color=colors.BLUE
return v
def setVelocity(self,velocity):
"""Set the velocity of the center of the material form."""
for point in self.points:
point.velocity=velocity
def delVelocity(self):
"""Set the velocity to the null vector."""
self.setVelocity(Vector.null())
#Acceleration
def getAcceleration(self):
"""Return the acceleration of the material form."""
v=Vector.average([point.acceleration for point in self.points])
v.color=colors.RED
return v
def setAcceleration(self,acceleration):
"""Set the acceleration of the material form to the given acceleration."""
for point in self.points:
point.acceleration=acceleration
def delAcceleration(self):
"""Set the acceleration to the null vector."""
self.setAcceleration(Vector.null())
#Steps
def getSteps(self):
"""Return the steps of each material point of the material form."""
return [point.step for point in self.points]
def setSteps(self,steps):
"""Set the steps of the material points."""
for i,point in enumerate(self.points):
point.step=steps[i]
def delSteps(self):
"""Set the steps of the material points to null."""
for (i,point) in enumerate(self.points):
point.step=Segment.null()
center=property(getCenter,setCenter,"Representation of the material center of the form.")
abstract=property(getAbstract,setAbstract,delAbstract,"Representation of the form in the abstract.")
motion=property(getMotion,setMotion,delMotion,"Representation of the motion of the form.")
position=property(getPosition,setPosition,delPosition,"Representation of the position of the form.")
velocity=property(getVelocity,setVelocity,delVelocity,"Representation of the velocity of the form.")
acceleration=property(getAcceleration,setAcceleration,delAcceleration,"Representation of the acceleration of the form.")
#abstract_center=property(getAbstractCenter,setAbstractCenter,delAbstractCenter,"Representation of the abstract center of the material form.")
#abstract_points=property(getAbstractPoints,setAbstractPoints,delAbstractPoints,"Representation of the abstract points of the material form.")
steps=property(getSteps,setSteps,delSteps,"Representation of the steps of the material form.")
FallingForm=lambda:MaterialForm([materialpoint.FallingPoint() for i in range(5)])
if __name__=="__main__":
from .context import Surface
surface=Surface()
c1=[-10,-10,10,10]
f1=Form.random(c1,n=5)
f1=MaterialForm.createFromForm(f1)
f1.velocity=Vector(0,1)
f1.acceleration=Vector(0,-0.01)
print(f1)
c2=[-10,-10,10,10]
f2=Form.random(c2,n=5)
f2=MaterialForm.createFromForm(f2)
#print(form[0].forces)
#print(form.getMass())
origin=Point.origin()
while surface.open:
surface.check()
surface.clear()
surface.control()
surface.show()
f1.update(t=1)
f2.update(t=1)
f1.rotate(0.01,f1.center.abstract)
f2.rotate(-0.01,f2.center.abstract)
for p in f1|f2:
p.show(surface)
surface.draw.window.print("f1: "+str(f1.motion),(10,10))
surface.draw.window.print("f2: "+str(f2.motion),(10,40))
f1.show(surface)
f2.show(surface)
f1.showNext(surface)
f2.showNext(surface)
f1.showMotion(surface)
f2.showMotion(surface)
f1.showSteps(surface)
f2.showSteps(surface)
surface.flip()
|
3503794997dce6518791e3cadd3633111a429f8f | Adewale888/Data_Structures | /Single_Number.py | 623 | 3.84375 | 4 | """
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
"""
class Solution:
def singleNumber(self, nums: List[int]) -> int:
d={}
for i in nums:
d[i]= d.get(i, 0)+ 1
for k,v in d.items():
if v== 1:
return k
print (k)
|
9a8f8553651c28b83478c5f5c543030b3a636202 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4127/codes/1800_2567.py | 154 | 3.828125 | 4 | from numpy import*
a= int(input("numero de asteriscos: "))
k=a
for i in range(a):
print("*"*a)
a= a-1
a = a +1
for i in range(k):
print("*"*a)
a=a+1
|
98c66ee0792bf54e60c292ddc70b33fe29106e9c | qmnguyenw/python_py4e | /geeksforgeeks/python/easy/25_13.py | 2,964 | 4.90625 | 5 | Python | Creating a 3D List
A 3-D List means that we need to make a list that has three parameters to it,
i.e., (a x b x c), just like a 3 D array in other languages. In this program
we will try to form a 3-D List with its content as “#”. Lets look at these
following examples:
Input :
3 x 3 x 3
Output :
[[['#', '#', '#'], ['#', '#', '#'], ['#', '#', '#']],
[['#', '#', '#'], ['#', '#', '#'], ['#', '#', '#']],
[['#', '#', '#'], ['#', '#', '#'], ['#', '#', '#']]]
Input :
5 x 3 x 2
Output :
[[['#', '#', '#', '#', '#'],
['#', '#', '#', '#', '#'],
['#', '#', '#', '#', '#']],
[['#', '#', '#', '#', '#'],
['#', '#', '#', '#', '#'],
['#', '#', '#', '#', '#']]]
## Recommended: Please try your approach on **__{IDE}__** first, before moving
on to the solution.
__
__
__
__
__
__
__
# Python program to print 3D list
# importing pretty printed
import pprint
def ThreeD(a, b, c):
lst = [[ ['#' for col in range(a)] for col in
range(b)] for row in range(c)]
return lst
# Driver Code
col1 = 5
col2 = 3
row = 2
# used the pretty printed function
pprint.pprint(ThreeD(col1, col2, row))
---
__
__
Output:
[[['#', '#', '#', '#', '#'],
['#', '#', '#', '#', '#'],
['#', '#', '#', '#', '#']],
[['#', '#', '#', '#', '#'],
['#', '#', '#', '#', '#'],
['#', '#', '#', '#', '#']]]
Refer pprint() to get more insight into this topic.
Now let’s suppose we need to merge two 3D lists into one.
__
__
__
__
__
__
__
# Python program to merge two 3D list into one
# importing pretty printed
import pprint
def ThreeD(a, b, c):
lst1 = [[ ['1' for col in range(a)] for col in
range(b)] for row in range(c)]
lst2= [[ ['2' for col in range(a)] for col in
range(b)] for row in range(c)]
# Merging using "+" operator
lst = lst1+lst2
return lst
# Driver Code
col1 = 3
col2 = 3
row = 3
# used the pretty printed function
pprint.pprint(ThreeD(col1, col2, row))
---
__
__
Output:
[[['1', '1', '1'], ['1', '1', '1'], ['1', '1', '1']],
[['1', '1', '1'], ['1', '1', '1'], ['1', '1', '1']],
[['1', '1', '1'], ['1', '1', '1'], ['1', '1', '1']],
[['2', '2', '2'], ['2', '2', '2'], ['2', '2', '2']],
[['2', '2', '2'], ['2', '2', '2'], ['2', '2', '2']],
[['2', '2', '2'], ['2', '2', '2'], ['2', '2', '2']]]
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
cc204660e3accc9099df3d38b9f3033e2267304d | Okiii-lh/to_offer_note | /python/链表中倒数第k个节点.py | 415 | 3.59375 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def findKthNode(pListHead, k):
if pListHead is None or k == 0:
return
tmpNode = pListHead
resultNode = pListHead
for i in range(k):
if tmpNode.next is not None:
tmpNode = tmpNode.next
else:
return
while tmpNode.next is not None:
tmpNode = tmpNode.next
resultNode = resultNode.next
return resultNode |
2a0c3b7cfb8ab58354e5a44dedb6b65f50d33c59 | bakker4444/Algorithms | /Python/leetcode_481_magical_string.py | 1,688 | 4.0625 | 4 | ## 481. Magical String
#
# A magical string S consists of only '1' and '2' and obeys the following rules:
#
# The string S is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string S itself.
#
# The first few elements of string S is the following: S = "1221121221221121122……"
#
# If we group the consecutive '1's and '2's in S, it will be:
#
# 1 22 11 2 1 22 1 22 11 2 11 22 ......
#
# and the occurrences of '1's or '2's in each group are:
#
# 1 2 2 1 1 2 1 2 2 1 2 2 ......
#
# You can see that the occurrence sequence above is the S itself.
#
# Given an integer N as input, return the number of '1's in the first N number in the magical string S.
#
# Note: N will not exceed 100,000.
#
# Example 1:
# Input: 6
# Output: 3
# Explanation: The first 6 elements of magical string S is "12211" and it contains three 1's, so return 3.
##
class Solution(object):
def magicalString(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 0:
return 0
if n <= 3:
return 1
head = 2
tail = 3
num = 1
result = 1
arr1 = [1, 2, 2]
while tail < n:
for i in range(arr1[head]):
arr1.append(num)
if num == 1 and tail < n:
result += 1
tail += 1
num = num ^ 3
head += 1
# print(arr1)
return result
if __name__ == "__main__":
print(Solution().magicalString(4))
print(Solution().magicalString(14))
print(Solution().magicalString(133))
print(Solution().magicalString(277))
|
229d6a639c3148a85ede91f884cc4004ce71e6a0 | Noboomta/ISP-SKE-KU-2020 | /labexam1-Noboomta/bank_account.py | 5,182 | 4.09375 | 4 | """
import
"""
from money import Money
from check import Check
class BankAccount:
"""
A BankAccount with a minimum required balance (default is 0)
that accepts deposit of Money or Checks. The balance is always the
total of deposits minus withdraws, but the value of a check is not
available for withdraw until `clear_check(check)` is called.
The available balance (`available` property) is the amount that can
be withdrawn so that a) no not-yet-clear checks are withdrawn, and
b) the balance after withdraw is at least the minimum balance.
>>> acct = BankAccount("Taksin Shinawat",1000)
# min required balance is 1,000
>>> acct.balance
0.0
>>> acct.available
0.0
>>> acct.min_balance
1000.0
>>> acct.deposit( Money(10000) ) # deposit 10,000 cash
>>> acct.balance
10000.0
>>> acct.available
9000.0
>>> c = Check(40000)
>>> acct.deposit(c) # deposit check for 40,000
>>> acct.balance
50000.0
>>> acct.withdraw(30000) # try to withdraw 30,000
Traceback (most recent call last):
...
ValueError: Amount exceeds available balance
>>> acct.clear_check(c)
>>> acct.available
49000.0
>>> acct.withdraw(30000) # try to withdraw 30,000
Money(30000)
>>> acct.balance
20000.0
>>> acct.withdraw(20000) # try to withdraw EVERYTHING
Traceback (most recent call last):
...
ValueError: Amount exceeds available balance
>>> acct.withdraw(15000)
Money(15000)
>>> acct.balance
5000.0
"""
def __init__(self, name: str, min_balance: float = 0.0):
"""Create a new account with given name.
Arguments:
name - the name for this account
min_balance - the minimum required balance, a non-negative number.
Default min balance is zero.
"""
# you don't need to test min_balance < 0. It's too trivial.
assert min_balance >= 0, "min balance parameter must not be negative"
self.__name = name
self.__balance = 0.0
self.__min_balance = float(min_balance)
# checks deposited and waiting to be cleared
self.__pending_checks = []
@property
def balance(self) -> float:
"""Balance in this account (float), as a read-only property"""
return self.__balance
@property
def available(self) -> float:
"""Available balance in this account (float),
as a read-only property"""
sum_holds = sum(check.value for check in self.__pending_checks)
avail = self.balance - self.min_balance - sum_holds
return avail if (avail > 0) else 0.0
@property
def min_balance(self) -> float:
"""Minimum required balance for this account, as read-only property"""
return self.__min_balance
@property
def account_name(self):
"""The account name. Read-only."""
return self.__name
def deposit(self, money: Money):
"""Deposit money or check into the account.
Arguments:
money - Money or Check object with a positive value.
Throws:
ValueError if value of money parameter is not positive.
"""
if money.value <= 0:
raise ValueError("Cannot deposit a negative amount")
# if it is a check, verify the check was not already deposited
if isinstance(money, Check):
# looks like a check
if money in self.__pending_checks:
raise ValueError("Check already deposited")
# add to list of checking waiting to clear
self.__pending_checks.append(money)
# both cash and checks contribute to the balance
self.__balance += money.value
def clear_check(self, check: Check):
"""Mark a check as cleared so it is available for withdraw.
Arguments:
check - reference to a previously deposited check.
Throws:
ValueError if the check isn't in
the list of checks waiting to clear
"""
if check in self.__pending_checks:
self.__pending_checks.remove(check)
def withdraw(self, amount: float) -> Money:
"""
Withdraw an amount from the account.
Arguments:
amount - (number) the amount to withdraw,
at most the available balance
Returns:
a Money object for the amount requested.
Throws:
ValueError if amount exceeds available balance or is not positive.
"""
if amount <= 0:
raise ValueError("Amount to withdraw must be positive")
if amount >= self.available:
raise ValueError("Amount exceeds available balance")
# try to create the money before deducting from balance,
# in case Money throws an exception.
money = Money(amount)
self.__balance -= amount
return money
def __str__(self):
"""String representation of the bank account.
Includes the acct name but not the balance.
"""
return f"{self.account_name} Account"
|
6b99f97439b7e623e0197378e7b7c056d295b1e0 | jmval111/Programming-Foundations-with-Python | /2 - Uses Classes - Draw Turtles/Making A Circle Out Of Squares/circles squares.py | 506 | 3.8125 | 4 |
import turtle
def draw_square(some_turtle) :
for i in range(0,4) :
some_turtle.forward(100)
some_turtle.right(90)
def draw_art() :
window = turtle.Screen()
window.bgcolor("red")
jp = turtle.Turtle()
jp.shape("turtle")
jp.color("yellow")
jp.speed(6)
for i in range(0,36) :
draw_square(jp)
jp.right(10)
"""
jp2 = turtle.Turtle()
jp2.shape("circle")
jp2.color("yellow")
jp2.speed(2)
jp2.circle(100)
"""
window.exitonclick()
draw_art()
|
e252e529272fd288fca0ea9eba48c2ffcc178e29 | AlexseyPivovarov/python_scripts | /Lesson13_1527107917/Lesson13/lesson12/yield_.py | 236 | 3.703125 | 4 | def f(a):
yield
while a:
yield a
a-=1
else:
return 999
a = f(5)
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
|
07c5c529e740af3fc6d0118d8e630d9750108634 | RotcivSnitram/Graphs | /grafico.py | 887 | 3.9375 | 4 | '''
Documentação:
Gera gráficos de funções escolhidas
Ao digitar o comando no terminal deve-se colocar:
python (ou python3) nomedoarquivo.py 'equação f(x)' valor_do_intervalo_inicial valor_do_intervalo_final
'''
# Biblioteca
import numpy as np
import math
import sys
import matplotlib.pyplot as plt
# Função
def f(x):
# Documentação:
"""
Digite em forma de string a sua função
Parâmetros: x
Retorno: y (float)
"""
y = eval(sys.argv[1])
return y
# Gráfico da função para diversos pontos
intervalo1 = float(sys.argv[2])
intervalo2 = float(sys.argv[3])
x_f = np.linspace(intervalo1, intervalo2)
f_x = f(x_f)
plt.plot(x_f, f_x, 'r-', label = 'f(x)')
plt.xlim(left = intervalo1, right = intervalo2)
plt.xlabel("x")
plt.ylabel("f(x)")
plt.title("Gráfico f(x)")
plt.legend()
plt.grid(True)
plt.show() |
35829561de09a77eb965e593e87afe8e3e03da64 | rusini/life10-benchmarks | /life.py | 1,170 | 3.546875 | 4 | # life.py -- Conway's Game of Life in Python (version 2)
from sys import stdout
n, m = 40, 80
g = 1000
def display(b):
for i in xrange(n):
for j in xrange(m):
stdout.write("*" if b[i][j] else " ")
print
def main():
b = [[0 for j in xrange(m)] for i in xrange(n)]
# initialization
b[19][41] = 1
b[20][40] = 1
b[21][40] = 1
b[22][40] = 1
b[22][41] = 1
b[22][42] = 1
b[22][43] = 1
b[19][44] = 1
# end of initialization
print "Before:"; display(b)
nextb = [[0 for j in xrange(m)] for i in xrange(n)]
nm1, mm1 = n - 1, m - 1
for k in xrange(g):
for i in xrange(n):
up = i - 1 if i != 0 else nm1; down = i + 1 if i != nm1 else 0
for j in xrange(m):
left = j - 1 if j != 0 else mm1; right = j + 1 if j != mm1 else 0
count = (
b[up ][left ] +
b[up ][j ] +
b[up ][right] +
b[i ][right] +
b[down][right] +
b[down][j ] +
b[down][left ] +
b[i ][left ] )
nextb[i][j] = b[i][j] if count == 2 else 1 if count == 3 else 0
b, nextb = nextb, b
print "After", g, "generations:"; display(b)
main()
|
f79ea66d25d259f45c8fbed68dda5523a7050d37 | souravs17031999/100dayscodingchallenge | /cs50/pset1.py | 789 | 3.796875 | 4 | def mario_block_right(n):
for i in range(0, n):
for j in range(0, n-i-1): # printing spaces
print(" ", end = "")
for k in range(0, i + 1): # printing stars
print("*", end = "")
print()
def mario_block_left(n):
for i in range(0, n):
for k in range(0, i + 1): # printing stars
print("*", end = "")
print()
def mario_tree(n):
for i in range(0, n):
for j in range(0, n-i-1): # printing spaces
print(" ", end = "")
for k in range(0, i + 1): # printing stars
print("*", end = "")
print(" ", end = "")
for k in range(0, i + 1): # printing stars
print("*", end = "")
print()
if __name__ == '__main__':
while(1):
height = int(input("Mario Tree Height: "))
if height <= 0:
print("wrong value of height !")
else:
mario_tree(height)
break
|
1a1d8681f4cf5425888f3e8c57051cdc1d25b22f | Naman5tomar/Hacktoberfest-2021 | /Dice Roll Simulator.py | 296 | 4.375 | 4 | #importing module for random number generation
import random
#range of the values of a dice
min_val = 1
max_val = 6
#to loop the rolling through user input
roll_again = "yes"
#loop
while roll_again == "yes" or roll_again == "y":
print("Rolling The Dices...")
print("The Values are :")
|
7a34a68ae0051a708c7e4d90b8b7f4a3d75cf662 | gabriellaec/desoft-analise-exercicios | /backup/user_107/ch22_2020_09_16_10_50_14_782276.py | 193 | 3.625 | 4 | count = int(input("Quantos cigarros você fuma por dia?"))
time = int(input("Há quantos anos você fuma?"))
days_per_cigarrette = 10 / 60 / 24
lost_time = count * days_per_cigarrette * time
|
7fc9b6836b1e0ae6838ddaf4fbdd6ed165afa9b5 | katieunger/hmc-homework | /lesson_1/pbj.py | 5,820 | 4.1875 | 4 | # Variables
bread = 8
peanutButter = 6
jelly = 0
sandwiches = bread/2
minIngredientQuantity = min(sandwiches, peanutButter, jelly)
# Goal 1
# Create a program that can tell you whether or not you can make a peanut butter and jelly sandwich
print "Goal 1"
print "Can I make any peanut butter and jelly sandwiches?"
# If I have more than one bread slice, at least one serving of peanut butter, and at least one serving of jelly, I can make a PB&J sandwich.
if bread > 1 and peanutButter >= 1 and jelly >= 1:
print "Yes, you can make at least one peanut butter and jelly sandwich.\n"
else:
print "No, you don't have sufficient ingredients to make any peanut butter and jelly sandwiches.\n"
# Goal 2
# Create a program to tell you: if you can make a sandwich, how many you can make
print "Goal 2"
print "How many peanut butter and jelly sandwiches can I make?"
# If I have more than one bread slice, at least one serving of peanut butter, and at least one serving of jelly, I can make as many PB&J sandwiches as the the number of servings of the ingredient I have the least of.
if bread > 1 and peanutButter >= 1 and jelly >= 1:
print "You can make {0} sandwich(es).\n".format(minIngredientQuantity)
else:
print "You don't have sufficient ingredients to make any peanut butter and jelly sandwiches.\n"
# Goal 3
# Create a program to allow you to make open-face sandwiches if you have an odd number of slices of bread
print "Goal 3"
print "How many peanut butter and jelly sandwiches can I make if I can also make an open-face sandwich?"
# If I have more than one bread slice, at least one serving of peanut butter, and at least one serving of jelly, I can make as many PB&J sandwiches as the the number of servings of the ingredient I have the least of.
if bread > 1 and peanutButter >= 1 and jelly >= 1:
print "You can make {0} sandwich(es) with two slices of bread.\n".format(minIngredientQuantity)
# If I have an odd amount of bread, I may be able to make an additional open-face sandwich - there is a leftover slice of bread.
if bread%2 != 0:
# Do I have enough leftover PB&J after the sandwiches with two bread slices are made to make an open face sandwich?
# minIngredientQuantity represents the number of sandwiches I can make with two slices of bread. Subtracting this from the number of servings of peanut butter and the number of servings of jelly will tell me whether there is leftover peanut butter or jelly. I need at least 1 additional serving of peanut butter and at least 1 additional serving of jelly.
if peanutButter - minIngredientQuantity >= 1 and jelly - minIngredientQuantity >= 1:
print "You can make an additional open-face sandwich.\n"
else:
print "You have leftover bread, but you've used up all your peanut butter and/or jelly. You cannot make an additional open-face sandwich.\n"
else:
print "You have an even number of bread slices, so you don't have any leftover bread to make open-face sandwiches.\n"
else:
print "You don't have sufficient ingredients to make any peanut butter and jelly sandwiches.\n"
# Goal 4
# Create a program to tell you: if you have enough bread and peanut butter but no jelly, that you can make a peanut butter sandwich
print "Goal 4"
print "How many peanut butter and jelly sandwiches can I make if I can also make peanut butter sandwiches if I run out of jelly?"
# If I have more than one bread slice, at least one serving of peanut butter, and at least one serving of jelly, I can make as many PB&J sandwiches as the the number of servings of the ingredient I have the least of.
if bread > 1 and peanutButter >= 1 and jelly >= 1:
print "You can make {0} peanut butter and jelly sandwich(es).\n".format(minIngredientQuantity)
# If I have leftover peanut butter and bread, I may be able to make additional peanut butter sandwiches.
# I need to figure out how much peanut butter and bread I have leftover after making the PB&J sandwiches.
extraPB = peanutButter - minIngredientQuantity
extraBread = (bread - minIngredientQuantity*2)
if extraPB >= 1 and extraBread > 1:
# Which do I have the least of, PB or bread?
print "You have {0} extra serving(s) of peanut butter.".format(extraPB)
print "You have {0} extra slices of bread.".format(extraBread)
minButterBread = min(extraPB, extraBread/2)
print "You can make {0} peanut butter sandwich(es).\n".format(minButterBread)
else:
print "You don't have enough leftover bread and peanut butter to make any additional peanut butter sandwiches.\n"
# If I have more than one bread slice, at least one serving of peanut butter, and no jelly, I can make as many peanut butter sandwiches as whichever ingredient, peanut butter or bread/2, I have the least of.
elif bread > 1 and peanutButter >= 1 and jelly == 0:
minButterBread = min(peanutButter,bread/2)
print "You have no jelly, but you can make {0} peanut butter sandwich(es).\n".format(minButterBread)
else:
print "You don't have sufficient ingredients to make any peanut butter and jelly sandwiches.\n"
# Goal 5
# Create a program to tell you: if you're missing ingredients, which ones you need to be able to make your sandwiches
print "Goal 5"
# If I have more than one bread slice, at least one serving of peanut butter, and at least one serving of jelly, I can make as many PB&J sandwiches as the the number of servings of the ingredient I have the least of.
if bread > 1 and peanutButter >= 1 and jelly >= 1:
print "You can make {0} peanut butter and jelly sandwich(es).".format(minIngredientQuantity)
# If I'm out of an ingredient:
elif minIngredientQuantity == 0:
print "You're missing an ingredient."
if jelly == 0:
print "You have no jelly!"
elif bread == 0:
print "You have no bread!"
else:
print "You have no peanut butter!"
else:
print "You don't have sufficient ingredients to make any sandwiches." |
1e782445919645b992cad93a03f6010f4fd8e025 | Kronossos/DLS_trees | /test_module/Tree.py | 3,981 | 3.796875 | 4 | # -*- coding: utf-8 -*-
import random
class Leaf:
def __init__(self, value):
self.value = value
self.color = "white"
def __iter__(self):
yield self
def __str__(self, level=0, blank=False, sign=" "):
if not blank:
blank = []
line = list(" " * level + sign + str(self.value))
for fill in blank:
try:
if line[fill] == " ":
line[fill] = "│"
except:
pass
return "".join(line)
def is_leaf(self):
return True
def label(self):
return self.value
def height(self):
return 1
def set_label(self, value):
self.value = value
class BinNode:
def __init__(self, left, right, value=None):
self.father = None
self.left = left
left.father = self
self.right = right
right.father = self
self.value = value
self.color = "white"
def __iter__(self):
for node in self.left:
yield node
for node in self.right:
yield node
yield self
def __str__(self, level=0, blank=False, sign=" "):
if not blank: blank = []
switch = False
line = list(" " * level + sign + "█>")
# if self.label():
# line += self.label()
for fill in blank[:]:
if switch or "".join(line[fill]) == "└":
switch = True
blank.pop(-1)
elif line[fill] == " ":
line[fill] = "│"
tree = "".join(line)
if self.label():
tree += str(self.label())
if not self.left.is_leaf(): blank.append(level + 2)
tree += "\n" + self.left.__str__(level + 2, blank, "├-")
tree += "\n" + self.right.__str__(level + 2, blank, "└-")
return tree
def is_leaf(self):
return False
def son(self, which):
if which == "L":
return self.left
elif which == "R":
return self.right
else:
print("Unknow son!")
def set_label(self, value):
self.value = value
def label(self):
return self.value
class BinTree:
def __init__(self, node):
if node.__class__.__name__ in ["BinNode", "Leaf"]:
self.node = node
self.label_dict = {}
else:
exit("Given root is not possible part of BinTree.")
def __str__(self):
if self.root: return self.node.__str__()
def __iter__(self):
return iter(self.node)
def root(self):
return self.node
def create_set_label(self):
for x in self:
if not x.is_leaf():
left_labels = set(x.son("L").label())
right_labels = set(x.son("R").label())
x.set_label(tuple(right_labels.union(left_labels)))
else:
new_label = (x.label(),)
x.value = new_label
def create_string_label(self, sign="N_"):
count = 0
for x in self:
if not x.is_leaf():
x.set_label(sign + str(count))
count += 1
def create_list_label(self):
for x in self:
if not x.is_leaf():
left_labels = x.son("L").label()
right_labels = x.son("R").label()
x.set_label(right_labels + left_labels)
else:
new_label = [x.label()]
x.value = new_label
def label_to_node(self, label_function=create_set_label):
label_dict = {}
for node in self:
label_dict[node.label()] = node
self.label_dict = label_dict
def label_dict(self):
return self.label_dict
def son_set(self):
son_set = []
for v in self:
if not v.is_leaf():
son_set.append((v.son("L"), v.son("R")))
return son_set |
775be2c124779c47bf7a5408b9e8f631b6a8d6a9 | chenlei65368/algorithm004-05 | /Week 1/id_040/LeetCode_283_040.py | 1,284 | 3.703125 | 4 | # 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
#
# 示例:
#
# 输入: [0,1,0,3,12]
# 输出: [1,3,12,0,0]
#
# 说明:
#
#
# 必须在原数组上操作,不能拷贝额外的数组。
# 尽量减少操作次数。
#
# Related Topics 数组 双指针
#
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def moveZeroes1(self, nums: list) -> None:
"""
Do not return anything, modify nums in-place instead.
1. 统计数组中0的个数
2. 通过python的list.remove删除0,再在结尾加上0
"""
zero_count = 0
for n in nums:
if n == 0:
zero_count += 1
for i in range(zero_count):
nums.remove(0)
nums.append(0)
# 第一遍 2019年10月14日
def moveZeroes2(self, nums: list) -> None:
j = 0
for i, n in enumerate(nums):
if n != 0:
nums[i], nums[j] = nums[j], nums[i]
j += 1
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
s = Solution()
nums = [0, 1, 0, 2, 3, 0, 4]
print(nums)
s.moveZeroes2(nums)
print(nums) |
bb49f6363d633439c4856806c202c8e65cc59ad2 | s-vedara/Python-Lessons | /Lesson-7-Loops.py | 309 | 4.21875 | 4 |
#Конечный цикл.
for x in range(0,100, 2): #3 цифра это шаг
# print("123")
print(x)
if x == 50: ##Если x раво 50 то прервать
break
#Безконечный цикл.
x=0
while True:
print(x)
x=x+1
if x == 100:
break
|
df55eff3c745496dca439685aa8f8b0869b3d7ae | ArnulfoPerez/python | /raspberry/oo/turtle_race.py | 623 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 28 13:06:59 2019
@author: arnulfo
"""
from turtle import Turtle
from random import randint
laura = Turtle()
rik = Turtle()
lauren = Turtle()
carrieanne = Turtle()
colors = ['red','purple','green','blue']
index = 0
turtles = [laura,rik,lauren,carrieanne]
startx, starty = -160, 100
for t in turtles:
t.color(colors[index])
t.shape('turtle')
t.penup()
t.goto(startx, starty)
t.pendown()
starty += 40
index += 1
for movement in range(100):
for t in turtles:
t.forward(randint(1,5))
input("Press Enter to close")
exit()
|
ee80948bf145312860867b875725ab50b6dd2948 | Ankush-Anku/Tranning | /38_simple_interest.py | 298 | 3.875 | 4 | #Assignment
"""
Accept p,n and r
si = pnr/100
print si
"""
def print_interest(n,p,r):
si = (p*n*r)/100
print(f"Simple interest is = {si}")
def main():
n = float(input("Enter n: "))
p = float(input("Enter p: "))
r = float(input("Enter r: "))
print_interest(n ,p,r)
main() |
ae6896cc66f403b87d46ea88f23f11284f5c9780 | nathan181/entrega2PBD | /exerc04.py | 1,546 | 4.34375 | 4 | """4. Faça um Programa que leia 2 números e em seguida pergunte ao usuário qual
operação ele deseja realizar. O resultado da operação deve ser acompanhado de
uma frase que diga se o número é:
par ou ímpar;
positivo ou negativo;
inteiro ou decimal.
"""
n1, n2 = float(input("Digite o primeiro número: ")), float(input("Digite o segundo número: "))
opcao = input("Qual operação deseja realizar?\n+ - Adição\n- - Subtração\n* - Multiplicação\n/ - Divisão\n")
OK = True
if opcao == "+":
result = n1+n2
elif opcao == "-":
result = n1-n2
elif opcao == "*":
result = n1*n2
elif opcao == "/":
if n2 == 0.0:
print('Erro! O divisor não pode ser 0.')
OK = False
else:
result = n1/n2
else:
print('Erro! Opção inválida!')
OK = False
if not OK:
pass
else:
r = str(result)
#Testando se o número é inteiro
if (r[-2]=='.' and r[-1]=='0'):
conjunto = 'inteiro'
else:
conjunto = 'decimal'
#Testando se o número é par (aplica-se apenas a números inteiros)
if conjunto == 'inteiro':
if result%2==0:
parimpar = 'par'
else:
parimpar = 'ímpar'
else:
parimpar = 'paridade só se aplica a números inteiros'
#Testando se o número é negativo
if result < 0.0:
sinal = 'negativo'
elif result == 0.0:
sinal = 'nulo'
else:
sinal = 'positivo'
print(f'Resultado é: {result}, {conjunto}, {sinal}, {parimpar}.')
print('Fim de programa.\n') |
c23ba21792ac483b47121e4a14a304004abe3576 | YusiZhang/leetcode-python | /BinaryTree/MaximumDepthBinaryTree.py | 1,194 | 3.546875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
"""java solution iterative
// iteration method
public int maxDepth(TreeNode root) {
int max = 0;
if (root == null) {return 0;}
Stack<TreeNode> path = new Stack<>();
Stack<Integer> sub = new Stack<>();
path.push(root);
sub.push(1);
while (!path.isEmpty()) {
TreeNode temp = path.pop();
int tempVal = sub.pop();
if (temp.left == null && temp.right == null) {max = Math.max(max, tempVal);}
else {
if (temp.left != null) {
path.push(temp.left);
sub.push(tempVal + 1);
}
if (temp.right != null) {
path.push(temp.right);
sub.push(tempVal + 1);
}
}
}
return max;
}
""" |
c12a39a6bfa880d13d3e62cab36721762d413dfb | grvn/aoc2020 | /02/day2-2.py | 357 | 3.59375 | 4 | #!/usr/bin/env python3
from sys import argv
def main():
valid=0
with open(argv[1]) as f:
for line in f:
a,b,passwd = line.strip().split()
min,max = a.split('-')
letter = b.strip(':')
if (passwd[int(min)-1] == letter) ^ (passwd[int(max)-1] == letter):
valid+=1
print('1:',valid)
if __name__ == '__main__':
main() |
a64f6cbf7e332f140073895f6c5a35cbe06caba1 | sernol9/Python4Beginners | /Python for Everybody/Exercises215.py | 299 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 11 17:29:40 2019
@author: olivia
"""
# name = input("Enter your name\n")
# print (name)
try:
hours = float(input ("Enter Hours:"))
rate = float(input("Enter Rate:"))
print ("Pay"+str(hours*rate))
except:
print("Enter float numbers\n") |
f7694836e3b09c8212fb19c0ef9a0b6812db61db | jamiejamiebobamie/pythonPlayground | /gold_mine.py | 2,162 | 4.15625 | 4 | # https://www.geeksforgeeks.org/gold-mine-problem/
# Given a gold mine of n*m dimensions.
# Each field in this mine contains a positive integer which is the amount of gold in tons.
# Initially the miner is at first column but can be at any row.
# He can move only (right->,right up /,right down\) that is from a given cell,
# the miner can move to the cell diagonally up towards the right or right or diagonally down towards the right.
# Find out maximum amount of gold he can collect.
#
# Examples:
#
# Input : mat[][] = {{1, 3, 3},
# {2, 1, 4},
# {0, 6, 4}};
# Output : 12
# {(1,0)->(2,1)->(2,2)}
#
# Input: mat[][] = { {1, 3, 1, 5},
# {2, 2, 4, 1},
# {5, 0, 2, 3},
# {0, 6, 1, 2}};
# Output : 16
# (2,0) -> (1,1) -> (1,2) -> (0,3) OR
# (2,0) -> (3,1) -> (2,2) -> (2,3)
#
# Input : mat[][] = {{10, 33, 13, 15},
# {22, 21, 04, 1},
# {5, 0, 2, 3},
# {0, 6, 14, 2}};
# Output : 83
# array = [[1, 3, 3],[2, 1, 4],[0, 6, 4]]
array = [[10, 33, 13, 15],
[22, 21, 4, 1],
[5, 0, 2, 3],
[0, 6, 14, 2]]
def getMoney(array):
choices = []
for column in range(len(array[0])): #the miner moves from the rightmost column (index 0) to the leftmost column (index len(array))
block = []
for row in range(len(array)):
block.append((array[row][column],row))
# if abs((block[len(block)-1])[1] - block[len(block)-2][1]) < 3:
choices.append(max(block))
print(choices)
if column > 1:
while (abs(choices[-1][1] - choices[-2][1])) > 3:
choices.pop()
block.pop(row*column)
choices.append(max(block))
return choices
getMoney(array)
# print(getMoney(array))
# Input : mat[][] = {{1, 3, 3},
# {2, 1, 4},
# {0, 6, 4}};
#WORK IN PROGRESS... FUNCTION GIVES MAX MONEY MOVES, BUT DOESN'T TAKE INTO ACCOUNT THE INDEX MOVEMENT RULES.
#PRONE TO ERROR THE LARGER THE ARRAY BECOMES.
|
c99501502c5ae7e95d117746d09a988f579c8a49 | kaushikdivya/realpython | /poetry.py | 1,784 | 3.703125 | 4 | def makePoem():
import random
nouns = ["fossil", "horse", "aardvark", "judge", "chef", "mango", "extrovert", "gorilla"]
verbs = ["kicks", "jingles", "bounces", "slurps", "meows", "explodes", "curdles"]
adj = ["furry", "balding", "incredulous", "fragrant", "exuberant", "glistening"]
prep = ["against", "after", "into", "beneath", "upon", "for", "in", "like", "over","within"]
adv = ["curiously", "extravagantly", "tantalizingly", "furiously", "sensuously"]
n=[]
v=[]
aj=[]
av=[]
pep=[]
while True:
n1 = random.choice(nouns)
if n1 not in n:
if len(n) < 3:
n.append(n1)
else:
break
while True:
v1 = random.choice(verbs)
if v1 not in v:
if len(v) < 3:
v.append(v1)
else:
break
while True:
aj1 = random.choice(adj)
if aj1 not in aj:
if len(aj) < 3:
aj.append(aj1)
else:
break
while True:
pep1 = random.choice(prep)
if pep1 not in pep:
if len(pep) < 2:
pep.append(pep1)
else:
break
while True:
av1 = random.choice(adv)
if av1 not in av:
if len(av) < 1:
av.append(av1)
else:
break
if aj[0][0] in ["a", "e", "i", "o", "u"]:
A_An = "An"
else:
A_An = "A"
poem = """ {} {} {}\n
{} {} {} {} {} the {} {}\n
{}, the {} {}\n
the {} {} {} a {} {}""".format(A_An,aj[0],n[0],A_An,aj[0],n[0],v[0],pep[0],aj[1],n[1],av[0],n[0],v[1],n[1],v[2],pep[1],aj[2],n[2])
return poem
print makePoem()
|
3f043cdb66ccab201a7610b50151ed0155dce946 | Aasthaengg/IBMdataset | /Python_codes/p03544/s750060000.py | 132 | 3.84375 | 4 | memo = {0:2, 1:1}
n = int(input())
for number in range(2,n+1):
memo[number] = memo[number-1] + memo[number-2]
print(memo[n]) |
5ab6e24f24e404637b835c3e92529b4398e3d7c9 | Callum-Diaper/COM404 | /1-basics/3-decision/8-nestception/bot.py | 851 | 4.28125 | 4 | user_inp = str(input("Where should I look? "))
if user_inp == "in the bedroom":
bedroom_inp = str(input("Where should I look in the bedroom? "))
if bedroom_inp == "under the bed":
print("Found some shoes but no battery")
else:
print("Found some mess but no battery.")
elif user_inp == "in the bathroom":
bath_inp = str(input("Where in the bathroom should I look? "))
if bath_inp == "in the bathtub":
print("Found a rubber duck but no battery")
else:
print("It is wet but I found no battery.")
elif user_inp == "in the lab":
lab_inp = str(input("Where in the lab should I look? "))
if lab_inp == "on the table":
print("Yes! I found my battery!")
else:
print("Found some tools but no battery.")
else:
print("I do not know where that is but I will keep looking.") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.