blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
68c773b526dc0b3601274352a1d15c327a49cfa0 | ahmetcanozturk/HackerRank-ProblemPortfolio | /Python/circular-array-rotation.py | 949 | 3.90625 | 4 | # solution to the HackerRank problem "Circular Array Rotation"
# https://www.hackerrank.com/challenges/circular-array-rotation/problem
# For each array, perform a number of right circular rotations and return the values of the elements at the given indices.
# Ahmetcan Ozturk
def circularArrayRotation(a, k, queries):
result = []
i = 0
while i < k:
elm = a.pop(len(a)-1)
a.insert(0, elm)
i = i + 1
for q in queries:
result.append(a[q])
return result
if __name__ == "__main__":
print("nkq: ")
nkq = input().split()
n = int(nkq[0])
k = int(nkq[1])
q = int(nkq[2])
print("array: ")
arr = list(map(int, input().rstrip().split()))
queries = []
for _ in range(q):
queries_item = int(input())
queries.append(queries_item)
result = circularArrayRotation(arr, k, queries)
print("output: ")
print('\n'.join(map(str, result)))
print('\n') |
c05b04d1763be126ae5c0ae3d1486a45b92ef017 | codewithsandy/Python-Basic-Exp | /15 TryCatch_Exception_Handling/first.py | 190 | 3.828125 | 4 | print("Enter Num 1 : ")
num1 = input()
print("Enter Num 2 : ")
num2 = input()
try:
print("Sum = ", int(num1)+int(num2))
except Exception as e:
print(e)
print("\tThis is important") |
e78c6a1c3d2378af649337f924fb5d31e593b14b | dmc87/ASCIIencryption | /ASCII Block Cipher.py | 19,223 | 3.71875 | 4 | # Darcy McIntyre, 10522336
# Created 27/03/2021
# Meet Alice next to the fridge in Building 18 at ECU.
# 1100111
def ascii_to_binary(plaintext): # This function converts text to binary via decimal
value = '' # and spits it out in 7 bit strings for easy reading
for character in plaintext:
binary = ("{0:07b}".format(ord(character)))
value = value + binary + ' '
value = value.rstrip()
return value
def ascii_x(plaintext): # This function converts text to binary via decimal
value = '' # and spits it out in one whole string
for character in plaintext:
binary = ("{0:07b}".format(ord(character)))
value = value + binary
return value
def bin_list(value): # Take the binary string and put it in a list to match the keystream list
return ([char for char in value])
def group7(value): # This function groups strings together by 7 to make ascii bits
n = 7
lst = [value[index : index + n] for index in range(0, len(value), n)]
return lst
def ciphertext(blist): # This function grabs the grouped binary in the list and turns them into an ascii string
ascii_cipher = []
for bn in blist:
ascii_cipher.append(chr(int(bn, 2)))
ascii_cipher = ''.join(map(str, ascii_cipher))
return ascii_cipher
def dec_cipher(blist): # This function grabs the grouped binary in the list and turns them into decimal
ascii_cipher = []
for bn in blist:
ascii_cipher.append(int(bn, 2))
ascii_cipher = ' '.join(map(str, ascii_cipher))
return ascii_cipher
def block(bits, length): # Make blocks to the length of the plaintext binary
n = len(length)
lst = [bits[index : index + n] for index in range(0, len(bits), n)]
return lst
def diffusion(block):
bit_list = []
permutation = []
bits = ''.join(block)
for bit in bits:
bit_list.append(bit)
permutation = (bit_list[1:] + bit_list[:1])
permutation = ''.join(permutation)
return permutation
def confusion(pt, ks): # This function turns the values of a list into ciphertext
bits = ''.join(pt)
bits = [bit for bit in bits]
ciphertext = []
counter = 0
for bit in ks: # Perform the binary xor below
ciphertext.append(str((int(bit) + (int(bits[counter])))%2))
counter = counter + 1
ciphertext = ''.join(ciphertext)
return ciphertext
def encrypt(block, keystream):
x = diffusion(block)
y = confusion(x, keystream)
return y
def transform_key(keystream):
bit_list = []
transformation = []
for bit in keystream:
bit_list.append(bit)
transformation = (bit_list[-1:] + bit_list[:-1])
return transformation
def reverse_transform_key(keystream):
bit_list = []
transformation = []
for bit in keystream:
bit_list.append(bit)
transformation = (bit_list[1:] + bit_list[:1])
return transformation
def reverse_diffusion(block):
bit_list = []
permutation = []
bits = ''.join(block)
for bit in bits:
bit_list.append(bit)
permutation = (bit_list[-1:] + bit_list[:-1])
permutation = ''.join(permutation)
return permutation
def reverse_confusion(pt, ks):
bits = ''.join(pt)
bits = [bit for bit in bits]
ciphertext = []
counter = 0
for bit in ks: # Perform the binary xor below
ciphertext.append(str((int(bit) - (int(bits[counter])))%2))
counter = counter + 1
ciphertext = ''.join(ciphertext)
return ciphertext
def decrypt(block, keystream):
y = reverse_confusion(block, keystream)
y = reverse_diffusion(x)
return y
while True:
key = []
cipher = []
b1=[]
b2=[]
b3=[]
b4=[]
b5=[]
b6=[]
b7=[]
# Print main menu
print('Welcome to the Basic Block Cipher Program (BBCP)')
print('Please select from the following options:')
print('To encrypt a message, press 1')
print('To decrypt a message, press 2')
print('To decrypt the message that you encrypted in option 1, press 3')
print('To exit, press any other character')
# Enter something
choice = (input('> '))
# Encryption chosen
if choice == '1':
print('Welcome to the encryption function.')
print('Please enter your ASCII value')
text = input('> ')
#text = 'Meet Alice next to the fridge in Building 18 at ECU.'
print('\nPlaintext: ', text)
print('\nBelow are your ASCII to binary values.\n')
print(ascii_to_binary(text), '\n')
print('Length of binary bits is:', len(ascii_x(text)), 'bits.\n')
# Time to generate a key, and then the keystream
print('Below, when you enter how long you would like your key to be,\nkeep in mind that the key will be duplicated to the length of the plaintext.\n')
keylength = (input('how long would you like to make the binary key?: '))
# Generate a list of bits for the key
for i in range(1, int(keylength)+1):
x = (input('Enter a binary value: '))
key.append(x)
# Put plaintext binary into 7 lists (blocks), make keystream
b = block(ascii_x(text), text)
bs = len(b[0])
kl = len(key)
keystream = key * int(bs/kl)
# This code legitimately works, it takes values from the front (1, 2, 3) and puts them at the back (4, 5, 6..n)
y = bs - len(keystream) # Get the difference
keysafe = keystream # Put the keystream in a safe
z = 0 # Set a counter
while y != 0: # While there's a difference, grab values from the start of the list to pad out
keysafe.append(keystream[z]) # Add numbers to the end of the list from the front of the list
z = z + 1
y = y - 1
keystream = keysafe
# Announce plaintext and keystream lengths
print('\nLength of keystream bits is:', len(keystream), 'bits')
print('Block size:', bs , 'bits\n')
# Set up blocks from block list
b1 += [b[0]]
b2 += [b[1]]
b3 += [b[2]]
b4 += [b[3]]
b5 += [b[4]]
b6 += [b[5]]
b7 += [b[6]]
print("The plaintext data undergoes diffusion, by converting the ASCII into 7-bit binary strings")
print("The plaintext binary is then divided into 7 blocks.")
print("The plaintext binary undergoes further diffusion by shifting bits within the block 1 space left.")
print("After the diffusion, each block undergoes the confusion state,\nwhere the keystream is XOR'ed to the block (key addition).")
print("After each block undergoes confusion, the keystream is transformed for the next round")
print("of key addition by shifting all the bits in the keystream to the right.")
print("This process is repeated 3 times, and the resultant blocks are added together to create the ciphertext.\n")
print("\nPrinting a sample of a round of block encryption")
print("\nPlaintext block 1: ")
print(''.join(b1))
print("\nDiffusion block 1: ")
print(diffusion(b1))
print("\nKeystream: ")
print(''.join(map(str, keystream)))
sample = (diffusion(b1))
print("\nCiphertext transformation block 1: ")
print(confusion(sample, keystream))
print("\n\nCommencing 3 rounds of encryption.\n")
# Round 1
b1 = encrypt(b1, keystream)
b2 = encrypt(b2, keystream)
b3 = encrypt(b3, keystream)
b4 = encrypt(b4, keystream)
b5 = encrypt(b5, keystream)
b6 = encrypt(b6, keystream)
b7 = encrypt(b7, keystream)
keystream = transform_key(keystream)
# Round 2
b1 = encrypt(b1, keystream)
b2 = encrypt(b2, keystream)
b3 = encrypt(b3, keystream)
b4 = encrypt(b4, keystream)
b5 = encrypt(b5, keystream)
b6 = encrypt(b6, keystream)
b7 = encrypt(b7, keystream)
keystream = transform_key(keystream)
# Round 3
b1 = encrypt(b1, keystream)
b2 = encrypt(b2, keystream)
b3 = encrypt(b3, keystream)
b4 = encrypt(b4, keystream)
b5 = encrypt(b5, keystream)
b6 = encrypt(b6, keystream)
b7 = encrypt(b7, keystream)
CipherText = b1+b2+b3+b4+b5+b6+b7
print(ciphertext(group7(CipherText)))
ctvar = ciphertext(group7(CipherText))
print('\nIf you want to decrypt this message directly,\nselect option 3 from the main menu\nas the ciphertext has been pre-loaded for you.\n')
print('-'*75,'\n')
print('\n')
elif choice == '2':
print('Welcome to the decryption function.')
print('Please enter your ciphertext value')
text = input('> ')
print('\nCiphertext: ')
print(text)
print('\nBelow are your ASCII to binary values.\n')
print(ascii_to_binary(text), '\n')
print('Length of binary bits is:', len(ascii_x(text)), 'bits.\n')
# Time to generate a key, and then the keystream
print('Below, when you enter how long you would like your key to be,\nkeep in mind that the key will be duplicated to the length of the ciphertext.\n')
keylength = (input('how long would you like to make the binary key?: '))
# Generate a list of bits for the key
for i in range(1, int(keylength)+1):
x = (input('Enter a binary value: '))
key.append(x)
# Put plaintext binary into 7 lists (blocks), make keystream
b = block(ascii_x(text), text)
bs = len(b[0])
kl = len(key)
keystream = key * int(bs/kl)
# This code legitimately works, it takes values from the front (1, 2, 3) and puts them at the back (4, 5, 6..n)
y = bs - len(keystream) # Get the difference
keysafe = keystream # Put the keystream in a safe
z = 0 # Set a counter
while y != 0: # While there's a difference, grab values from the start of the list to pad out
keysafe.append(keystream[z]) # Add numbers to the end of the list from the front of the list
z = z + 1
y = y - 1
keystream = keysafe
# Announce plaintext and keystream lengths
print('\nLength of keystream bits is:', len(keystream), 'bits')
print('Block size:', bs , 'bits\n')
# Set up blocks from block list
b1 += [b[0]]
b2 += [b[1]]
b3 += [b[2]]
b4 += [b[3]]
b5 += [b[4]]
b6 += [b[5]]
b7 += [b[6]]
print("The decryption process is the inverse of the encryption process.")
print("First, the original keystream must be transformed twice. Then the ciphertext undergoes reverse confusion:")
print('\nPlaintext bit (Xi) = ciphertext bit (Yi) - keystream bit (Si) mod(2)\n')
print("After the XOR is done, the cipher text needs to do reverse diffusion, by shifting bits right by 1.")
print("The keystream must then be reverse transformed, shifting bits left by 1.")
print("Then the reverse confusion is applied, reverse diffusion, and reverse key transformation 2 more times,")
print("Until the ciphertext is decrypted into plaintext.")
print('\n\nRunning 3 rounds of decryption')
# Prepare keystream for decryption
keystream = transform_key(keystream)
keystream = transform_key(keystream)
# 3 rounds of decryption per block (reverse confusion, reverse diffusion, reverse transform key)
b1 = (reverse_diffusion(reverse_confusion(b1, keystream)))
b2 = (reverse_diffusion(reverse_confusion(b2, keystream)))
b3 = (reverse_diffusion(reverse_confusion(b3, keystream)))
b4 = (reverse_diffusion(reverse_confusion(b4, keystream)))
b5 = (reverse_diffusion(reverse_confusion(b5, keystream)))
b6 = (reverse_diffusion(reverse_confusion(b6, keystream)))
b7 = (reverse_diffusion(reverse_confusion(b7, keystream)))
keystream = reverse_transform_key(keystream)
b1 = (reverse_diffusion(reverse_confusion(b1, keystream)))
b2 = (reverse_diffusion(reverse_confusion(b2, keystream)))
b3 = (reverse_diffusion(reverse_confusion(b3, keystream)))
b4 = (reverse_diffusion(reverse_confusion(b4, keystream)))
b5 = (reverse_diffusion(reverse_confusion(b5, keystream)))
b6 = (reverse_diffusion(reverse_confusion(b6, keystream)))
b7 = (reverse_diffusion(reverse_confusion(b7, keystream)))
keystream = reverse_transform_key(keystream)
b1 = (reverse_diffusion(reverse_confusion(b1, keystream)))
b2 = (reverse_diffusion(reverse_confusion(b2, keystream)))
b3 = (reverse_diffusion(reverse_confusion(b3, keystream)))
b4 = (reverse_diffusion(reverse_confusion(b4, keystream)))
b5 = (reverse_diffusion(reverse_confusion(b5, keystream)))
b6 = (reverse_diffusion(reverse_confusion(b6, keystream)))
b7 = (reverse_diffusion(reverse_confusion(b7, keystream)))
CipherText = b1+b2+b3+b4+b5+b6+b7
print('Your decrypted plaintext is:\n')
print(ciphertext(group7(CipherText)))
print('-'*75,'\n')
print('\n')
elif choice == '3':
print('Welcome to the decryption function.')
print('\nThis function will decrypt the message you just encrypted,\nassuming you have the right key.')
#print('Please enter your ciphertext value')
#text = input('> ')
#text = 'Meet Alice next to the fridge in Building 18 at ECU.'
text = ctvar
print('\nCiphertext: ')
print(text)
print('\nBelow are your ASCII to binary values.\n')
print(ascii_to_binary(text), '\n')
print('Length of binary bits is:', len(ascii_x(text)), 'bits.\n')
# Time to generate a key, and then the keystream
print('Below, when you enter how long you would like your key to be,\nkeep in mind that the key will be duplicated to the length of the ciphertext.\n')
keylength = (input('how long would you like to make the binary key?: '))
# Generate a list of bits for the key
for i in range(1, int(keylength)+1):
x = (input('Enter a binary value: '))
key.append(x)
# Put plaintext binary into 7 lists (blocks), make keystream
b = block(ascii_x(text), text)
bs = len(b[0])
kl = len(key)
keystream = key * int(bs/kl)
# This code legitimately works, it takes values from the front (1, 2, 3) and puts them at the back (4, 5, 6..n)
y = bs - len(keystream) # Get the difference
keysafe = keystream # Put the keystream in a safe
z = 0 # Set a counter
while y != 0: # While there's a difference, grab values from the start of the list to pad out
keysafe.append(keystream[z]) # Add numbers to the end of the list from the front of the list
z = z + 1
y = y - 1
keystream = keysafe
# Announce plaintext and keystream lengths
print('\nLength of keystream bits is:', len(keystream), 'bits')
print('Block size:', bs , 'bits\n')
# Set up blocks from block list
b1 += [b[0]]
b2 += [b[1]]
b3 += [b[2]]
b4 += [b[3]]
b5 += [b[4]]
b6 += [b[5]]
b7 += [b[6]]
print("The decryption process is the inverse of the encryption process.")
print("First, the original keystream must be transformed twice. Then the ciphertext undergoes reverse confusion:")
print('\nPlaintext bit (Xi) = ciphertext bit (Yi) - keystream bit (Si) mod(2)\n')
print("After the XOR is done, the cipher text needs to do reverse diffusion, by shifting bits right by 1.")
print("The keystream must then be reverse transformed, shifting bits left by 1.")
print("Then the reverse confusion is applied, reverse diffusion, and reverse key transformation 2 more times,")
print("Until the ciphertext is decrypted into plaintext.")
print("Example: previous encryption\n")
print(ctvar)
print('\n\nRunning 3 rounds of decryption')
# Prepare keystream for decryption
keystream = transform_key(keystream)
keystream = transform_key(keystream)
# 3 rounds of decryption per block (reverse confusion, reverse diffusion, reverse transform key)
b1 = (reverse_diffusion(reverse_confusion(b1, keystream)))
b2 = (reverse_diffusion(reverse_confusion(b2, keystream)))
b3 = (reverse_diffusion(reverse_confusion(b3, keystream)))
b4 = (reverse_diffusion(reverse_confusion(b4, keystream)))
b5 = (reverse_diffusion(reverse_confusion(b5, keystream)))
b6 = (reverse_diffusion(reverse_confusion(b6, keystream)))
b7 = (reverse_diffusion(reverse_confusion(b7, keystream)))
keystream = reverse_transform_key(keystream)
b1 = (reverse_diffusion(reverse_confusion(b1, keystream)))
b2 = (reverse_diffusion(reverse_confusion(b2, keystream)))
b3 = (reverse_diffusion(reverse_confusion(b3, keystream)))
b4 = (reverse_diffusion(reverse_confusion(b4, keystream)))
b5 = (reverse_diffusion(reverse_confusion(b5, keystream)))
b6 = (reverse_diffusion(reverse_confusion(b6, keystream)))
b7 = (reverse_diffusion(reverse_confusion(b7, keystream)))
keystream = reverse_transform_key(keystream)
b1 = (reverse_diffusion(reverse_confusion(b1, keystream)))
b2 = (reverse_diffusion(reverse_confusion(b2, keystream)))
b3 = (reverse_diffusion(reverse_confusion(b3, keystream)))
b4 = (reverse_diffusion(reverse_confusion(b4, keystream)))
b5 = (reverse_diffusion(reverse_confusion(b5, keystream)))
b6 = (reverse_diffusion(reverse_confusion(b6, keystream)))
b7 = (reverse_diffusion(reverse_confusion(b7, keystream)))
CipherText = b1+b2+b3+b4+b5+b6+b7
print('Your decrypted plaintext is:\n')
print(ciphertext(group7(CipherText)))
print('-'*75,'\n')
print('\n')
else:
break
|
4530924dc591135a544cd52bed96fff9031bc220 | verifier-studio/python-data-structures-algorithms | /algorithms/sort/shell_sort.py | 616 | 3.5 | 4 | '''
希尔排序
'''
'''
可以理解为通过步长优化的插入排序
'''
def shellSort(arr):
length = len(arr)
# 步长
gap = length // 2
while gap >= 1:
for k in range(0, gap):
for i in range(k+gap, length, gap):
for j in range(i, 0, -gap):
if arr[j] < arr[j-gap]:
arr[j], arr[j-gap] = arr[j-gap], arr[j]
else:
break
gap = gap // 2
if __name__ == '__main__':
test = [9, 8, 7, 6, 5, 4, 3, 1, 2, 10, 18, 100, 60, 50, 40]
shellSort(test)
print(test) |
a0b5b5829c963418c9df656111ff65fad0154150 | khp3040/Python-Demo-In-Spyder | /CaseStudy_With_Cart/check_quantity.py | 841 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 19 18:05:15 2021
@author: 0014CR744
"""
class Quantity():
def quantity():
try:
quant = int(input("Enter Quantity you wish to purchase : "))
return quant
except ValueError:
print("Please enter a number and not a string")
def verifyQuantity(quant,orderList):
try:
if quant <= 0:
raise ValueError()
elif quant <= int(orderList[0]["stockAvailable"]):
return True
elif quant > int(orderList[0]["stockAvailable"]):
print("Stock Unavailable")
else:
raise ValueError()
except ValueError:
print("Please Enter Positive Integer")
except TypeError:
pass |
cead83ed5601e75dc5fda3aa6468b6cd590ca783 | TianyaoHua/LeetCodeSolutions | /Letter Combinations of a Phone Number/Letter_Combinations_of_a_Phone-Number.py | 912 | 3.53125 | 4 | class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
digit2str_map = {'1': [1,"*"],'2': [3,"abc"],'3': [3,"def"],'4': [3,"ghi"],'5': [3,"jkl"],'6': [3,"mno"],'7': [4,"pqrs"],'8': [3,"tuv"],'9': [4,"wxyz"],'0': [1," "]}
answer = [""]
if digits == "":
return []
else:
for digit in digits:
[str_l, string] = digit2str_map.get(digit)
temp =[]
for i in range(str_l):
temp1 = answer[0:]
for j in range(len(answer)):
temp1[j] = temp1[j]+string[i]
temp += temp1[0:]
answer = temp[0:]
return answer
if __name__ == "__main__":
solution = Solution()
answer = solution.letterCombinations('1')
print(answer)
|
e8adc5007f04e288d6c13778fce184ebec2313df | YitingWang25436/Animal-Crossing-exploration | /What recipes can I make or are close to make?.py | 9,748 | 3.640625 | 4 | #!/usr/bin/env python
# coding: utf-8
# 
# 
# # **What is crafting & recipes in Animal Crossing: New Horizons?**
#
# Player is starting out on a deserted island, there are very few resources to be had at the beginning of the game - besides raw materials such as sticks and stones.Therefore, the concept of crafting is introduced to allow players to make anything from tools (like the axe and shovel) to clothing to furniture - an expansive new element to the game.
#
# The player gathers what are called "DIY recipes" - which can be acquired both from predictable sources such as Tom Nook, and randomised origins like bottles on the beach and floating balloon presents. Once in hand, players simply select the recipes in their inventories, "learn" them, and then choose them the next time they're at a workbench. Combined with the right materials, this allows everyone to craft to their heart's content.
# # Goal
# Problem to be solved: Given a set of items, what DIY recipes can you make or are close to make?
#
# In the game, it's easy to figure out which recipes I could make given my raw materials, as game has already marked for us. However, as a player, I often confused by which recipe was close to make. Hoping by designing a function I could solve my problem and find some interesting insights from data exploration process.
# # 1. Data preparation
# In[2]:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
recipes = pd.read_csv('C:/Users/ETTTT/Desktop/Animal Crossing/recipes.csv')
# ### 1.1 Data set structure
#
# First step, I want to have an overview about my dataset. The total missing values seems EXTREMELY high! More than 40% of data are missing! Definitely, we should dive deep into it.
# In[3]:
recipes.head(5)
# In[4]:
def stats(x) :
return pd.DataFrame({"Value":['%d '%x.shape[0],x.shape[1],sum(x.isnull().sum().values),
sum(x.isnull().sum().values)/(recipes.shape[0]*recipes.shape[1]),]},
index=['Number of observations','Number of variables','Total missing value','% of Total missing value'])
summary_table=pd.DataFrame(stats(recipes))
summary_table
# ### 1.2 Missing value
#
# I want to detect the count/percentage of missing values in every column of the dataset. This will give an idea about the distribution of missing values.
# In[5]:
# Create missing value table
total = recipes.isnull().sum().sort_values(ascending=False)
percent = (recipes.isnull().sum()/recipes.isnull().count()).sort_values(ascending=False)
missing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])
missing_data.head(13)
# Well.. Let's visualize it!
#
# Actually, based on my understanding of Animal crossing recipes,there is no need to worry about missing values at all.
#
# * For each recipe, the types of raw materials are varied. For example, the first one :acorn pochette which only need 6 acorns, so column material2 - material6 are empty.
# * Not every item/ recipe would be purchased by miles, it also explain why there are so many missing values in Miles Price.
# * Source Notes suggests that some recipes are seansonal limited. It's fair to be incomplete.
#
# My key takeaway here is to have a fully understanding of your product/object before dealing with data.
# In this case, if I haven't played this game yet, I'd probably delete several columns or the row containng miss value as usual.
#
#
# In[12]:
import missingno as msno
msno.bar(recipes)
# # 2. Data visualization & insights
#
#
# There are several interested fingings here!
#
# **Recipe Types:**
# * Housewares recipes are far more than any other types. Animal Crossing New Horizons features an extensive list of different furniture objects and other items that you can use to decorate your home and other parts of the island. However, in Animal Crossing World, players don't have rights to design their own furniture, all housewares are predesigned.Players have to gather recpes or exchange with friends to get more rare housewares to decorate their idland. BTW...The competition for the most incredible island was fierce, there are so many island tour videos on YouTube!
#
# * Amount of clothes,bags,shoes,bottom recipes are relative lower than others. The differents from housewares, players could deigin pattern for their outfit to make it unique. ACNH only provide basic type of clothes.The secret to getting the most creative, hilarious and downright bonkers Animal Crossing wallpapers, artworks and outfits in your game is in custom designs — and rather than have to sketch your own, you can scan those that helpful designers have already created straight into your game using QR codes, which made ACNH more social than any other games! Players also create their only community to share outfit ideas or island plannng examples.
#
#
# **Recipe could buy by Mile**
#
# Interesting! I played ACNH for months and never thought of there are only two types of recipe could purchase by mile point.
#
# **Source**
# * You could get 76 kinds of recipes by shooting down balloons with your slingshot! It's despair to know it untill now...
# * The most shocking is that character of villagers matters access to recipes!!! OMG!!Don't be picky when you pick your villagers or reject it due to it's snooty or smug. Don't be prejudiced. Great job Nintendo!
# * There are also several seasonal limited rescources,like Easter egg bottle/balloon.
# * Some recipes offered when you accomplish certan challenge,like shooting 300 ballons,fishing up all 3 trash items etc.
#
# Hope this plot will give you reference where could get recipes!
#
#
# In[7]:
plt.figure(figsize=(12, 8))
##Plot 1 Recipe Types
plt.subplot(221)
Category= pd.DataFrame({'values':recipes.groupby('Category').size().sort_values(ascending=False).values,
'index':recipes.groupby('Category').size().sort_values(ascending=False).index.to_list()})
order=recipes.groupby('Category').size().sort_values(ascending=False).index
sns.barplot(y='values',x='index',data=Category,order=order)
ax = plt.gca()
#Adjust xlabels for fitting the graph
ax.set_xticklabels(ax.get_xticklabels(), rotation=30, ha='right')
#Add label for each cols
for a,b in zip(Category.index,Category['values']):
plt.text(a, b+0.001, '%d' % b, ha='center', va= 'bottom',fontsize=9)
plt.title('Recipe Types')
plt.xlabel('Types')
##Plot 2 Recipe could buy by Mile
plt.subplot(222)
recipes_copy=recipes.copy()
recipes_copy.dropna(subset=['Miles Price'],how='any',inplace=True)
Category= pd.DataFrame({'values':recipes_copy.groupby('Category').size().sort_values(ascending=False).values,
'index':recipes_copy.groupby('Category').size().sort_values(ascending=False).index.to_list()})
order=recipes_copy.groupby('Category').size().sort_values(ascending=False).index
sns.barplot(y='values',x='index',data=Category,order=order)
ax = plt.gca()
#Add label for each cols
for a,b in zip(Category.index,Category['values']):
plt.text(a, b+0.001, '%d' % b, ha='center', va= 'bottom',fontsize=9)
#Add label for each cols
plt.xlabel('Types')
plt.title('Recipe could buy by Mile')
##Plot 3 Recipe Source
plt.subplot(212)
Source= pd.DataFrame({'values':recipes.groupby('Source').size().sort_values(ascending=False).values,
'index':recipes.groupby('Source').size().sort_values(ascending=False).index.to_list()})
order_Source=recipes.groupby('Source').size().sort_values(ascending=False).index
sns.barplot(y='values',x='index',data=Source,order=order_Source)
ax = plt.gca()
#Adjust xlabels for fitting the graph
ax.set_xticklabels(ax.get_xticklabels(), rotation=90, ha='right')
#Add label for each cols
for a,b in zip(Source.index,Source['values']):
plt.text(a, b+0.001, '%d' % b, ha='center', va= 'bottom',fontsize=9)
plt.title('Recipe Source')
plt.xlabel('Source')
plt.show()
# # 3. Build function
#
#
# By changing input of **what_in_my_bag** and call function **close_to_make()/ could_make()**, you'll get answer!
#
# Those functions are super easy, only contains several Loop functions. The key here is to convert reicpes into dictionary, then we could compare each number of material of what we have with what we expect.
# In[8]:
def close_to_make(what_in_my_bag):
close_to_make=[]
df=recipes.iloc[:,:13]
for i in range(len(df)):
for j in range(df.shape[1]):
if str(df.iloc[i,j]) in what_in_my_bag.keys() :
close_to_make.append(str(df.iloc[i,0]))
break
return pd.DataFrame({"What is close to make":close_to_make })
what_in_my_bag={'apple':5 }
close_to_make(what_in_my_bag)
# In[9]:
def could_make(what_in_my_bag):
could_make = []
df=recipes.iloc[:,:13]
for i in range(len(df)):
recipe = {}
for j in (2, 4, 6, 8, 10, 12):
if str(df.iloc[i,j]) != 'nan':
recipe[str(df.iloc[i,j])]=df.iloc[i,j-1]
count = len(recipe)
for k in recipe.keys():
if k in what_in_my_bag.keys():
if recipe[k] <= what_in_my_bag[k]:
count -= 1
else:
break
if count == 0:
could_make.append(str(df.iloc[i,0]))
return pd.DataFrame({"What could I make":could_make})
what_in_my_bag={'apple':10,'wood':4 }
could_make(what_in_my_bag)
# In[ ]:
# In[ ]:
|
cd590662244f835f87e335dc0311aaec81c3155d | tfox72/python-challenge | /PyPoll/main.py | 2,177 | 4.0625 | 4 |
# coding: utf-8
# ## Option 2: PyPoll
#
# 
#
# In this challenge, you are tasked with helping a small, rural town modernize its vote-counting process. (Up until now, Uncle Cleetus had been trustfully tallying them one-by-one, but unfortunately, his concentration isn't what it used to be.)
#
# You will be given two sets of poll data (`election_data_1.csv` and `election_data_2.csv`). Each dataset is composed of three columns: `Voter ID`, `County`, and `Candidate`. Your task is to create a Python script that analyzes the votes and calculates each of the following:
#
# * The total number of votes cast
#
# * A complete list of candidates who received votes
#
# * The percentage of votes each candidate won
#
# * The total number of votes each candidate won
#
# * The winner of the election based on popular vote.
#
# As an example, your analysis should look similar to the one below:
#
# ```
# Election Results
# -------------------------
# Total Votes: 620100
# -------------------------
# Rogers: 36.0% (223236)
# Gomez: 54.0% (334854)
# Brentwood: 4.0% (24804)
# Higgins: 6.0% (37206)
# -------------------------
# Winner: Gomez
# -------------------------
# In[1]:
import pandas as pd
# In[2]:
elect_df = pd.read_csv('election_data_2.csv')
# In[3]:
total_votes = elect_df["Voter ID"].count()
total_votes
# In[4]:
canidates = elect_df.groupby('Candidate').County.count()
canidates
# In[5]:
canidate2 = pd.DataFrame(canidates)
canidate2.reset_index(inplace=True)
canidate2.rename(columns={'County':'Votes'},inplace=True)
canidate2
# In[6]:
winner = canidate2.iloc[1, 0]
# In[7]:
winner2 = "Winner " + winner
# In[8]:
percent = (canidate2.iloc[:,1]/total_votes).apply('{:.0%}'.format)
percent2 = pd.DataFrame(percent)
percent2.rename(columns={'Votes':'Percentage'},inplace=True)
percent2
# In[9]:
table = pd.concat([canidate2,percent2], axis=1)
table
# In[10]:
print('Election Results')
print('----------------')
total_votes2 = 'Total Votes: ' + str(total_votes)
print(total_votes2)
print('----------------')
print(table)
print('----------------')
print(winner2)
# In[ ]:
# In[ ]:
|
6af3ea24e38c1638d4fc86ccd1bc76914f8e1591 | daniel-reich/turbo-robot | /662nTYb83Lg3oNN79_19.py | 922 | 3.953125 | 4 | """
Given a list of four points in the plane, determine if they are the vertices
of a parallelogram.
### Examples
is_parallelogram([(0, 0), (1, 0), (1, 1), (0, 1)]) ➞ True
is_parallelogram([(0, 0), (2, 0), (1, 1), (0, 1)]) ➞ False
is_parallelogram([(0, 0), (1, 1), (1, 4), (0, 3)]) ➞ True
is_parallelogram([(0, 0), (1, 2), (2, 1), (3, 3)]) ➞ True
is_parallelogram([(0, 0), (1, 0), (0, 1), (1, 1)]) ➞ True
### Notes
The points may be given in any order (compare examples #1 and #5).
"""
def is_parallelogram(lst):
a = ( lst[1][0] - lst[0][0], lst[1][1] - lst[0][1] )
b = ( lst[2][0] - lst[0][0], lst[2][1] - lst[0][1] )
c = ( lst[3][0] - lst[0][0], lst[3][1] - lst[0][1] )
A = a[0] == b[0] + c[0] and a[1] == b[1] + c[1]
B = b[0] == a[0] + c[0] and b[1] == a[1] + c[1]
C = c[0] == a[0] + b[0] and c[1] == a[1] + b[1]
return A or B or C
|
03a4dba0f142ed9f5573fbb33e6769beaa72898a | malipalema/python-journey | /16511111004Magret.p75.py | 299 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 6 14:32:06 2019
@author: Pale
"""
def exponential(n,x):
sum=1
for i in range(n,0,-1):
sum=1+x*sum/i
print("e(x) is about= ",sum)
n=int(input("Enter the nth term: "))
x=int(input("Enter a number: "))
exponential(n,x) |
f0d8fc01da1e9b86fbb365f4704ca6514870a14f | JonahMerrell/LinearAlgebraPackage | /VectorMethods/vector_1norm.py | 440 | 3.578125 | 4 | '''
coding language: Python 3.7.0
written by: Jonah Merrell
date written: October 29 2019
written for: Homework4 Task2
course: Math 4610
purpose: Calculate the 1-norm of a vector
'''
def vector_1norm(vector):
sum = 0.0
for i in range(len(vector)):
sum += abs(vector[i])
return sum
#The code below is used just for testing.
#vector = [5,7,9,2,5]
#print(vector_1norm(vector))
|
cb3381ee38f9e5135aa753e19b555e71166d968c | dataAlgorithms/algorithms | /recurBacktrack/hanoiTower.py | 3,852 | 4.03125 | 4 | '''
Solve tower of hanoi using recursive way
'''
def towerOfHanoiUsingRecur(n, from_rod, to_rod, aux_rod):
if n == 1:
print "Move disk 1 from rod", from_rod, "to rod", to_rod
return
towerOfHanoiUsingRecur(n-1, from_rod, aux_rod, to_rod)
print "Move disk", n, "from rod", from_rod, "to rod", to_rod
towerOfHanoiUsingRecur(n-1, aux_rod, to_rod, from_rod)
'''
[root@1 scripts]# python tower.py
2 disks
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
-------------------
3 disks
Move disk 1 from rod A to rod C
Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C
-------------------
4 disks
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
-------------------
'''
if __name__ == "__main__":
for n in [2, 3, 4]:
print '%d disks' % n
towerOfHanoiUsingRecur(n, 'A', 'C', 'B')
print '-------------------'
'''
Solve tower of hanoi using iterative way
'''
import sys
class Peg:
""" Stack representing one Hanoi peg. """
def __init__(self, n=0):
self.stack = []
self.stack.extend(range(1,n+1))
def count(self):
return len(self.stack)
def empty(self):
return self.count()==0
def top(self):
return self.stack[-1] if not self.empty() else 0
def pop(self):
return self.stack.pop() if not self.empty() else 0
def push(self, disc):
if disc < self.top():
raise Exception("Game rules violated")
self.stack.append(disc)
def __repr__(self):
return str(self.stack)
class Pegs():
""" Class representing three Hanoi pegs. """
def __init__(self, n, src=1, dst=3):
self.n = n
self.dst = dst
self.pegs = [None] #First non-peg to make indexing start from 1
for i in range(3):
self.pegs.append(Peg(n if i==src-1 else 0))
def simplemove(self, src, dst):
disc = self.pegs[src].pop()
print("from {} to {}.".format(src, dst))
self.pegs[dst].push(disc)
print(self)
def legalmove(self, first, second):
"""Performs the only legal move between two pegs."""
d1 = self.pegs[first].top()
d2 = self.pegs[second].top()
if d1 > d2:
self.simplemove(first, second)
else:
self.simplemove(second, first)
def finished(self):
return self.pegs[self.dst].count() == self.n
def __repr__(self):
return str(self.pegs[1:])
def hanoj(n, src=1, dst=3, tmp=2):
if n % 2 == 0: # Even disc flow
flow = ((src, tmp), (src, dst), (dst, tmp))
else: #Odd disc flow
flow = ((src, dst), (src, tmp), (dst, tmp))
p = Pegs(n, src)
step = 0
while not p.finished():
print("Step {:03}: ".format(step+1), end="")
p.legalmove(*flow[step % 3])
step += 1
if __name__ == "__main__":
hanoj(int(sys.argv[1]))
'''
[root@RND-SM-1-59Q tmp]# python iterHani.py 3
Step 001: from 1 to 3.
[[1, 2], [], [3]]
Step 002: from 1 to 2.
[[1], [2], [3]]
Step 003: from 3 to 2.
[[1], [2, 3], []]
Step 004: from 1 to 3.
[[], [2, 3], [1]]
Step 005: from 2 to 1.
[[3], [2], [1]]
Step 006: from 2 to 3.
[[3], [], [1, 2]]
Step 007: from 1 to 3.
[[], [], [1, 2, 3]]
'''
|
0d729431796f1e012cb745894ff64b701bc9b58b | Gaurav927/Dynamic-Programming | /buy_sell_stocks_1.py | 951 | 3.625 | 4 |
from functools import lru_cache
class Stock:
def maxProfit(self, share_price):
@lru_cache(maxsize=None)
def get_best_profit(day, have_stock):
if day<0:
return 0 if not have_stock else -float('inf')
price = share_price[day]
if have_stock:
strategy_sell = get_best_profit(day-1, False) - price
strategy_hold = get_best_profit(day-1, True)
return max(strategy_hold, strategy_sell)
else:
strategy_buy = get_best_profit(day-1, True) + price
strategy_avoid = get_best_profit(day-1, False)
return max(strategy_buy, strategy_avoid)
return get_best_profit(len(share_price)-1, False)
a = Stock()
print(a.maxProfit([3,2,6,5,0,3]))
|
26124c28b6f468c1b21f56e953867fed85f43981 | YONGJINJO/Python | /Algorithm/Dynamic Programming/fib_tab.py | 198 | 3.765625 | 4 | def fib_tab(n):
fib = [0, 1, 1]
for i in range(3, n + 1):
fib.append(fib[i - 1] + fib[i - 2])
return fib[n]
# 테스트
print(fib_tab(10))
print(fib_tab(56))
print(fib_tab(132)) |
2523914b51897da2d9212651792802377356a454 | vbarrera30/python-a-fondo | /Capitulo_4/clase_definiendo__len__.py | 660 | 3.921875 | 4 | class Planta:
def __init__(self, nombre, tipo, altura):
self.nombre = nombre
self.tipo = tipo
self.altura = altura
def __eq__(self, otra_planta):
return self.tipo == self.tipo
def __gt__(self, otra_planta):
return self.altura > otra_planta.altura
def __ge__(self, otra_planta):
return self.altura >= otra_planta.altura
if __name__ == '__main__':
camelia = Planta('Camelia', 'Arbusto', 2)
celindo = Planta('Celindo', 'Arbusto', 5)
pino = Planta('Pino', 'Árbol', 9)
print(camelia == celindo)
print(camelia == pino)
print(camelia > celindo)
print(camelia < pino)
|
cae4413049f1682975d5854b94530771d6e06fa4 | vijay2249/stress-relief | /copies.py | 4,105 | 3.828125 | 4 | import os
import sys
import hashlib
import send2trash
def usage():
print("[+] python file.py <folder1> <folder2> <folder3> delete -> to permanently delete the repeated files")
print("[+] python file.py <folder1> <folder2> <folder3> trash -> to send the repeated files to trash/recycle bin")
print("[+] python file.py <folder1> <folder2> <folder3> print -> to just print the repeated files")
print("[+] You can enter as many folders as you can")
sys.exit()
def printResults(files):
print('[+] The following files are identical. The name could differ, but the content is identical')
print('-------------------')
for f in files:
for i in f:
print('\t{}'.format(i))
print('-------------------')
def trashFiles(files):
for f in files:
for i in f[1:]:
print("[=] Trashing {} file".format(i))
send2trash.send2trash(i)
print("_________________")
print("[+] {} duplicates of this file are send to trash".format(f[0]))
print("[+] Successfully deleted all the duplicate files....YAY!!!!!!!!")
def deletePermanently(files):
warnAgain = str(input("[-] Are you sure to delete files permanently(yes/no): "))
while warnAgain.lower() not in ['yes', 'no', 'y', 'n']:
warnAgain = str(input("[-] Are you sure to delete files permanently(yes/no): "))
if warnAgain.lower() in ['yes', 'y']:
print("[-] Deleting duplicate files permanently......")
for f in files:
for i in f[1:]:
print("[=] Deleting {} file".format(i))
os.remove(i)
print("_________________")
print("[+] {} duplicates of this file are permanently removed successfully".format(f[0]))
else:
print("[=] Please check once again before you are sure to delete files [=]")
def hashfile(path, blocksize = 65536):
afile = open(path, 'rb')
hasher = hashlib.md5()
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
afile.close()
return hasher.hexdigest()
def findDuplicates(parentFolder):
# Dups in format {hash:[names]}
copies = {}
for dirName, subdirs, fileList in os.walk(parentFolder):
print("Scanning {}".format(dirName))
for filename in fileList:
path = os.path.join(dirName, filename) # Get the path to the file
file_hash = hashfile(path) # Calculate hash
# Add or append the file path
if file_hash in copies:
copies[file_hash].append(path)
else:
copies[file_hash] = [path]
return copies
def delete_Empty_Folders(Folders):
for i in Folders:
for dirname, folders, files in os.walk(i):
for folder in folders:
try:
path = os.path.join(dirname, folder)
os.rmdir(path)
print("[+] Deleted empty folder {}".format(path))
except Exception as error:
continue
# storing files in parent dictionary
def joinDicts(parentDict, childDict):
for key in childDict.keys():
parentDict[key] = childDict[key] if key not in parentDict else parentDict[key]+childDict[key]
if __name__ == '__main__':
if len(sys.argv) > 2 and sys.argv[-1].lower() in ['trash', 'delete', 'print']:
duplicate_files = {}
folders = sys.argv[1:-1]
for i in folders:
if os.path.exists(i):
joinDicts(duplicate_files, findDuplicates(i))
else:
print("[-] Folder path {} does not exists".format(i))
sys.exit()
duplicate_files = list(filter(lambda x : len(x) > 1, duplicate_files.values()))
if len(duplicate_files) < 0:
print("[+] No Duplicate files found....YAY!!!!!!!!!")
sys.exit()
else:
print("[+] Duplicates found...")
if sys.argv[-1].lower() == 'print':
printResults(duplicate_files)
elif sys.argv[-1].lower() == 'trash':
trashFiles(duplicate_files)
delete_Empty_Folders(sys.argv[1:-1])
elif sys.argv[-1].lower() == 'delete':
deletePermanently(duplicate_files)
delete_Empty_Folders(sys.argv[1:-1])
sys.exit()
else:
usage()
|
07d6116ad1fcc5a0abc6a4bc4c0923a08e2ca1d4 | syeeuns/week1-5_algorithm | /week1_algorithm/problem/하노이탑.py | 527 | 3.546875 | 4 | # 하노이탑 원반 개수 n개면 이동 횟수 2^n -1
def move(n, start, stop):
if n == 1:
print(f'{start} {stop}')
return
else:
move(n-1, start, 6-start-stop)
print(f'{start} {stop}')
move(n - 1, 6 - start - stop, stop)
def move_big(n, start, stop):
if n == 1:
return
else:
move_big(n-1, start, 6-start-stop)
move_big(n - 1, 6 - start - stop, stop)
n = int(input())
if n > 20:
print(2**n-1)
else:
print(2**n-1)
move(n, 1, 3)
|
0095b71fdeffcb27e7c71e626a286e28035d0f50 | caiosuzuki/exercicios-python | /ex035.py | 416 | 4.1875 | 4 | print('-=-'*8)
print('Analisador de Triângulos')
print('-=-'*8)
c1 = float(input('Digite o comprimento da primeira reta: '))
c2 = float(input('Digite o comprimento da segunda reta: '))
c3 = float(input('Digite o comprimento da terceira reta: '))
if c1 < c2 + c3 and c2 < c1 + c3 and c3 < c1 + c2:
print('Essas três retas formam um triângulo!')
else:
print('Essas três retas NÃO formam um triângulo!')
|
ffd35cfdf67267417a3dae2045200a72de61f52e | AndrewW-coder/Coding-class | /difficult/games/blackjack.py | 2,703 | 3.8125 | 4 | import random
your_decision = 0
###########################################
Ace = 1
King = 10
Queen = 10
Jack = 10
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 10]
card1 = random.randint(1, 10)
card2 = random.randint(1, 10)
card3 = random.randint(1, 10)
card4 = random.randint(1, 10)
your_value = card1 + card3
dealer_value = card2 + card4
print('You got 2 cards and your value is currently ' + str(your_value))
print('The dealer got 2 cards and one of them was a ' + str(card2))
for i in range(0, 5):
your_decision = input('Do you wish to hit or stand? ').lower()
if your_decision == 'hit':
n = random.randint(0, len(l)-1)
your_value += l[n]
while dealer_value <= 15:
d = random.randint(0, len(l)-1)
dealer_value += l[d]
print('The card you have recieved is ' + str(l[n]))
print('This now brings you up to a total of ' + str(your_value))
else:
while dealer_value <= 15:
d = random.randint(0, len(l)-1)
dealer_value += l[d]
your_value = your_value
print('Your final total is ' + str(your_value))
print('The dealers value is ' + str(dealer_value))
if your_value <= 21 and dealer_value <= 21:
if your_value > dealer_value:
print('Congratulations! You beat the dealer! Thanks for playing!')
break
elif your_value < dealer_value:
print('Sorry, looks like the dealer beat you. Try again next time!')
break
else:
print('Looks like you have a draw! How suprising!')
break
if your_value > 21 and dealer_value <= 21:
print('The dealer had ' + str(dealer_value))
print("Sorry, looks like you busted and the dealer didn't. You lost. Try again next time!")
break
elif your_value <= 21 and dealer_value > 21:
print('The dealer has ' + str(dealer_value))
print("The dealer busted! You win!")
break
elif your_value > 21 and dealer_value > 21:
print('Looks like you both busted. RIP!')
break
if your_value > 21 and dealer_value <= 21:
print('The dealers total is ' + str(dealer_value))
print("Sorry, looks like you busted and the dealer didn't. You lost. Try again next time!")
break
elif your_value <= 21 and dealer_value > 21:
print('The dealers total is ' + str(dealer_value))
print("The dealer busted! You win!")
break
elif your_value > 21 and dealer_value > 21:
print('The dealers total is ' + str(dealer_value))
print('Looks like you both busted. RIP!')
break |
df0d4e91567fd96b69d01a4f06eab6925478215b | 11lixy/Little-stupid-bird | /even_or_odd.py | 478 | 4.125 | 4 | number = input("Enter a numbr, and I'll tell you if it's even or odd: ")#input让程序暂停运行,等待用户输入一些文本
number = int(number)#函数int()将输入转换为数值
if number % 2 == 0:#运算符%将两个数相除,返回余数.一个数number和2执行求模运算,余数为0,就是偶数。
print("\nThe number " + str(number) + " is even.")#str函数转换为字符串输出
else:
print("\nThe number " + str(number) + " is odd.") |
1834461ee3b46ef0c8245a42061f1b33fdd67a4d | vik-jhun/word_ladder | /word_ladder.py | 2,999 | 4.1875 | 4 | #!/bin/python3
from collections import deque
import copy
def word_ladder(start_word, end_word, dictionary_file='words5.dict'):
'''
Returns a list satisfying the following properties:
1. the first element is `start_word`
2. the last element is `end_word`
3. elements at index i and i+1 are `_adjacent`
4. all elements are entries in the `dictionary_file` file
For example, running the command
```
word_ladder('stone','money')
```
may give the output
```
['stone', 'shone', 'phone', 'phony', 'peony', 'penny', 'benny', 'bonny', 'boney', 'money']
```
but the possible outputs are not unique,
so you may also get the output
```
['stone', 'shone', 'shote', 'shots', 'soots', 'hoots', 'hooty', 'hooey', 'honey', 'money']
```
(We cannot use doctests here because the outputs are not unique.)
Whenever it is impossible to generate a word ladder between the two words,
the function returns `None`.
'''
if start_word == end_word:
return [start_word]
word_stack = [] # Create a stack
word_stack.append(start_word) # Push the start word onto the stack
word_queue = deque() # Create a queue
word_queue.appendleft(word_stack) # Enqueue the stack onto the queue
words = open(dictionary_file).readlines()
wordList = []
for i in words:
wordList.append(i.strip("\n"))
while len(word_queue) != 0: # While the queue is not empty
temp = word_queue.pop() # Dequeue a stack from the queue AND save
for word in set(wordList): # For each word in the dictionary
if _adjacent(word, temp[-1]): # If the word is adjacent to the top of the stack
temp_copy = copy.deepcopy(temp)
temp_copy.append(word)
if word == end_word: # If this word is the end word
for j in range(1, len(temp_copy)-2):
if _adjacent(temp[j-1],temp[j+1]):
temp_copy.pop(j)
return (temp_copy)
word_queue.appendleft(temp_copy)
wordList.remove(word)
def verify_word_ladder(ladder):
'''
Returns True if each entry of the input list is adjacent to its neighbors;
otherwise returns False.
'''
if len(ladder) == 0:
return False
i = 0
while i < len(ladder)-1:
if _adjacent(ladder[i], ladder[i+1]) == True:
i += 1
else:
return False
return True
def _adjacent(word1, word2):
'''
Returns True if the input words differ by only a single character;
returns False otherwise.
>>> _adjacent('phone','phony')
True
>>> _adjacent('stone','money')
False
'''
count_diffs = 0
if len(word1) == len(word2):
for a, b in zip(word1, word2):
if a!= b:
count_diffs += 1
if count_diffs == 1:
return True
else:
return False
|
0733166d40bc1807d9c95c5f89228da93d15bb0d | HermanLin/CSUY1134 | /labs/lab8.py | 260 | 3.515625 | 4 | def is_balanced(inp_str):
lefty = "([{"
righty = ")]}"
tmp_stack = ArrayStack()
for i in inp_str:
if i is.in lefty:
tmp_stack.push()
else:
#is of same type as stack.top()
#if not, return false |
44063cf1001c74827325153186428f80db586ae4 | achisum94/projects | /portfolio/typing speed.py | 475 | 3.65625 | 4 | print('welcome to the first interview')
print('please enter your typing speed')
typing_speed=int(input())
if typing_speed>60:
print('congratulations')
print('you passed the first interview')
print('the company will contact you')
print('later regarding the second interview')
else:
print('sorry')
print('we are looking for candidates')
print('with a typing speed')
print('above 60')
print('thank you')
print('for applying to this job') |
8579b36f40a906a495a48495d7950183c4c6058f | aroseartist/Lessons-In-Python | /Ch5-Playground2.py | 2,262 | 4.3125 | 4 | # ################# NUMBER LOOP ################# #
# Write a program which repeatedly reads numbers until the user enters "done".
# Once "done" is entered, print out the total, count, and average of the numbers.
# If the user enters anything other than a number, detect their mistake using
# try and except and print an error message and skip to the next number.
# ################# NUMBER LOOP ################# #
total = 0
count = 0
while True:
given_number = input('Enter a number:\n')
if given_number.lower() == 'done':
break
try:
total += float(given_number)
count += 1
except ValueError:
print('Invalid input')
average = total/count
print('\nTotal:', total)
print('Count:', count)
print('Average:\n', average)
# ################# NUMBER LOOP - MUTATING LISTS ################# #
# Write a program which repeatedly reads numbers until the user enters "done".
# Once "done" is entered, print out the total, count, and average of the numbers.
# If the user enters anything other than a number, detect their mistake using
# try and except and print an error message and skip to the next number.
# ################# NUMBER LOOP - MUTATING LISTS ################# #
input_list = list()
while True:
input_numb = input('Enter a number: ')
if input_numb.lower() == 'done':
print('moving on...')
break
input_float = float(input_numb)
input_list.append(input_float)
average = sum(input_list) / len(input_list)
print('Average:', average)
# ################# MAX / MIN ################# #
# Write another program that prompts for a list of numbers as above and at the
# end prints out both the maximum and minimum of the numbers instead of the average.
# ################# MAX / MIN ################# #
min = None
max = None
while True:
given_number = input('\nEnter a number:\n')
if given_number.lower() == 'done':
break
try:
given_number_float = float(given_number)
if max is None or given_number_float > max:
max = given_number_float
if min is None or given_number_float < min:
min = given_number_float
except ValueError:
print('Invalid input')
print('\nMinimum:\n', min)
print('Maximum:\n', max)
|
c7dc669aee53df98168e24b2d7329ec3d3f85fd0 | immanuel-odisho/ASTM-Material-Load-Blast | /src/SeqServices.py | 1,525 | 3.9375 | 4 | ## @file SeqServices.py
# @title SeqServices
# @author Immanuel Odisho
# @date Feb/7/2018
## @brief will check if a sequence of numbers is ascending
# @param X is the sequence of numbers
# @return boolean
def isAscending(X):
for i in range(0,len(X)-1):
if (X[i+1] >= X[i]):
pass
else:
return False
return True
## @brief will see if a given value falls within a sequence
# @param X is the sequence
# @param x is the value
# @return will return a boolean
def isInBounds(X,x):
return (x <= X[-1] and x >= X[0])
## @brief will apply linear interpolation between 2 points and given value
# @param x1 x1 coordinate
# @param y1 y1 coordinate
# @param x2 x2 coordinate
# @param y2 y2 coordinate
# @param x is the value to interpolate about
# @return returns evaluation
def interpLin(x1,y1,x2,y2,x):
return ((y2-y1)/(x2-x1))*(x-x1) + y1
## @brief will apply quadratic interpolation between 3 points and given value
# @param x1 x1 coordinate
# @param y1 y1 coordinate
# @param x2 x2 coordinate
# @param y2 y2 coordinate
# @param x3 x3 coordinate
# @param y3 y3 coordinate
# @param x is the value to interpolate about
# @return returns evaluation
def interpQuad(x0,y0,x1,y1,x2,y2,x):
return y1 + ((y2-y0)/(x2-x0))*(x-x1)+((y2-2*y1+y0)/2*(x2-x1)**2)*(x-x1)**2
## @brief will return the index of a value in a sequence
# @param X is the sequence
# @param x is the value
# @return index
def index(X,x):
for i in range(0,len(X)):
if (x < X[i]):
return i - 1
elif (x == X[i]):
return i
|
7e9562dd4cf034ae114fee62ef76f735eb9fd4ec | Krishrawat/Rock-paper-scissors--lizard-spock | /JUST A MINI PROJECT1.py | 1,131 | 4 | 4 | #BY_KRISH_RAWAT
import random
def name_to_number(name):
if name=="Rock":
return 0
elif name=="Spock":
return 1
elif name=="Paper":
return 2
elif name=="Pizard":
return 3
elif name=="Scissors":
return 4
else:
print("invalid input")
def number_to_name(number):
if number==0:
return "Rock"
elif number==1:
return "Spock"
elif number==2:
return "Paper"
elif number==3:
return "Lizard"
elif number==4:
return "Scissors"
else:
print("invalid input")
def rpsls(player_choice):
print ("")
print ("Player chooses " + player_choice)
player_number=name_to_number(player_choice)
comp_number=random.randrange(0,5)
comp_choice=number_to_name(comp_number)
print ("Computer chooses " + comp_choice)
x=(comp_number-player_number)%5
if x==0:
print ("Player and computer tie!")
elif 0<x<=2:
print ("Computer wins!")
else:
print ("Player wins!")
x=rpsls(input().title())
|
7c90844dc5e7f271433e67d6f3c506226e659188 | S4RT-4K/VIRANK | /virank.py | 1,391 | 3.5 | 4 | import os
import time
import sys
time.sleep(1)
os.system('clear')
print("\033[1;32;40m ")
os.system("figlet VIRANK")
print(" Developer: S4RT-4K")
print(" VERSION: 1.0")
print(" ")
First_name = input("\033[1;32;40m Your First Name:- ")
if len(First_name) == 0:
print(" ")
print("Please Enter Your First Name")
print(" ")
sys.exit()
print(" ")
Last_name = input(" Your Last Name:- ")
if len(Last_name) == 0:
print(" ")
print("Please Enter Your Last Name")
print(" ")
sys.exit()
time.sleep(1)
print(" ")
print("Is This Name Correct?" + " " + First_name.upper() + " " + Last_name.upper())
print(" ")
time.sleep(1)
correct = input("If It Is Correct Then Type y Otherwise n: ")
time.sleep(1)
print(" ")
if correct == "y" or "Y":
print("OK! Let's Move On")
else:
print("Sad! Run It Again With Correct Information")
print(" ")
sys.exit()
time.sleep(2)
print(" ")
os.system("cd /sdcard && wget -nd -H -p -A jpg -e robots=off https://ibb.co/6WRVMZx")
os.system('clear')
for i in range(100):
time.sleep(0.1)
print("\033[1;33;40m Your System is Hacked, SpywareID#~SPY70D, Gaining Data...Sending to the Database")
os.system('clear')
for j in reversed(range(11)):
time.sleep(1)
print(f"\033[1;34;40m Gaining Data Succeeded, Turning Off Computer In {j} seconds.")
os.system('clear')
for l in range(11):
time.sleep(0.3)
print("\033[1;31;40m PRANKED SUCCESSFULLY HEHE :-)")
|
32192c22ffa96f39657dd551593f1366a4af401a | Tiger-tech893/Physics-with-Python | /Getting acceleration due to gravity.py | 1,148 | 3.546875 | 4 | import pyttsx3
import time
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
speak("This is program for finding acceleration due to gravity of any planet whose mass and radius is given")
speak("Follow the instructions")
while True:
speak('Hello what is the mass of the planet ?')
mass = input('What is the mass of the planet ?\n')
speak('now pardon me by typing radius of planet as this is mandatory')
radius = input('What is the radius of the planet ?\n')
Universal_gravatational_constant = 0.0000000000667
adg = float(Universal_gravatational_constant) * float(mass)
d = float(radius) * float(radius)
f = float(adg) / float(d)
print("The acceleration due to gravity on the planet whose mass is {} kg and radius is {} m is {} m/s^2".format((mass) ,(radius) ,(f)))
t = "The acceleration due to gravity on the planet whose mass is {} kilogram and radius is {} meter is {} meters per second squared".format((mass) ,(radius) ,(f))
speak(t)
time.sleep(5)
|
e0a74e90d8516839775df30b4143eea4ef51c89e | VBres/RobotObjectPerception | /color_detection/src/rgb2hsv.py | 2,112 | 3.640625 | 4 | import numpy as np
#Function that takes a RGB image and returns the corresponding HSV image
# INPUT : (nbPixels,3) data, the image to convert
# size, the size of the image
# OUTPUT : (nbPixels,3) imageHSV, the HSV image as an array
# see http://www.rapidtables.com/convert/color/rgb-to-hsv.htm for more explanations
def rgb2hsv(data, size):
nbRow, nbCol, nbCha = size
nbPix = nbRow * nbCol
#Computation of internal parameters
normalizedImage = data/255
cMax = np.max(normalizedImage,axis=1)
cMin = np.min(normalizedImage,axis=1)
delta = cMax - cMin
# Hue
H = np.zeros(nbPix)
rPrime = normalizedImage[:,0]
gPrime = normalizedImage[:,1]
bPrime = normalizedImage[:,2]
indices = (delta != 0) * (cMax == rPrime)
H[indices] = 60*((np.divide(gPrime[indices] - bPrime[indices], delta[indices]))%6)
indices = (delta != 0) * (cMax == gPrime)
H[indices] = 60*((np.divide(bPrime[indices] - rPrime[indices], delta[indices]))+2)
indices = (delta != 0) * (cMax == bPrime)
H[indices] = 60*((np.divide(rPrime[indices] - gPrime[indices], delta[indices]))+4)
# Saturation
S = np.zeros(nbPix)
S[(cMax != 0)] = np.divide(delta[(cMax != 0)], cMax[(cMax != 0)])
# Value
V = cMax
imageHSV = np.array([H,S,V]).transpose()
return imageHSV
#Function that takes a RGB pixel and returns the corresponding HSV pixel
# INPUT : (1,3) pixels, the pixel to convert
# OUTPUT : (1,3) hsvPixel, the HSV pixel
# see http://www.rapidtables.com/convert/color/rgb-to-hsv.htm for more explanations
def rgb2hsvPix(pixel):
#Computation of internal parameters
normalizedPixel = pixel/255
cMax = np.max(normalizedPixel)
cMin = np.min(normalizedPixel)
delta = cMax - cMin
# Hue
rPrime = normalizedPixel[0]
gPrime = normalizedPixel[1]
bPrime = normalizedPixel[2]
H = 0
if delta != 0:
if cMax == rPrime:
H = 60*(((gPrime - bPrime) / delta) % 6)
elif cMax == gPrime:
H = 60*(((bPrime - rPrime) / delta) + 2)
else:
H = 60*(((rPrime - gPrime) / delta) + 4)
# Saturation
S = 0
if cMax != 0:
S = delta/cMax
# Value
V = cMax
hsvPixel = [H, S, V]
return hsvPixel
|
dfff319d36e9a69226858dc08009530f245e6c1f | smchng/Image-Editing | /cmpt120YAIP.zip/main.py | 12,133 | 3.5 | 4 | # CMPT 120 Yet Another Image Processer
# Starter code for main.py
# Author: Samantha Chung
# Date: December 7 2020
# Description: Multiple piel manipulation functions that can be used to edit a photo
# - This file is where all the functions are called and the use interface is created and shown
import cmpt120imageProj
import cmpt120imageManip
import tkinter.filedialog
import pygame
pygame.init()
# list of system options
system = [
"Q: Quit",
"O:Open Image",
"S:Save Current Image",
"R:Reload Original Image"
]
# list of basic operation options
basic = [
"1:Invert",
"2:Flip Horizontal",
"3:Flip Vertical",
"4:Switch to Intermediate Functions",
"5:Switch to Advanced Functions"
]
# list of intermediate operation options
intermediate = [
"1:Remove Red Channel",
"2:Remove Green Channel",
"3:Remove Blue Channel",
"4:Convert to Grayscale",
"5:Apply Sepia Filter",
"6:Decrease Brightness",
"7:Increase Brightness",
"8: Switch to Basic Functions",
"9: Switch to Advanced Functions"
]
# list of advanced operation options
advanced = [
"1:Rotate Left",
"2:Rotate Right",
"3:Pixelate",
"4:Binarize",
"5: Switch to Basic Functions",
"6: Switch to Intermediate Functions"
]
# a helper function that generates a list of strings to be displayed in the interface
def generateMenu(state):
"""
Input: state - a dictionary containing the state values of the application
Returns: a list of strings, each element represets a line in the interface
"""
menuString = ["Welcome to CMPT 120 Image Processer!"]
menuString.append("") # an empty line
menuString.append("Choose the following options:")
menuString.append("") # an empty line
menuString += system
menuString.append("") # an empty line
# build the list differently depending on the mode attribute
if state["mode"] == "basic":
menuString.append("--Basic Mode--")
menuString += basic
menuString.append("")
menuString.append("Enter your choice(Q/O/S/R or 1-5)...")
elif state["mode"] == "intermediate":
menuString.append("--Intermediate Mode--")
menuString += intermediate
menuString.append("")
menuString.append("Enter your choice(Q/O/S/R or 1-9)...")
elif state["mode"] == "advanced":
menuString.append("--Advanced Mode--")
menuString += advanced
menuString.append("")
menuString.append("Enter your choice(Q/O/S/R or 1-6)...")
else:
menuString.append("Error: Unknown mode!")
return menuString
# a helper function that returns the result image as a result of the operation chosen by the user
# it also updates the state values when necessary (e.g, the mode attribute if the user switches mode)
def handleUserInput(state, img):
"""
Input: state - a dictionary containing the state values of the application
img - the 2d array of RGB values to be operated on
Returns: the 2d array of RGB vales of the result image of an operation chosen by the user
"""
userInput = state["lastUserInput"].upper()
# handle the system functionalities
if userInput.isalpha(): # check if the input is an alphabet
print("Log: Doing system functionalities " + userInput)
if userInput == "Q": # this case actually won't happen, it's here as an example
print("Log: Quitting...")
#My functions start here
if userInput == "O":
print ("Opening image...")
#Opens window so you can choose whiever image is needed
tkinter.Tk().withdraw()
openFilename = tkinter.filedialog.askopenfilename()
#Saves the image opened to a dictionary value that will be used later on
appStateValues["lastOpenFilename"] = openFilename
#Gets image and displays it in window with text instructions
img = cmpt120imageProj.getImage(openFilename)
cmpt120imageProj.showInterface(img,"Project Image",generateMenu(appStateValues))
if userInput == "S":
print ("Saving current image...")
#Opens window to save the edited image
tkinter.Tk().withdraw()
saveFilename = tkinter.filedialog.asksaveasfilename()
#After saved, the image is taken and showed again in output window
cmpt120imageProj.saveImage(img, saveFilename)
cmpt120imageProj.showInterface(img,"New Saved Image",generateMenu(appStateValues))
if userInput == "R":
print ("Loading original image...")
#Finds the last opened image that was stored in dictionary in the "OPEN" function and shows it
img = cmpt120imageProj.getImage(appStateValues["lastOpenFilename"])
cmpt120imageProj.showInterface(img, "Project Image", generateMenu(appStateValues))
# ***add the rest to handle other system functionalities***
# or handle the manipulation functionalities based on which mode the application is in
elif userInput.isdigit(): # has to be a digit for manipulation options
print("Log: Doing manipulation functionalities " + userInput)
#If the chosen mode is "basic," these are the available keys that can manipulate the image
#Each modes interface is stored in the dictionary and is shown when selected
if state['mode'] == "basic":
if userInput == "1":
print ("Image colours inverted")
"""
#Each function uses a variable to ressaign the function call to
#img is used since it is a global variable and was used when opening the image
#So after the new pixels are returned from the function, showInterface will use those pixels and shwo them in output
"""
img = cmpt120imageManip.invertImage(img)
cmpt120imageProj.showInterface(img,"Project Image Inverted",generateMenu(appStateValues))
elif userInput == "2":
print ("Image flipped horizontally")
img = cmpt120imageManip.flipHorizontal(img)
cmpt120imageProj.showInterface(img,"Project Image Flipped Horizontal",generateMenu(appStateValues))
elif userInput == "3":
print ("Image flipped vertically")
img = cmpt120imageManip.flipVertical(img)
cmpt120imageProj.showInterface(img,"Project Image Flipped Vertical",generateMenu(appStateValues))
elif userInput == "4":
print ("Changed to Intermediate functions")
state ["mode"] = "intermediate"
cmpt120imageProj.showInterface(img,"Intermediate Functions",generateMenu(appStateValues))
elif userInput == "5":
print ("Changed to Advanced mode")
state ["mode"] = "advanced"
cmpt120imageProj.showInterface(img,"Advanced Functions",generateMenu(appStateValues))
#These keys are allowed if the mode is changed to intermediate
elif state['mode'] == 'intermediate':
if userInput == "1":
cmpt120imageManip.redChannel(img)
cmpt120imageProj.showInterface(img,"Project Image Red Removed",generateMenu(appStateValues))
elif userInput == "2":
img = cmpt120imageManip.greenChannel(img)
cmpt120imageProj.showInterface(img,"Project Image Green Removed",generateMenu(appStateValues))
elif userInput == "3":
img = cmpt120imageManip.blueChannel(img)
cmpt120imageProj.showInterface(img,"Project Image Blue Removed",generateMenu(appStateValues))
elif userInput == "4":
img = cmpt120imageManip.grayscale(img)
cmpt120imageProj.showInterface(img,"Project Image Grayscaled",generateMenu(appStateValues))
elif userInput == "5":
img = cmpt120imageManip.sepia(img)
cmpt120imageProj.showInterface(img,"Project Image Sepia Filter Applied",generateMenu(appStateValues))
elif userInput == "6":
img = cmpt120imageManip.decreaseBrightness(img)
cmpt120imageProj.showInterface(img,"Project Image Decreased Brightness by 10",generateMenu(appStateValues))
elif userInput == "7":
img = cmpt120imageManip.increaseBrightness(img)
cmpt120imageProj.showInterface(img,"Project Image Increased Brightness by 10",generateMenu(appStateValues))
elif userInput == "8":
state ["mode"] = "basic"
cmpt120imageProj.showInterface(img,"Basic Functions",generateMenu(appStateValues))
elif userInput == "9":
state ["mode"] = "advanced"
cmpt120imageProj.showInterface(img,"Advanced Functions",generateMenu(appStateValues))
#These keys are allowed if the mode is changed to advanced
elif state['mode'] == 'advanced':
if userInput == "1":
img = cmpt120imageManip.leftRotate(img)
cmpt120imageProj.showInterface(img,"Project Image Rotated Left",generateMenu(appStateValues))
elif userInput == "2":
img = cmpt120imageManip.rightRotate(img)
cmpt120imageProj.showInterface(img,"Project Image Rotated Right",generateMenu(appStateValues))
elif userInput == "3":
img = cmpt120imageManip.pixelate(img)
cmpt120imageProj.showInterface(img,"Project Image Pixelated",generateMenu(appStateValues))
elif userInput == "4":
img = cmpt120imageManip.binarize(img)
cmpt120imageProj.showInterface(img,"Project Image Binarized",generateMenu(appStateValues))
elif userInput == "5":
state ["mode"] = "basic"
cmpt120imageProj.showInterface(img,"Basic Functions",generateMenu(appStateValues))
elif userInput == "6":
state ["mode"] = "intermediate"
cmpt120imageProj.showInterface(img,"Intermediate Functions",generateMenu(appStateValues))
# ***add the rest to handle other manipulation functionalities***
else: # unrecognized user input
print("Log: Unrecognized user input: " + userInput)
return img
# use a dictionary to remember several state values of the application
appStateValues = {
"mode": "basic",
"lastOpenFilename": "",
"lastSaveFilename": "",
"lastUserInput": ""
}
currentImg = cmpt120imageProj.createBlackImage(600, 400) # create a default 600 x 400 black image
cmpt120imageProj.showInterface(currentImg, "No Image", generateMenu(appStateValues)) # note how it is used
# ***this is the event-loop of the application. Keep the remainder of the code unmodified***
keepRunning = True
# a while-loop getting events from pygame
while keepRunning:
### use the pygame event handling system ###
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
appStateValues["lastUserInput"] = pygame.key.name(event.key)
# prepare to quit the loop if user inputs "q" or "Q"
if appStateValues["lastUserInput"].upper() == "Q":
keepRunning = False
# otherwise let the helper function handle the input
else:
currentImg = handleUserInput(appStateValues, currentImg)
elif event.type == pygame.QUIT: #another way to quit the program is to click the close botton
keepRunning = False
# shutdown everything from the pygame package
pygame.quit()
print("Log: Program Quit")
|
86eae8e6560ca36102342a16c0d6692d38130c90 | dshmatkou/S7_TestingLabs | /5/task_5.py | 3,503 | 3.890625 | 4 | from __future__ import unicode_literals, absolute_import
import collections
from random import randint
KEY_FILE = 'key.txt'
def is_prime(n):
"""Check if n is prime
:param n: number > 2
:type n: int
:rtype: bool
"""
if n == 2:
return True
if n < 2:
return False
k = 50
s = 0
t = n - 1
while t % 2 == 0:
t /= 2
s += 1
for _ in xrange(k):
a = randint(2, max(n - 2, 2))
x = pow(a, t, n)
if x == 1 or x == (n - 1):
continue
for _ in xrange(s - 1):
x = pow(x, 2, n)
if x == 1:
return False
if x == n - 1:
break
if x == n - 1:
continue
return False
return True
def read_key():
with open(KEY_FILE, 'r') as f:
key = int(f.readline(), base=16)
return key
def find_simple(number):
"""Find prime which greater than number.
:type number: int
:rtype: int
"""
number += 1
while not is_prime(number):
number += 1
return number
def find_gcd(a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
while a > 0 and b > 0:
if a > b:
a %= b
else:
b %= a
return a + b
def find_relatively_prime(prime, count):
"""Return count relatively primes which greater than prime.
:type prime: int
:type count: int
:rtype: list
"""
result = []
current = prime + 1
result.append(current)
lcm = current
while len(result) < count:
current += 1
if find_gcd(lcm, current) != 1:
continue
result.append(current)
lcm *= current
return result
def encode(n, m, key):
assert 3 < n < 20, 'Wrong participants count'
assert 2 < m < 19 and m < n, 'Wrong key participants count'
p = find_simple(key)
relatively_primes = find_relatively_prime(p, n)
high_border = 1
for i in xrange(m):
high_border *= relatively_primes[i]
low_border = 1
for i in xrange(m - 1):
low_border *= relatively_primes[n - i - 1]
r = (high_border - key - 1) / p
upgraded_secret = key + r * p
parts = [
(p, item, upgraded_secret % item)
for item in relatively_primes
]
return parts
### DECODE
def get_gcd(a, b):
if a == 0:
return b, 0, 1
d, x1, y1 = get_gcd(b % a, a)
x = y1 - (b / a) * x1
y = x1
return d, x, y
def get_upgraded_secret(r, m):
"""Return X according to chinese remainder theorem.
:param a: remainders
:type a: list
:param p: modules
:type p: list
:rtype: int
"""
assert len(r) == len(m)
mm = 1
for item in m:
mm *= item
x = 0
for i, mi in enumerate(m):
yi = mm / mi
gcd, reversed_y, _ = get_gcd(yi, mi)
si = reversed_y % mi
ci = (r[i] * si) % mi
x = (x + ci * yi) % mm
return x
def decode(parts):
upgraded_secret = get_upgraded_secret(
[item[2] for item in parts],
[item[1] for item in parts],
)
secret = upgraded_secret % parts[0][0]
with open('out.txt', 'w') as f:
f.write(hex(secret)[2:])
### MAIN
if __name__ == '__main__':
key = read_key()
n = 7
m = 6
parts = encode(n, m, key)
with open('parts.txt', 'w') as f:
for item in parts:
f.write(str(item) + '\n')
decode(parts[:m])
|
446658d96fb3ded704d0fc3c34be1be33c729381 | xiyangxitian1/heima_learn | /leetcode/二叉树/二叉树展开成链表.py | 1,362 | 3.96875 | 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 flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if root is None:
return None
def helper(root):
t1 = root.left
t2 = root.right
root.left = None
# 如果为叶节点,则直接返回此节点*
if t1 is None and t2 is None:
return root
# 如果有一个子节点为None,则根节点的右节点变为非空的节点,并返回此非空节点链表化后的尾节点
if t1 is None or t2 is None:
root.right = t2 if t1 is None else t1
return helper(root.right)
# 如果两个子节点都不为空
# 将根节点与左节点连起来
root.right = t1
# 对左节点链表化后,返回其尾节点
t1_tail = helper(t1)
# 将刚才的尾节点与右节点连接
t1_tail.right = t2
# 对右节点进行链表化
t2_tail = helper(t2)
# 返回链表化的尾节点
return t2_tail
helper(root)
return root
|
6d2243fab316c2c8c2dc4eaaef8e47e60ae4256e | Danielhsuuu/LearnPythonTheHardWay | /ex32.py | 1,141 | 4.59375 | 5 | #The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
#You can just go elements = range(0,6)
#there are many functions of list: add, contains, delitem, delslice, eq, ge, getattribute, getitem, getslice, gt, iadd, etc.
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print("This is count %d" % number)
# same as above
for fruit in fruits:
print("A fruit of type: %s" % fruit)
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print("I got %r" % i)
# we can also build slists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
#for i in range(0, 6):
# print("Adding %d to the list." % i)
# append is a function that lists understand elements.append(i)
elements = range(0,6)
# now we can print them out too
for i in elements:
print("Element was: %d" % i) |
ccf76bea71ec4666bc4dfce5edd1e29ae7381efa | myroom9/python-practice01 | /14.py | 1,113 | 3.796875 | 4 | # 문제14
# 숨겨진 카드의 수를 맞추는 게임입니다.
# 1-100까지의 임의의 수를 가진 카드를 한 장 숨기고 이 카드의 수를 맞추는 게임입니다.
# 아래의 화면과 같이 카드 속의 수가 57인 경우를 보면 수를 맞추는 사람이 40이라고 입력하면
# "더 높게", 다시 75이라고 입력하면 "더 낮게" 라는 식으로 범위를 좁혀가며 수를 맞추고 있습니다.
# 게임을 반복하기 위해 y/n이라고 묻고 n인 경우 종료됩니다.
import random
random_value = random.randint(1, 100)
user_select = 'y'
count = 1
print('수를 결정하였습니다. 맞추어 보세요\n 1 - 100')
while user_select == 'y' or user_select == 'Y':
print(random_value)
print(str(count) + '>>', end='')
user_value = input()
if random_value < int(user_value):
print('더 작게!')
elif random_value > int(user_value):
print('더 높게!')
else:
random_value = random.randint(1, 100)
print('맞았습니다.')
print('다시 하겠습니까(y/n)?')
user_select = input() |
af4f32cef965ce65049262fa46ae922039448c9c | geniousisme/CodingInterview | /leetCode/Python/208-implementTrie.py | 2,056 | 3.9375 | 4 | '''
TC: O(N) per action
SC: O(1)
'''
class TrieNode(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.is_string = False
self.leaves = {}
class Trie(object):
def __init__(self):
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
# one character store into leaves of root, one by one
# if there is no char in the leaves, create one TrieNode for it
curr = self.root
for char in word:
if not char in curr.leaves:
curr.leaves[char] = TrieNode()
curr = curr.leaves[char]
curr.is_string = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
# dfs for the children of the trie,
# if it can return node, which means we have the word in this trie,
# but still need to return is_string to check if it is the word
# ex. if "doggy" in the trie, then when we look for "dog", it will
# return node, but the node is_string is False.
# if it return None, then which means there is no such word.
node = self.childSearch(word)
if node:
return node.is_string
return False
def childSearch(self, word):
# look for the children node for word
curr = self.root
for char in word:
if char in curr.leaves:
curr = curr.leaves[char]
else:
return None
return curr
def startsWith(self, prefix):
"""
Returns if there is any word in the trie
that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
# since we only need to check the prefix,
# then it can just be judged by checking if it is node or not.
return self.childSearch(prefix) is not None
|
4230ef1b88d2bbabc2185e4edee27559bf7c59b8 | JosiahMc/python_stack | /python_fundamentals/muliplication.py | 581 | 3.96875 | 4 | for row in range(0, 13):
str_row = []
str_format = "{0:{width}} {1:{width}} {2:{width}} {3:{width}} {4:{width}} {5:{width}} {6:{width}} {7:{width}} {8:{width}} {9:{width}} {10:{width}} {11:{width}} {12:{width}}"
if row == 0:
str_row.append("x ")
pass
for col in range(0, 13):
if (row == 0 and col > 0):
str_row.append(str(col))
elif (row > 0 and col == 0):
str_row.append(str(row))
elif (row > 0 and col > 0):
str_row.append(str(row * col))
print str_format.format(*str_row, width=3)
|
f7aca5c34a50332d12895770269801296e32e3be | Pie-R-Square/ExpenseRecorder1 | /SQLite_Basic.py | 1,129 | 3.9375 | 4 | import sqlite3
# create data base
conn = sqlite3.connect('Expense.db')
# create operater
c = conn.cursor()
# create table
'''
'Details(details)'
'Rate(rate)'
'Quantity(quantity)'
'Discount(discount)'
'Total(amount)'
'Timestamp(now)'
'Transaction ID(transactionID)'
'''
c.execute("""CREATE TABLE IF NOT EXISTS ExpenseList(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
details TEXT,
rate REAL,
quantity REAL,
discount REAL,
amount REAL,
now TEXT,
transactionID TEXT
)""")
def insert_expense(details, rate, quantity, discount, amount, now, transactionID):
ID = None
with conn:
c.execute("""INSERT INTO expenseList VALUES (?,?,?,?,?,?,?,?)""",
(ID, details, rate, quantity, discount, amount, now, transactionID))
conn.commit() # record data to database
print("Insert succeed")
def show_expense():
with conn:
c.execute("SELECT * FROM expenseList")
expense = c.fetchall()
print(expense)
return expense
show_expense()
#insert_expense("f",52.0,15.0,4468.0,-3688.0,"Jun 12, 2021 20:35:53",202106122035757644)
print("Succeed") |
38816b78c89acf4942e65d0715349edf907ad1d7 | vedika000lodha/c97_project | /c97.py | 515 | 4.21875 | 4 | import random
print("number guessing game")
number = random.randint(1, 9)
chances = 0
while chances < 5:
guess = int (input("guess a number between 1 - 9 : "))
if guess == number:
print("Congrats u won!!")
break
elif guess < number:
print("ur guess was too low : guess a number higher than ", guess)
else:
print("ur guess was too high : guess a number lower than ", guess)
chances = chances + 1
if chances == 5:
print("u loose, the number is ", number) |
9508415755919213c4735e9bdf00048cb7aad99f | sebaspasker/Competitive | /CodeWars/5 kyu/first_non_rep_char.py | 212 | 3.609375 | 4 | def first_non_repeating_letter(string):
string_lower = string.lower()
for i in range(0, len(string_lower)):
if string_lower.count(string_lower[i]) == 1:
return string[i]
return ''
|
02893020480221fc1df16c5af2f71c2b16d6bfeb | INNOMIGHT/hackerrank-solutions | /LinkedLists/deleting_a_node.py | 580 | 3.71875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def delete_node(self, position):
pointer = self.head
for i in range(position - 1):
pointer = pointer.next
temp_next = pointer.next.next
pointer.next = None
pointer.next = temp_next
def print_list(self, head):
print_val = self.head
while print_val is not None:
print(print_val.data)
print_val = print_val.next
|
ff8761800538e485b2e06c1c5267d2a8a2d50110 | Dasem/psu | /cripta/utils/eiler.py | 1,076 | 3.734375 | 4 | #!/usr/bin/env python3
# coding: utf8
import sys
n = int(sys.argv[1])
def step(deg, osn, mod):
acc = 1
summ=osn
while deg != 0:
if deg % 2 != 0:
acc=(summ*acc)%mod
summ=(summ*summ)%mod
deg//=2
return acc
def ferma_test(a, p):
return step(p-1, a, p) == 1
def eiler(n, tested):
simple = []
current_digit = 1
while len(simple) != n:
if ferma_test(tested[0], current_digit):
simple.append(current_digit)
current_digit+=1
new_simple = []
for test in tested:
new_simple = []
for digit in simple:
if ferma_test(test, digit):
new_simple.append(digit)
return new_simple
def Isprime(n):
i = 2
j = 0
while(True):
if(i*i <= n and j != 1):
if(n % i == 0):
j=j+1
i=i+1
elif(j==1):
return False
else:
return True
ans = eiler(n,[2,3,5])
for i in ans:
if not Isprime(i):
print('ALARM!!!!', i)
print(ans, len(ans))
|
20f9d3923f548cc1937c59f6e6934105f41648ee | sabb1r/ProjectEuler | /problem7.py | 565 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 6 15:04:26 2018
@author: sabbir
"""
from math import sqrt
def is_prime(num):
if num < 2:
return False
elif num == 2:
return True
elif num % 2 == 0:
return False
for i in range(3, int(sqrt(num))+1, 2):
if num % i == 0:
return False
else:
return True
start = 1 # 2 is already counted
i = 3
while start != 10001:
if is_prime(i):
start += 1
i = i + 2
print('The answer is = ', i-2) |
fa390ef1c1fcf9183ce45b89871dcceff44374e8 | ashjambhulkar/objectoriented | /LeetCodePremium/101.symmetric-tree.py | 735 | 3.953125 | 4 | #
# @lc app=leetcode id=101 lang=python3
#
# [101] Symmetric Tree
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
def helper(left, right):
if not left and not right:
return True
if not left or not right:
return False
return helper(left.left, right.right) and helper(left.right, right.left) and left.val == right.val
return helper(root.left, root.right)
# @lc code=end
|
df3882dbb144e1ae14bc2dc6213929a59555ceb2 | JaoLucass/atividades-de-poo | /conta.py | 1,343 | 3.703125 | 4 | class Conta:
def __init__(self, numero, titular, saldo, limite, data_abertura):
self.numero = numero
self.titular = titular
self.saldo = saldo
self.limite = limite
self.data_abertura = data_abertura
def deposita(self, valor):
self.saldo += valor
#def saca(self, valor):
# self.saldo -= valor
def saca(self, valor):
if(self.saldo < valor):
return False
else:
self.saldo -= valor
return True
def transfere_para(self, destino, valor):
retirou = self.saca(valor)
if(retirou == false):
return False
else:
destino.deposita(valor)
return True
def extrato(self):
print("numero: {} \nsaldo: {}\nnome: {} \nsobrenome: {} \nCPF: {} \n".format(self.numero, self.saldo, self.titular.nome, self.titular.sobrenome, self.titular.cpf))
print("data de abertura: {}/{}/{} \n".format(self.dia, self.mes, self.ano))
class Cliente:
def __init__(self, nome, sobrenome, cpf):
self.nome = nome
self.sobrenome = sobrenome
self.cpf = cpf
#
class Data:
def __init__(self, dia, mes, ano):
self.dia = dia
self.mes = mes
self.ano = ano
|
13e7a0419643d87c883a97918f7dac7d8c38fa1c | logic27/Codes | /DSA codes/DSL_assignment_3.py | 3,501 | 4.03125 | 4 | class Matrix:
def __init__(self):
self.matrix = []
self.row = 0
self.col = 0
def get_mat(self):
self.row = int(input("Enter no of rows in matrix :"))
self.col = int(input("Enter no of columns in matrix :"))
self.matrix = [[int(input("enter element")) for i in range(self.col)] for j in range(self.row)]
def set_mat(self, row, col):
self.row = row
self.col = col
def show(self):
for i in range(self.row):
print("[ ", end=" ")
for j in range(self.col):
print( self.matrix[i][j], end=" ")
print("]")
def add_mat(self, mat):
add = Matrix()
add.set_mat(self.row, self.col)
add.matrix = [[0 for i in range(self.col)] for j in range(self.row)]
for i in range(self.row):
for j in range(self.col):
add.matrix[i][j] = self.matrix[i][j] + mat.matrix[i][j]
add.show()
def sub_mat(self, mat):
sub = Matrix()
sub.set_mat(self.row, self.col)
sub.matrix = [[0 for i in range(self.col)] for j in range(self.row)]
for i in range(self.row):
for j in range(self.col):
sub.matrix[i][j] = self.matrix[i][j] - mat.matrix[i][j]
sub.show()
def mul_mat(self, mat):
mul = Matrix()
mul.set_mat(self.row, mat.col)
mul.matrix = [[0 for i in range(mat.col)] for j in range(self.row)]
for i in range(self.row):
for j in range(mat.col):
for k in range(self.col):
mul.matrix[i][j] = mul.matrix[i][j] + self.matrix[i][k] * mat.matrix[k][j]
mul.show()
def transpose_mat(self):
trans = Matrix()
trans.matrix = [[0 for i in range(self.row)] for j in range(self.col)]
trans.set_mat(self.col, self.row)
for i in range(self.col):
for j in range(self.row):
trans.matrix[i][j] = self.matrix[j][i]
trans.show()
m1 = Matrix()
m2 = Matrix()
m3 = Matrix()
print("1.Enter elements in matrices\n2.Addition of matrices\n3.Subtraction of matrices\n4.Multiplication of "
"matrices\n5.Transpose of matrix")
while True:
print()
c = int(input("Enter your choice"))
if c == 1:
print("For first matrix")
m1.get_mat()
print("For second matrix")
m2.get_mat()
print("First matrix")
m1.show()
print("Second matrix")
m2.show()
elif c == 2:
if m1.row == m2.row and m1.col == m2.col:
print("Addition of matrices is")
m1.add_mat(m2)
else:
print("Operation can't perform as matrix are not similar. Enter new matrices")
elif c == 3:
if m1.row == m2.row and m1.col == m2.col:
print("Subtraction of matrices is")
m1.sub_mat(m2)
else:
print("Operation can't perform as matrix are not similar. Enter new matrices")
elif c == 4:
if m1.col == m2.row:
print("Multiplication of matrices is")
m1.mul_mat(m2)
else:
print("Operation can't perform as no of column are not equal to no of row. Enter new matrices")
elif c == 5:
print("for check transpose of matrix")
m3.get_mat()
print("Entered matrix")
m3.show()
print("Transpose of matrix is")
m3.transpose_mat()
else:
print("Quiting program")
break
|
ebded9516b55eb209e1e4f341d2448d6f332cf2b | jcebo/pp1 | /04-Subroutines/16.2.py | 157 | 3.65625 | 4 | def czytajLiczbe():
x=float(input("Podaj pierwsza liczbę: "))
y=float(input("Podaj drugą liczbę: "))
print(f"suma tych liczb to: {x+y} ")
|
15977e97daf18502cf94fa2752c6bd5f3842f16f | NPHackClub/BeginnerRoom-2020 | /Week 10 - math/Week 10 - Math.py | 302 | 4.125 | 4 | #User input and statement
n = int(input("Enter number: "))
print("multiplication table of", n)
#Multiplication of n to 10
for x in range(1,11):
print(n*x)
#Sum of all numbers until n and statement
print("sum of all numbers until", n)
total = 0
for y in range(n+1):
total += y
else:
print(total) |
ff0fd1569f4c8fa095a543522cd80c3547abfffc | MadDogofDarkness/data-stuff | /inter.py | 2,258 | 4.0625 | 4 | syntax = ["the syntax of the language is each operation is on a single line",
"each operation can have one or more operators",
"no one function name or operator can be longer than 4 characters",
"new functions can be defined"]
functions = ["low", "big", "add", "sub", "mult", "div", "deff"]
def deff(funcname, operators):
if len(funcname) <= 4:
functions.append(funcname)
return 0
else:
return 1
def div(operator1, operator2):
return operator1 / operator2
def mult(operator1, operator2):
return operator1 * operator2
def sub(operator1, operator2):
return operator1 - operator2
def add(operator1, operator2):
return operator1 + operator2
def big(operator1, operator2):
#returns the bigger of the two operators
#if they are the same, returns operator1
if operator2 > operator1:
return operator2
else:
return operator1
def low(operator1, operator2):
#returns the lower of two operators
#if they are the same, returns operator1
if operator2 >= operator1:
return operator1
else:
return operator2
def convert_to_record(data):
tostore = None
'''this takes in a data which is a list, or tuple, and converts it to the correct format for storage in the database'''
'''if type is a list, array or tuple, will treat as a block of data'''
'''if type is an object, will assume the data is presented in the following format'''
'''[classname: name_of_object, attr1: value, ..., attr_n: value_n]'''
tostore = "["
for entry in data:
print(entry) # debug
tostore += str(data)
tostore += ','
tostore += ']'
print(len(tostore)) # debug
print(tostore) # debug
return tostore
def delimit(data, delimiter):
formatted = []
store = ""
for c in data:
if c == delimiter:
formatted.append(store)
store = ""
else:
store += c
formatted.append(store)
#print(formatted)#debug
return formatted
if __name__ == "__main__":
print(syntax)
ebin = input("enter here: ")
#convert_to_record2(ebin)
delimit(ebin, '%') |
b1d50d7863f3efbe15208fa669cd926958abb931 | Vijendrapratap/Machine-Learning | /Week2/Tuple/6. WAP to check whether an element exists within a tuple.py | 298 | 4.125 | 4 | """
Write a Python program to check whether an element exists within a tuple.
"""
new_tuple = (12, 23, 34, 45, 56, 67, 78)
element = int(input("Enter element : "))
if element in new_tuple:
print("{} is present in tuple ".format(element))
else:
print("{} is not present in tuple".format(element)) |
c58d807653035847ec8efd10c643e4d51099b2f5 | thewritingstew/lpthw | /ex30.py | 711 | 4.21875 | 4 | people = 30
cars = 40
trucks = 15
# checks to see if there are more cars than people
if cars > people:
# if there are more cars, it prints this
print "We should take the cars."
# otherwise it checks to see if there are less cars than people
elif cars < people:
# and if so it prints this
print "We should not take the cars."
# if none of the other conditions are met, it prints this
else:
print "We can't decide."
if trucks > cars:
print "That's too many trucks."
elif trucks < cars:
print "Maybe we could take the trucks."
else:
print "We still can't decide."
if people > trucks:
print "Alright, let's just take the trucks."
else:
print "Fine, let's stay home then."
|
98e1ec11d2c48ca3bb1af3e3582a0c9c1762e5d0 | Brinda2510/Assignment5 | /a.py | 2,803 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
from collections import Counter
import cv2
import pandas as pd
num = ["TRUE" if i%2==0 else "FALSE" for i in range (1301)]
print(num)
import functools
q=range(1,10)
print (functools.reduce(lambda x,y:x*y,q))
def f(x):
def g(y):
return y + x
return g
nf1 = f(1)
nf2 = f(3)
print(nf2(1))
def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print(longest_word('test.txt'))
class Triangle:
def __init__(self,a,b,c):
self.a = float(a)
self.b = float(b)
self.c = float(c)
def area(self):
s=(self.a + self.b + self.c)/2
return((s*(s-self.a)*(s-self.b)*(s-self.c))**0.5)
a=input("Enter the value of a = ")
b=input("Enter the value of b = ")
c=input("Enter the value of c = ")
t = Triangle(a, b, c)
print("area : {}".format(t.area()))
import random
lowercase= 'abcdefghijklmnopqrstuvwxyz'
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits = '0123456789'
punctuation = '!"#$%&\'()*+,-./:;<=>?@[]^_{|}~'
allowed = lowercase + uppercase + digits + punctuation
visually_similar = 'Il1O05S2Z'
def new_password(length:int, readable=True) -> str:
if length < 4:
print("password length={} is too short,".format(length),
"minimum length=4")
return ''
choice = random.SystemRandom().choice
while True:
password_chars = [
choice(lowercase),
choice(uppercase),
choice(digits),
choice(punctuation)
] + random.sample(allowed, length-4)
if (not readable or
all(c not in visually_similar for c in password_chars)):
random.SystemRandom().shuffle(password_chars)
return ''.join(password_chars)
def password_generator(length, qty=1, readable=True):
for i in range(qty):
print(new_password(length, readable))
def list_ends(a_list):
return [a_list[0], a_list[len(a_list)-1]]
a_list[1,1,2,3,4]
def sec(n):
main=list(1,2,3,4)
even=list()
odd=list()
index=0
for number in main:
if index%2!=0:
even.append(number)
else:
odd.append(number)
index +=1
final_even = " enter number".join(even)
final_odd = "enter number".join(odd)
print(final_even)
print(final_odd)
sec('1,2,2,3,4,5,6,7')
sec = ['abc','def','ghi','ert','yui']
def divide(l,n):
for i in range(0, len(l), n):
yield l[i:i + n]
n = 3
x = list(divide(sec, n))
while n>0:
n+=1
if n==3:
break
print(x)
|
d4ceb2b07f26490f4e492c96ac6890c527cf923d | dewlytg/Python-example | /48-sched调度模块 | 1,242 | 3.71875 | 4 | #!/usr/bin/python
#coding=utf-8
"""
通过调用scheduler.enter(delay,priority,func,args)函数,可以将一个任务添加到任务队列里面,当指定的时间到了,就会执行任务(func函数)。
delay:任务的间隔时间。
priority:如果几个任务被调度到相同的时间执行,将按照priority的增序执行这几个任务。
func:要执行的任务函数
args:func的参数
"""
import time,sched
#周期性执行给定的任务
#初始化sched模块的scheduler类
#第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。
s = sched.scheduler(time.time,time.sleep)
#被周期性调度触发的函数
def event_func1():
print "func1 Time:",time.time()
def perform1(inc):
s.enter(inc,0,perform1,(inc,))
event_func1()
def event_func2():
print "func2 time:",time.time()
def perform2(inc):
s.enter(inc,0,perform2,(inc,))
event_func2()
def mymain(func,inc=2):
if func == '1':
s.enter(0,0,perform1,(10,))#每10秒钟执行perform1
if func == '2':
s.enter(0,0,perform2,(20,))#每20秒执行perform2
if __name__ == "__main__":
mymain('1')
mymain('2')
s.run()
|
f3029e182ec3e5d41db752e29c78a3112da2ef2f | nbrahman/HackerRank | /04 Cracking the Coding Interview/BFS-Shortest-Reach-in-a-Graph.py | 1,085 | 3.578125 | 4 | from queue import Queue
def readInputs_buildGraph():
n, m = map(int, input().strip().split(' '))
graph = [0]
for j in range(n):
graph.append([])
for j in range(m):
(x, y) = map(int, input().strip().split(' '))
graph[x].append(y)
graph[y].append(x)
return n, graph
def computeDistance(s, graph):
distances = {s: 0}
q = Queue ()
q.put(s)
while (not q.empty()):
e = q.get()
d = distances[e] + 6
for neighbor in graph[e]:
if neighbor in distances:
continue
distances[neighbor] = d
q.put(neighbor)
return distances
def showDistances(s, n, distances):
for i in range(1, n + 1):
if (i == s):
continue
if i in distances:
print(distances[i], end = ' ')
else:
print(-1, end = ' ')
print()
t = int(input())
for i in range(t):
n, graph = readInputs_buildGraph()
s = int (input().strip())
distances = computeDistance(s, graph)
showDistances(s, n, distances)
|
9251af164f1604e594e99f48b837556a58b1cd73 | zenyj/lab-08-for-loops | /tens.py | 83 | 3.5625 | 4 | #for (i = 20; i <= 100; i = i + 10)
for i in range (20,110,10):
print(i)
|
8f5c389fe1d4d7c87ee48368a3120fdbfe0501e2 | souvikb07/DS-Algo-and-CP | /leetcode/easy_1.py | 1,990 | 4 | 4 | """
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 105
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
"""
# Solution 1
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
output_dict = {}
for i,num in enumerate(nums):
next_num = target-num
if next_num in output_dict:
return [output_dict[next_num],i]
else:
output_dict[num] = i
# Solution 2
"""
Approach 2: Two-pass Hash Table
To improve our run time complexity, we need a more efficient way to check if the complement exists in the array. If the complement exists, we need to look up its index. What is the best way to maintain a mapping of each element in the array to its index? A hash table.
We reduce the look up time from O(n)O(n) to O(1)O(1) by trading space for speed. A hash table is built exactly for this purpose, it supports fast look up in near constant time. I say "near" because if a collision occurred, a look up could degenerate to O(n)O(n) time. But look up in hash table should be amortized O(1)O(1) time as long as the hash function was chosen carefully.
A simple implementation uses two iterations. In the first iteration, we add each element's value and its index to the table. Then, in the second iteration we check if each element's complement (target - nums[i]target−nums[i]) exists in the table. Beware that the complement must not be nums[i]nums[i] itself!
""" |
a8bb2ea221dc3aa27efe6471ae7ca17c2d993e7b | PuppeteerQ/Cristina-s-CS-Final-Project | /Car_Inventory/cardb.py | 7,341 | 4.0625 | 4 | """
The goal of Car_inventory project is to write a program that can manipulate a car inventory database and accessories database with functions of:
1.find car
2.add car
3.remove car
4.show database
5. find accessories by car
6.export inventory
7. quit program
The cardb.py file is to create a program that can initialize, read in and manipulate databases.
Overall, the program is divided into 3 parts.
Part 1: Class for database of car
Part 2: Class for database of accessories
Part 3: Search engine(or a program created to manipulate carDB and accDB)
"""
import json
#import json module
from tabulate import tabulate
#import tabulate module to format output
#create a Car class
class Car(object):
#initialization
def __init__(self,model_num,year,color,maker,model,body_type,quantity):
self.model_num = model_num
self.year = year
self.color = color
self.maker = maker
self.model = model
self.body_type = body_type
self.quantity = quantity
#convert to a json file
def tojson(self):
return self.__dict__
#return a static method
@staticmethod
#create a function that demonstrate db info on car with formatted output
def list_cars_info(cars):
print(tabulate([car.values() for car in cars],
headers= list(cars[0].keys())))
@staticmethod
#create a function to add cars in inventory
def add_car():
#takes input from users
model_num = str(input("Please input car model number: "))
year = int(input("Please input car year: "))
color = str(input("Please input car color: "))
maker = str(input("Please input car maker: "))
model = str(input("Please input car model: "))
body_type = str(input("Please input car body type: "))
quantity = int(input("Please input car quantity: "))
#append the init method
c = Car(model_num,year,color,maker,model,body_type,quantity)
#return the inventory
return c
#Create a class for the 2th part - accessory db
class Accessory(object):
#initialization
def __init__(self,seq_id,name,model_number,year,color,maker,model,body_type,quantity):
self.seq_id = seq_id
self.name = name
self.model_number = model_number
self.year = year
self.color = color
self.maker = maker
self.model = model
self.body_type = body_type
self.quantity = quantity
#convert to a json file
def tojson(self):
return self.__dict__
#create a function that demonstrate db info on accessories with formatted output
@staticmethod
def list_accessories_info(accessories):
print(tabulate([acc.values() for acc in accessories],
headers= list(accessories[0].keys())))
#Part 3: Create a search engine(program) class to manipulate DBs
class CarDBEngine(object):
#initialization
def __init__(self):
self.car_db = {}
self.accessory = {}
#Create a function to load database
#since we already have info of databases in JSON file, to load databases, simply read the JSON file
def load_db(self,json_file):
#
with open(json_file,'r') as fp:
db = json.load(fp)
self.car_db = db['cars']
self.accessory = db['accessories']
# Find Car by Model Number
def find_car_by_model_number(self,model_number):
if model_number in self.car_db.keys():
Car.list_cars_info([self.car_db[model_number]]);
#function to add car
def add_car(self):
c = Car.add_car().tojson()
self.car_db[c['model_num']] = c
#function to remove car
#delete car by given model number
def remove_car_by_model_number(self,model_num):
if model_num in self.car_db.keys():
del self.car_db[model_num]
#display car inventory
def show_inventory(self):
Car.list_cars_info(list(self.car_db.values()));
def export_inventory(self):
#create a function to export inventory
#convert dict into string that can be write in JSON file
db = {}
db['cars'] = {}
db['accessories'] = {}
for key,value in self.car_db.items():
db['cars'][key] = value
for key,value in self.accessory.items():
db['accessories'][key] = value
with open('cardb.json','w') as fp:
json.dump(db,fp)
#create a function to find a match
def find_matched_cars(self,seq):
if seq in self.accessory.keys():
model_number = self.accessory[str(seq)]['model_number']
if model_number in self.car_db.keys():
Car.list_cars_info([self.car_db[model_number]])
else:
print('No Match')
else:
print('No Match')
#create a function show acc database
def show_accessories(self):
#output accesspry info
Accessory.list_accessories_info(list(self.accessory.values()));
#if user inputs quit, exit program
def quit(self):
print('See you next time')
self.export_inventory()
exit(0)
#main function, operation meun
if __name__ == '__main__':
engine = CarDBEngine()
print('Welcome to the mini Car database engine (enter quit to exit)')
print("Instructions:")
print("<find car> find the car given model number")
print("<add car> add a new type of car")
print("<remove car> remove car given model number")
print("<show cars> show all cars")
print("<show acc> show all accessories")
print("<export> export the db to json file")
print("<find match> find match by giving accessory seq id")
#open the json file that contains database we have set up in advance
engine.load_db('cardb.json')
#if everything okay
while True:
#Tell user to input a command
cmd = input("please input your command: ")
#if user inputs find car
#request input of model number
#call engine to find car by model number given
if "find car" == cmd:
model_number = (input("please input model number: "))
engine.find_car_by_model_number(model_number)
#if user inputs add car
#call engine to add car
elif "add car" == cmd:
engine.add_car()
#if user inputs remove car
#request for a model number
#then removed
elif "remove car" == cmd:
model_number = (input("please input model number: "))
engine.remove_car_by_model_number(model_number)
#if user inputs show cars
#call engine to show inventory
elif "show cars" == cmd:
engine.show_inventory()
#if user inputs show acc
#call engine to show acc inventory
elif "show acc" == cmd:
engine.show_accessories()
#if user inputs export
#call engine's export object
elif "export" == cmd:
engine.export_inventory()
#if user inputs find match
#call engine to find match by seq id
elif "find match" == cmd:
seq_id = (input("please input accessory seq id: "))
engine.find_matched_cars(seq_id)
#if user inputs quit, stop the program
elif "quit" == cmd:
engine.quit()
#if input is not valid
#reshow the meun
else:
print("your command is wrong")
print("Instructions:")
print("<find car> find the car given model number")
print("<add car> add a new type of car")
print("<remove car> remove car given model number")
print("<show cars> show all cars")
print("<show acc> show all accessories")
print("<export> export the db to json file")
print("<find match> find match by giving accessory seq id")
#engine.load_db('cardb.json')
#engine.show_accessories()
#engine.find_car_by_model_number('c3')
#engine.add_car()
#engine.remove_car_by_model_number('c5')
#engine.export_inventory()
#engine.find_matched_cars(1) |
163249718b991047cfb3c5245332ec871080a1e4 | kingwongf/basic_algos | /basic_algos3.py | 4,180 | 3.8125 | 4 |
def merge_sort(arr):
if len(arr)>1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i=j=k=0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
arr[k] = R[j]
j+=1
k+=1
while i < len(L):
arr[k] = L[i]
i+=1
k+=1
while j < len(R):
arr[k] = R[j]
j+=1
k+=1
return arr
def recur_fib(n):
if n ==1:
return 1
elif n==2:
return 1
else:
return recur_fib(n-1) + recur_fib(n-2)
def prime_sieve(n):
primes = [True]*(n+1)
p=2
while p*p<=n:
if primes[p]:
for j in range(p*2,n+1,p):
primes[j] = False
p+=1
return [p for p in range(n+1) if primes[p]]
def non_recur_fib(n):
d=[1,1]
while len(d)< n:
d.append(d[-1]+d[-2])
return d
def merge_sort2(arr):
if len(arr)>1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
merge_sort2(L)
merge_sort2(R)
i=j=k=0
while len(L) > i and len(R) > j:
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
arr[k] = R[j]
j+=1
k+=1
while len(L) >i:
arr[k] = L[i]
i+=1
k+=1
while len(R) >j:
arr[k] = R[j]
j+=1
k+=1
return arr
def binary_search(arr, elem):
print(list(zip(arr, list(range(len(arr))))))
sorted_arr = merge_sort(arr)
lb = 0
ub = len(sorted_arr) -1
while lb <=ub:
mid = (lb +ub)//2
if sorted_arr[mid] > elem:
ub = mid -1
elif sorted_arr[mid] < elem:
lb = mid +1
elif sorted_arr[mid] == elem:
return mid
return 'not in list'
def bubble_sort(arr):
for i in range(len(arr)):
swapped=False
for j in range(len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped=True
if swapped is False:
return arr
def part(arr, low, high):
i = low-1
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i+=1
arr[i],arr[j] = arr[j], arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return i+1
def quick_sort(arr, low, high):
if low < high:
pi = part(arr, low, high)
quick_sort(arr, low, pi-1)
quick_sort(arr, pi+1, high)
def beta(X,y):
import numpy as np
return np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)
def nonrecur_factorial(n):
r=n
for i in range(1,n-1):
r*=(n-i)
return r
def combinations(n,k):
'''
nCr = n!/((n-k)!*(k!))
= (n*(n-1)*(n-2) *...*(n-k+1))/ (k(k-1)(k-2)*...*(1))
:param n:
:param k:
:return:
'''
r = 1
for i in range(k):
r*= (n-i)
r= r/(i+1)
return r
def permutation(n,k):
'''
nPr = n!/k!
= n(n-1)(n-2)*...*(n-k+1)
:param n:
:param k:
:return:
'''
r = 1
for i in range(k):
r*= (n-i)
return r
def part2(arr, low, high):
i = low-1
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i+=1
arr[j], arr[i] = arr[i], arr[j]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i +1
def quicksort2(arr,low,high):
if low < high:
pi = part2(arr,low,high)
quicksort2(arr, low, pi-1)
quicksort2(arr, pi+1, high)
print('merge sort')
print(merge_sort([6,4,2,1,7,4,3]))
print("non recur fib")
print(non_recur_fib(10))
print("recur fib")
print(recur_fib(10))
print('merge sort 2')
print(merge_sort([6,4,2,1,7,4,3]))
print('bubble sort')
print(merge_sort([6,4,2,1,7,4,3]))
print('binary search')
print(binary_search([6,4,2,1,7,4,3], 3))
print([6,4,2,1,7,4,3].index(3))
print('quick sort')
li = [6,4,2,1,7,4,3]
low = 0
high = len(li)-1
quick_sort(li, low,high)
print(li)
|
ae2b7ec87540f34bc939985edcfed83fc895d76b | AeroX2/ncss-challenge | /2013/week-3/challenge35.py | 1,160 | 3.875 | 4 | import string
from math import sqrt
def sim(a,b):
while (len(a) != len(b)):
if (len(a) > len(b)):
b.append(0)
else:
a.append(0)
sum = 0
sumA = 0
sumB = 0
for i in range(len(a)):
sum += a[i] * b[i]
sumA += a[i]**2
sumB += b[i]**2
return sum / (sqrt(sumA) * sqrt(sumB))
def biggest_word(file_text):
i = 0
for word in file_text:
word = word.strip(string.punctuation)
if (len(word) > i):
i = len(word)
return i
def find_freq(file_text):
freqs = [0] * biggest_word(file_text)
for word in file_text:
word = word.strip(string.punctuation)
if (word != ""):
freqs[len(word)-1] += 1
return freqs
file = open("texts.txt")
file2 = open("unknown.txt")
freq1 = find_freq(file2.read().split())
blub = []
new = []
for line in file:
if (line.strip() != ""):
file3 = open(line.strip())
freq2 = find_freq(file3.read().split())
new.append((float(sim(freq1,freq2)),line.strip()))
blub = sorted(new, key=lambda x:(-x[0], x[1]))
for i in blub:
print("{:.3f} {}".format(i[0],i[1]))
|
3bd9cafa9e28d879b801f5264bd4fd2c69d90168 | EnriquePinto/Coursera-DiscreteOptimization | /week2/knapsack/solver_greedy.py | 1,205 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from collections import namedtuple
Item = namedtuple("Item", ['index', 'value', 'weight'])
def density(item):
val=item.value
weight=item.weight
return val/weight
def greedy(input_data):
# Modify this code to run your optimization algorithm
# parse the input
lines = input_data.split('\n')
firstLine = lines[0].split()
item_count = int(firstLine[0])
capacity = int(firstLine[1])
items = []
for i in range(1, item_count+1):
line = lines[i]
parts = line.split()
items.append(Item(i-1, int(parts[0]), int(parts[1])))
# a trivial algorithm for filling the knapsack
# it takes items in-order until the knapsack is full
value = 0
weight = 0
taken = [0]*len(items)
s_items=sorted(items,key=density,reverse=True)
for item in s_items:
if weight + item.weight <= capacity:
taken[item.index] = 1
value += item.value
weight += item.weight
# prepare the solution in the specified output format
output_data = str(value) + ' ' + str(0) + '\n'
output_data += ' '.join(map(str, taken))
return output_data
|
0989662fcba1b2f0290b50f71981cdf5cde5e4ae | iagsav/AS | /T2/SemenovaDS/2.1.py | 248 | 3.671875 | 4 | def is_prime(var):
for i in range(2,var+1):
a=0
for j in range(2,i):
if i%j==0:
a=1
break
if a==0:
print(i);
b=int(input("Введите число:"))
is_prime(b)
|
9ffd37059a6700adb4244a1b0155292bc0277417 | zuozuo12/usualProject | /python/Final18F_scripts/DerIntRoot.py | 7,517 | 4.3125 | 4 | #
# name:
# email:
#
# Note you are not allowed to change the any of the function interface defined below,
# you should call these functions by using propers inputs to solve the problems
# specified in the handout.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.integrate import quad
from nonlinear_eqn import *
from quadra import *
#the input x can be a vector, in that case your returned function values should also be a vector.
#this should be easily done by numpy array.
def func(x, n=100):
''' compute the function f(x,n) = 1 + sin(x) + sin(2x)/2 + sin(3x)/3 + ... + sin(nx)/n
(since n is given, essentially this is a single variable function)
return the function evaluated at x (note, the input x can be a vector)
'''
result=[];
# print(x)
for xi in x:
fn = 1;
for i in range(1,n+1):
fn=fn+np.sin(i*xi)/i;
result.append(fn);
return result;
def func1(x, n=100):
''' compute the function f(x,n) = 1 + sin(x) + sin(2x)/2 + sin(3x)/3 + ... + sin(nx)/n
(since n is given, essentially this is a single variable function)
return the function evaluated at x (note, the input x can be a vector)
'''
fn = 1;
for i in range(1,n+1):
fn=fn+np.sin(i*x)/i;
return fn;
def fder(x, n=100):
''' compute the derivative of f(x,n) = 1 + sin(x) + sin(2x)/2 + sin(3x)/3 + ... + sin(nx)/n,
you differentiate term by term (easy via basic calculus here), then sum them up.
return the derivative evaluated at x (note, the input x can be a vector)
'''
result = [];
# print(x)
for xi in x:
fn = 0;
for i in range(1, n + 1):
fn = fn + np.cos(i*xi);
result.append(fn);
return result;
def fder1(x, n=100):
''' compute the derivative of f(x,n) = 1 + sin(x) + sin(2x)/2 + sin(3x)/3 + ... + sin(nx)/n,
you differentiate term by term (easy via basic calculus here), then sum them up.
return the derivative evaluated at x (note, the input x can be a vector)
'''
fn = 0;
for i in range(1, n + 1):
fn = fn + np.cos(i*x);
return fn;
def plot_funcs(func, nset=[2, 5, 8, 10], a=-5, b=5):
''' plot the func(x,n) on [a,b] for n in nset for x on [a, b], save plot to fourier.png '''
for ni in nset:
result=func(np.linspace(a,b,1001),ni);
plt.plot(np.linspace(a,b,1001),result,label='n={}'.format(ni));
plt.plot(np.linspace(a,b,1001),np.linspace(a,b,1001)*0,'--')
plt.legend()
plt.title("Plot of f(x,n)");
plt.ylabel("f(x,n)")
plt.xlabel("x")
plt.savefig("fourier.png")
plt.show()
def plot_funcs_der(func, fder, n=8, a=-5, b=5):
''' plot the derivative of func(x,n) on [a,b] for a fixed n;
call fder() for exact derivative, plot this line with linestyle 'r--' and lw=4;
use numerical derivative via CFD with the two h values specifed in hand out,
you can plot these two lines using any linestyle but do not increase lw for them;
save plot to fourier_der.png.
'''
# input below the first function in the project PDF using lambda
f1 = lambda x: func1(x,n);
# compute derivatives f1', f1'', f1''' manually and list them below as f1der, f1der2, f1der3 (use lambda)
f1der = lambda x: fder1(x,n);
x = [p for p in np.linspace(a, b, 1001)] # intentionally set x to be a list
der = fder(x, n);
print(der)
plt.plot(x, der,label="exact: n={}".format(n));
for h in [0.2, 0.001]:
cfd=FD_1st_order(f1, x, h, fder=f1der, filename='function1')
plt.plot(x,cfd,'--',label="CFD: n={},h={}".format(n,h));
plt.legend();
plt.xlabel("x");
plt.ylabel("f(x,15)");
plt.title("first order derivative of f(x,15")
plt.show()
plt.savefig("fourier_der.png")
def FD_1st_order(f, x, h=1e-4, fder=None, filename=None):
'''compute 1st order derivative of f(x) using FFD, CFD, BFD.
tasks:
(1) output f'(x) in a tuple named (ffd, cfd, bfd), where ffd, cfd, bfd store the
f'(x) obtained by FFD, CFD, and BFD;
(2) call FD_plot() to do the plotting:
(2.1) when exact f'(x) is passed as input via fder, need to pass it on so that
a curve of exact dervative will be plotted in addition to FD curves
(2.2) when filename is passed as input, need to pass it on so that the plot will
be saved to a png file using a modification of this filename
'''
#add code to make sure elementwise operations such as x+h and x-h are valid for x
x = np.array(x)
#add code to compute 1st order ffd, bfd, cfd
cfd= [(f(i+h)-f(i-h))/(2*h) for i in x]
#add code to call FD_plot(), for the 1st order, this is done for you below
# FD_plot(x, h, cfd,fderivative=fder, FD_order='1st', filename=filename)
return cfd
def FD_plot(x, h, cfd,fderivative=None, FD_order=None, filename=None):
pass
def find_roots(func, n=10, tol=1e-12):
""" find all roots of f(x)=func(x,n) on [-10, 10], you should call the bisection() or ridder()
in the provided file nonlinear_eqn.py.
(you may set SHOW=True to let the solver show results at each step.)
generate a list [ (x1, f(x1)), (x2, f(x2), ..., (xk, f(xk)) ], where x1, x2, ..., xk are
all the roots of f(x) in [-10, 10] ordered in increasing order,
printout this list, and
return this list.
"""
#first define a lambda function to be passed to an equation solver
def fn_integral(f, a, b, npanel=1000, tol=1e-10):
""" find integral of f(x) on [a, b],
use simpson-1/3 rule with npanels, save the integral value in fsimpson,
use adaptive-trapezoid rule with accuracy tol, save the integral value in ftrap;
(note1: the n and tol required are different from the default, and you
are not allowed to change the interface above;
(note2: you can used the solvers provided in quadra.py; or you call your own code, just
copy and paste your own code from your 3rd project into this file.)
print out the integral values;
print out also the difference between the integrals obtained from the two solvers.
return a tuple (fsimpson, ftrap, fsimpson -ftrap)
"""
if __name__=='__main__':
""" call the functions above to achieve the tasks specified in the handout.
(since you are not allowed to change any of the function interfaces above,
you need to specify all the correct input variables in order to finish exactly
what the handout asks you to do.)
most of this part only need you to pass proper inputs to functions
"""
x=np.linspace(-10,10,100);
# call plot_funcs() to plot the functions
plot_funcs(func,[2,10,20,100],-10,10)
plot_funcs_der(func,fder,n=15,a=-2,b=2)
# call plot_funcs_der() to plot the derivative
# plot_funcs_der( )
# call find_roots() to find all the roots of func(x, 20) on [-10, 10]
# roots_froots = find_roots( )
# don't change the following two lines, it only checks if your output is correct
# for (i, rf) in enumerate(roots_froots):
# print('root{} = {:.14f}, f = {:.14e}'.format(i, rf[0], rf[1]))
# define a lambda functins, call fn_integral() to find the integral of this function
# f1 = lambda x:
# fn_integral( )
|
e18945288442346b9de22ea4780bbc673ac7c8e4 | guti7/hacker-rank | /python_OOP/ex5/animal.py | 1,767 | 3.890625 | 4 | # Make School OOP Coding Challenge Python Problem 5
import sys
# Implement Animal superclass
class Animal(object):
# Initializer
def __init__(self, name, food):
self.name = name
self.favoriteFood = food
# Sleep
def sleep(self):
print "%s sleeps for 8 hours" % self.name
# Eat
def eat(self, food):
print "%s eats %s" % (self.name, food)
if self.favoriteFood == food:
print "YUM! %s wants more %s" % (self.name, food)
# Implement Tiger class as a subclass of Animal
class Tiger(Animal):
def __init__(self, name):
super(Tiger, self).__init__(name, "meat")
# Implement Bear class as a subclass of Animal
class Bear(Animal):
def __init__(self, name):
super(Bear, self).__init__(name, "fish")
def sleep(self):
print "%s hibernates for 4 months" % self.name
# Tests
def test():
def getline():
# Read a line from stdin and strip whitespace
return sys.stdin.readline().strip()
# Get the number of animals
animalCount = int(getline())
# Iterate through the animals
for count in range(animalCount):
# Get the animal's species, name and food.
species = getline()
name = getline()
food = getline()
animal = None
# Check what animal's species
if species == "tiger":
# Create Tiger object
animal = Tiger(name)
elif species == "bear":
# Create a Bear object
animal = Bear(name)
else:
# Create an Animal object
animal = Animal(name, "kibble")
# Test the animal's instance methods
animal.eat(food)
animal.sleep()
# main
if __name__ == "__main__":
test()
|
3a6c0ad57224028392e2cbc9131850c2bb7db6f4 | reinaaa05/python | /paiza_05/paiza_05_005.erb | 639 | 3.78125 | 4 | # coding: utf-8
# Your code here!
# リストの整列
weapons = ["イージスソード", "ウィンドスピア", "アースブレイカー", "イナズマハンマー"]
print(weapons)
print(sorted(weapons))
print(sorted(weapons,reverse=True))
#数字を含む
weapons2 = ["4.イージスソード", "1.ウィンドスピア", "3.アースブレイカー", "2.イナズマハンマー"]
print(sorted(weapons2))
print(sorted(weapons2,reverse=True))
#漢字を含む
weapons3 = ["バーニングソード", "風神スピア", "大地ブレイカー", "稲妻ハンマー"]
print(sorted(weapons3))
print(sorted(weapons2,reverse=True))
|
e0cb09e427d7e2b1cbe80f3ddf57bb066dcc4b1b | Innocent19/week3_day3 | /day four/app/power.py | 237 | 4.28125 | 4 | a = int(input("Enter integer a : "))
b = int(input("Enter integer b : "))
def power(a,b):
if b==0:
return 1
if b<0:
return 1/a*power(a,b+1)
return a*power(a,b-1)
print(power(a,b)) |
7cdabddac31b26f9b398338365a68ddc29b7a40b | RashiKndy2896/Guvi | /Dec18_hw_05oddprint.py | 114 | 3.84375 | 4 | odd=[]
even=[]
i=1
for i in range(1,101):
if i%2 == 0:
even.append(i)
else:
odd.append(i)
print(odd) |
ca21d2f2abb0a557d166c4ad9c482d3bcb1d3314 | Kvazar78/Skillbox | /6.3_while_break/dz/task_5.py | 951 | 4.1875 | 4 | # Ваня увлекается историей, а в особенности календарями. Он изучает
# календари разных времён, эпох и народностей. Для исследования ему нужно
# посчитать, у кого сколько было месяцев с чётным количеством дней.
#
# Напишите программу, которая считает количество только чётных чисел
# в последовательности (последовательность заканчивается при вводе нуля)
# и выводит ответ на экран.
counter = 0
while True:
date = int(input('Вводи число: '))
if date == 0:
break
if date % 10 % 2 == 0:
counter += 1
print(f'Количество четных чисел в последовательности - {counter}')
|
07c538bd93fb2d4c78cf908110d00e216370ec67 | to-Remember/TIL | /May 31, 2021/1_var.py | 558 | 3.671875 | 4 | #주석: 프로그램 실행에 영향을 안줌. 없는 놈
'''
여러줄 주석
asdfasfd
asdff
asdasf
'''
# 변수를 정의함. 변수의 타입은 할당한 값의 타입을 따라감
str_val = 'abc'#문자열
int_val = 12 #정수
float_val = 23.345 #실수
bool_val = True #불
#type(): 괄호안에 넣은 값의 타입을 반환
print('str_val:', str_val, ', type:', type(str_val))
print('int_val:', int_val, ', type:', type(int_val))
print('float_val:', float_val, ', type:', type(float_val))
print('bool_val:', bool_val, ', type:', type(bool_val)) |
c858262f5a2fd5bee1b8f3d33da10c37ea7eca6e | zhuiwang/python_work | /huawei_jishi/4_daxiezimu.py | 215 | 3.75 | 4 | #!/usr/bin/env python3
while True:
try:
string = input()
num = 0
for s in string:
if 'A' <= s <= 'Z':
num += 1
print(num)
except:
break
|
b89587c149c1aa5d143706c799fa1858fe8f42a9 | SachinPitale/Python3 | /Python-2021/10.Loop/7.for-loop.py | 597 | 3.890625 | 4 |
my_string="Working with for loop"
print (my_string)
for each_char in my_string:
print (each_char)
print (" ".join(my_string))
print ("\n ".join(my_string))
my_list = [4,5,6,7,8]
for i in my_list:
print (i)
my_list1 = [(1,2),(3,4),(5,6)]
for i in my_list1:
print (i)
for i in my_list1:
for m in 0, 1:
print (i[m])
for i, j in my_list1:
print (i)
print (j)
my_dict = {"name": "sachin", "Profession": "IT", "Language": "Python"}
for i in my_dict.keys():
print (i)
for i in my_dict.values():
print (i)
for i in my_dict.items():
print (i)
|
6a651eb751fa9b756a16743f86422fe605f70e05 | gadoid/PythonNote | /thread_practice.py | 1,200 | 3.796875 | 4 | from threading import Thread,Lock
import time
# def counter():
# for i in range (10):
# print(i)
# time.sleep(1)
# def main():
# t1=Thread(target=counter)
# t1.start()
# t2=Thread(target=counter)
# t2.start()
# t1.join()
# t2.join()
class Account():
def __init__(self) -> None:
self._lock=Lock()
self._balance=0
def deposit(self,money):
self._lock.acquire()
try:
new_balance=self._balance+money
time.sleep(0.01)
self._balance=new_balance
finally:
self._lock.release()
@property
def balance(self):
return self._balance
class AddMoneyThred(Thread):
def __init__(self,account,money):
super( ).__init__()
self._account=account
self._money=money
def run(self):
self._account.deposit(self._money)
def main():
account=Account()
threads=[]
for _ in range(100):
t= AddMoneyThred(account,1)
threads.append(t)
t.start()
for t in threads:
t.join()
print(account.balance)
class read(Thread):
def __init__(self):
super().__init__(self) |
8bf364ddecb1fdb62d7745b3e825f0ee066aa788 | GabriellyBailon/Cursos | /CursoEmVideo/Python/Mundo 2/ex048.py | 464 | 4.0625 | 4 | #Mostrar a soma dos múltiplos inteiros de 3 que existem entre 1 e 500
soma = 0;
cont = 0;
for c in range(3, 501, 6):
soma = soma + c;
cont = cont + 1;
print(f"A soma desses {cont} números múltiplos de 3, é igual à {soma}");
#Realizando o laço com incrementação 3, se nota um padrão de que os números necessários crescem de 6
#em 6, o que demonstra que inserir essa informação no laço diretamente otimiza o código;
|
81b42a7b772698b0cc41e9358d5e4656127b1987 | SoundaryaGajjam/PythonPractice | /oops/class_object.py | 754 | 3.5625 | 4 | class Employee:
'Common base cls for all emps'
empCnt=0
def __init__(self, nm, sal):
self.name=nm
self.salary=sal
Employee.empCnt+=1
def displayCount(self):
print("Total emp count : %d" % Employee.empCnt)
def displayEmp(self):
print("Name : ", self.name, " Salary : ", self.salary)
e1 = Employee('AAA', 22000)
e1.displayCount()
e1.displayEmp()
e2 = Employee('BBB', 52000)
e2.displayCount()
e2.displayEmp()
#Built-in classes
print("Employee.__doc__ : ", Employee.__doc__)
help(Employee)
print("Employee.__name__ : ", Employee.__name__)
print("Employee.__module__ : ", Employee.__module__)
print("Employee.__bases__ : ", Employee.__bases__)
print("Employee.__dict__ : ", Employee.__dict__)
|
019838aa520ce2f7cda4486d319d5b6a7b983429 | MEng-Alejandro-Nieto/Python-3-Udemy-Course | /19 function exercises.py | 1,453 | 4.1875 | 4 | # write a function called "myfunc" that prints the string "Hello World"
def myfunc():
return print("Hello World")
myfunc()
print("")
# write a function called "myfunc" that takes in a Name, and prints "Hello Name"
def myfunc(Name):
return print(f"Hello {Name}")
myfunc("alejandro")
print("")
# define a function called "myfunc" that takes in a bolean value
#(True or False). if True return "Hello", and if False, Return "Goodbye"
def myfunc(a):
if a=="True":
return print("Good morning")
else:
return print("Goodbye")
myfunc("True")
print("")
#Define a function called myfunc that takes three arguments x,y,z. if z is True, return x, if z is false return y
def myfunc(x,y,z):
if z=="True":
return x
else:
return y
print(myfunc(1,2,"True"))
print("")
# Define a function called myfunc that takes in two arguments and returns their sum
def myfunc(a=0,b=0):
return a+b
print(myfunc(40,60))
print("")
# Define a function called is_even that takes in one argumet, and returns True if the passed-in value is even, False if it is not
def is_even(a):
if a%2==0:
return True
else:
return False
print(is_even(9))
print("")
# Define a function called "is_greater" that takes in two arguments, and returns True if the first value is greater than the second,
# False if it is less than or equal to the second.
def is_greater(a,b):
if a>b:
return True
else:
return False
print(is_greater(10,11))
print("")
#
|
ef5cf40ec867346b44ec5d7a6afabba14b35c55a | jimmyhzuk/morning-stock-market-emails | /ScrapeInformation/economic_calendar.py | 1,452 | 3.5625 | 4 | import requests
from datetime import datetime
today_date = datetime.now().strftime("%Y-%m-%d")
def scrape_economic_calendar():
r = requests.get(
'https://finnhub.io/api/v1/calendar/economic?token=c1n20v237fkvp2lsh1ag')
for x in r.json()['economicCalendar']:
# try:
if x['country'] == 'US':
if x['impact'] != 'low':
print(x)
time = x['time']
split_time = time.split(" ")
date = split_time[0]
if date == today_date:
print(x)
event = x['event']
impact = x['impact'].capitalize()
time = x['time']
x = time.split(" ")
time = x[1]
size = len(time)
time = time[:size - 3] + " EST"
print(event)
print(impact)
print(time)
return event, impact, time
else:
event = "No relevant economic events today"
impact = " "
time = " "
return event, impact, time
# except:
# Exception
# event = "No relevant economic events today"
# impact = "Medium"
# time = "12:15"
# return event, impact, time
scrape_economic_calendar() |
4ed4e0083099a5ec65a673c5f3bfbde230a52520 | vermamit89/problem_solving | /pattern.py | 1,221 | 4.21875 | 4 | # Pattern #1: Simple Number Triangle Pattern
# for i in range(1,6):
# for j in range(i):
# print(i, end=' ')
# print('')
# Pattern #2: Inverted Pyramid of Numbers
# for i in range(5,0,-1):
# for j in range(i):
# print((6-i),end=' ')
# print('')
# Pattern #3: Half Pyramid Pattern of Numbers
# for i in range(1,6):
# for j in range(1,i+1):
# print(j,end=' ')
# print('')
# Pattern #4: Inverted Pyramid of Descending Numbers
# for i in range(5,0,-1):
# for j in range(i):
# print(i,end=' ')
# print('')
# Pattern #5: Inverted Pyramid of the Same Digit
# for i in range(5,0,-1):
# for j in range(i):
# print('5',end=' ')
# print('')
# Pattern #6: Reverse Pyramid of Numbers
# for i in range(1,6):
# for j in range(i,0,-1):
# print(j,end=' ')
# print('')
# Pattern #7: Inverted Half Pyramid Number Pattern
# for i in range(6,1,-1):
# for j in range(i):
# print(j,end=' ')
# print('')
# Pattern #8: Pyramid of Natural Numbers Less Than 10
# index=1
# i=1
# while index<=6:
# j=0
# while j<i:
# print(index,end=' ')
# j+=1
# index+=1
# print('')
# i+=2
|
e2c92506657555e9a2d29a556a2e26680875666a | xuzifan08/LendingClub | /src/python/data_cleaning.py | 3,432 | 3.9375 | 4 | import pandas as pd
## This file is to read the raw csv file, clean the data and save it as cleaned data csv file
def removenull(dataframe, axis=1, percent=0.5):
"""
* removeNull function will remove the rows and columns based on parameters provided.
* dataframe : Name of the dataframe
* axis : axis = 0 defines drop rows, axis =1(default) defines drop columns
* percent : percent of data where column/rows values are null,default is 0.5(50%)
"""
df = dataframe.copy()
ishape = df.shape
if axis == 0:
rownames = df.transpose().isnull().sum()
rownames = list(rownames[rownames.values > percent * len(df)].index)
df.drop(df.index[rownames], inplace=True)
print("\nNumber of Rows dropped\t: ", len(rownames))
else:
colnames = (df.isnull().sum() / len(df))
colnames = list(colnames[colnames.values >= percent].index)
df.drop(labels=colnames, axis=1, inplace=True)
print("Number of Columns dropped\t: ", len(colnames))
print("\nOld dataset rows,columns", ishape, "\nNew dataset rows,columns", df.shape)
return df
def main():
df_chunk = pd.read_csv('/Users/xuzifan/Desktop/LendingClub/loan.csv', chunksize=1000000)
chunk_list = []
for chunk in df_chunk:
chunk_list.append(chunk)
loan = pd.concat(chunk_list)
loan = removenull(loan, axis=1, percent=0.5)
# 1. drop columns which has more than 95% same values
same_vals = ['tax_liens', 'chargeoff_within_12_mths', 'delinq_amnt', 'num_tl_120dpd_2m', 'num_tl_30dpd',
'num_tl_90g_dpd_24m', 'out_prncp', 'out_prncp_inv', 'policy_code', 'acc_now_delinq',
'pub_rec_bankruptcies', 'application_type', 'hardship_flag']
loan = loan.drop(same_vals, axis=1)
# 2. remove duplicate columns (based on observation)
"""duplicate=['purpose', 'funded_amnt', 'out_prncp_inv', 'total_pymnt_inv']"""
duplicate = ['purpose', 'funded_amnt', 'total_pymnt_inv'] #why??
loan = loan.drop(duplicate, axis=1)
# 3. select columns which makes sense for data warehouse and machine learning (based on observation)
cols_drop = ['pymnt_plan', 'zip_code', 'dti', 'pub_rec', 'total_rec_late_fee', 'recoveries',
'collection_recovery_fee', 'collections_12_mths_ex_med', 'disbursement_method', 'disbursement_method']
loan = loan.drop(cols_drop, axis=1)
# 4. filter out correlation
corr = loan.corr()
# drop the columns who have high correlations
corr_drop = ['int_rate', 'tot_hi_cred_lim', 'total_il_high_credit_limit', 'total_rev_hi_lim', 'revol_util',
'bc_util', 'tot_cur_bal', 'open_acc', 'num_actv_bc_tl', 'num_actv_rev_tl', 'num_bc_sats', 'num_bc_tl',
'num_op_rev_tl', 'num_rev_accts', 'num_rev_tl_bal_gt_0']
loan = loan.drop(corr_drop, axis=1)
# 5. Derive some new columns based on our business understanding that will be helpful in our analysis
# Loan amount to Annual Income ratio
loan['loan_income_ratio'] = loan['loan_amnt']/loan['annual_inc']
# Extract Year & Month from Issue date
loan['issue_month'], loan['issue_year'] = loan['issue_d'].str.split('-', 1).str
# generate ID for each row
loan["id"] = loan.index + 1
print(loan.shape)
# save dataframe as cleandata
loan.to_csv('/Users/xuzifan/Desktop/LendingClub/loan_clean.csv')
if __name__ == "__main__":
main()
|
04f4cf5d60191f12eb6087c225c747c93d002e3f | daniel-zm-fang/Cracking-the-Coding-Interview | /Chapter 2/Palindrome.py | 2,042 | 4.25 | 4 | # Implement a function to check if a linked list is a palindrome.
# method 1: reverse the linked list and check if it's same as the original
# method 2: iterative approach, pushing the 1st half of the linked list onto a stack then compare it to the 2nd half
# method 3: recursive approach
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def printLst(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
def addTail(self, data):
newTail = Node(data)
if self.head == None:
self.head = newTail
return
tail = self.head
while tail.next:
tail = tail.next
tail.next = newTail
def clone_reverse(self):
temp = self.head
info = []
new_lst = LinkedList()
while temp:
info.append(temp.data)
temp = temp.next
for i in range(len(info)-1, -1, -1):
new_lst.addTail(info[i])
return new_lst
def check_palindrome1(self):
copy = self.clone_reverse()
temp1, temp2 = self.head, copy.head
while temp1:
if temp1.data != temp2.data:
return False
temp1 = temp1.next
temp2 = temp2.next
return True
def check_palindrome2(self):
fast, slow = self.head, self.head
stack = []
while fast != None and fast.next != None:
stack.append(slow.data)
slow = slow.next
fast = fast.next.next
if fast != None: # has odd number of nodes, skip middle node
slow = slow.next
while slow != None:
if stack.pop() != slow.data:
return False
slow = slow.next
return True
lst = LinkedList()
lst.addTail(0)
lst.addTail(1)
lst.addTail(0)
print(lst.check_palindrome1())
print(lst.check_palindrome2())
|
edadf090594370372a66ee04467a1bdcd707ee24 | nicgirault/euler | /41.py | 1,807 | 4.03125 | 4 | # prime numbers are only divisible by unity and themselves
# (1 is not considered a prime number by convention)
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
available = ['1','2','3','4','5','6','7']
stack = []
res = []
for a in range(7):
p = available.pop(a)
stack.append(p)
for b in range(6):
p = available.pop(b)
stack.append(p)
for c in range(5):
p = available.pop(c)
stack.append(p)
for d in range(4):
p=available.pop(d)
stack.append(p)
for e in range(3):
p=available.pop(e)
stack.append(p)
for h in range(2):
p=available.pop(h)
stack.append(p)
p=available.pop()
stack.append(p)
str_num = ''
for x in stack:
str_num += x
num = int(str_num)
if isprime(num):
print num
available.append(stack.pop())
available.append(stack.pop())
available.sort()
available.append(stack.pop())
available.sort()
available.append(stack.pop())
available.sort()
available.append(stack.pop())
available.sort()
available.append(stack.pop())
available.sort()
available.append(stack.pop())
available.sort()
print sum(res)
|
4c0d70a3f3d83e9c11cd57ad9d7d5d89069070ad | PauloAlexSilva/Python | /Sec_7_colecoes/c_dicionarios.py | 5,911 | 4.15625 | 4 | """
Dicionários
OBS: Em algumas linguagens de programação, os dicionários Python são conhecidos por
mapas.
Dicionários são coleções do tipo chave/valor.
Dicionários são representados por chaves {}
print(type({}))
<class 'dict'>
OBS: Sobre os dicionários
- Chave e valor são separados por dois pontos 'chave : valor';
- Tanto chave como valor ser de qualquer tipo de dados;
- Podemos misturar tipos de dados;
# Criação de Dicionários
# Forma 1 (mais comum)
paises = {'pt': 'Portugal', 'br': 'Brasil', 'usa': 'Estados Unidos'}
print(paises)
print(type(paises))
# Forma 2 (menos comum)
paises = dict(pt='Portugal', br='Brasil', usa='Estados Unidos')
print(paises)
print(type(paises))
# Acessar elementos
# Forma 1 - Acessar via chave, da mesma forma que lista/tupla
print(paises['pt'])
# print(paises['ru'])
# OBS: Caso tentamos fazer um acesso utilizando uma chave que não existe,
# teremos o erro KeyError
# Forma 2 - Acessarvia get - Recomendado
print(paises.get('pt'))
print(paises.get('ru'))
# Caso o get não encontre o objecto com a chave informada será retornado o valor None
# e não será gerado Key Error
pais = paises.get('ru')
if pais:
print(f'Encontrei o país {pais}!')
else:
print(f'Não encontrei o país {pais}!')
# Podemos definir um valor padrão para caso não seja encontrado o objeto com a chave
informada
pais = paises.get('pt', 'Não encontrado!')
print(f'Encontrei o país {pais}!')
# Podemos verificar se determinada chave se encontra num dicionário
print('br' in paises)
print('ru' in paises)
print('Estados Unidos' in paises)
if 'ru' in paises:
russia = paises['ru']
# Podemos utilizar qualquer tipo de dado (int, float, string, boolean), inclusive lista,
# tupla dicionário, como chaves de dicionários.
# Tuplas por exemplo são bastante interessantes de serem utilizadas como chave de dicionários,
# pois as mesmas são imutáveis.
localidades = {
(35.6895, 39.6917): 'Escritórios em Tókio',
(40.7128, 74.0060): 'Escritórios em Nova York',
(35.7749, 122.4194): 'Escritórios em São Paulo'
}
print(localidades)
print(type(localidades))
# Adicionar elementos em um dicionário
receita = {'jan': 100, 'fev': 120, 'mar': 300}
print(receita)
print(type(receita))
# Forma 1 - Mais comum
receita['abr'] = 350
print(receita)
# Forma 2
novo_dado = {'mai': 500}
receita.update(novo_dado) # receita.update({'mai': 500})
print(receita)
# Actualizar dados num dicionário
# Forma 1
receita['mai'] = 550
print(receita)
# Forma 2
receita.update({'mai': 600})
print(receita)
# CONCLUSÃO 1: A forma de adicionar novos elementos ou atualizar dados em um dicionário é
# a mesma
# CONCLUSÃO 2: Em dicionários, NÃO podemos ter chaves repetidas.
# Remover dados de um dicionário
receita = {'jan': 100, 'fev': 120, 'mar': 300}
print(receita)
# Forma 1 - Mais comum
retorno = receita.pop('mar')
print(retorno)
print(receita)
# OBS 1: Aquie é preciso SEMPRE informar a chave, e caso não encontre o elemento,
# um KeyError é retornado
# OBS 2: Ao remover um objecto o valor deste objecto é sempre retornado
# Forma 2
del receita['fev']
print(receita)
# del receita['fev']
# Se a chave não existir será gerado um KeyError
# OBS: Neste caso o valor removido não é retornado.
"""
# Imagine que tem um comércio eletrónico, onde temos um carrinho de compras no qual
# adicionamos produtos.
"""
Carrinho de Compras:
Produto 1:
- nome;
- quantidade;
- preço.
Produto 2:
- nome;
- quantidade;
- preço.
# 1 - Poderíamos utilizar uma Lista para isso? Sim
carrinho = []
produto_1 = ['Playstation 4', 1, 300.00]
produto_2 = ['Go of war 4', 1, 50.00]
carrinho.append(produto_1)
carrinho.append(produto_2)
print(carrinho)
# Teríamos que saber qual é o índice de cada informação no produto.
# 2 - Poderíamos utilizar uma tupla para isso? Sim
produto_1 = ('Playstation 4', 1, 300.00)
produto_2 = ('God of War 4', 1, 50.00)
carrinho = (produto_1, produto_2)
print(carrinho)
# Teríamos que saber qual é o índice de cada informação no produto.
# 3 - Poderiamos utilizar um dicionário para isso? Sim
carrinho = []
produto_1 = {'nome': 'Playstation 4', 'quantidade': 1, 'preco': 300.00}
produto_2 = {'nome': 'God of War 4', 'quantidade': 1, 'preco': 50.00}
carrinho.append(produto_1)
carrinho.append(produto_2)
print(carrinho)
# Desta forma facilmente adicionamos ou removemos produtos no carrinho e em cada produto
# podemos ter a certeza sobre cada informação.
# Métodos de dicionários
dicionario = dict(a=1, b=2, c=3)
print(dicionario)
print(type(dicionario))
# Limparo o dicionário (Zerar dados)
dicionario.clear()
print(dicionario)
# Copiando um dicionário para outro
# Forma 1 (Deep Copy)
novo = dicionario.copy()
print(novo)
novo['d'] = 4
print(dicionario)
print(novo)
# Forma 2 (Shallow Copy)
# ambos são alterados
novo = dicionario
print(novo)
novo['d'] = 4
print(dicionario)
print(novo)
"""
# Forma não usual de criação de dicionários
outro = {}.fromkeys('a', 'b')
print(outro)
print(type(outro))
user = {}.fromkeys(['nome', 'pontos', 'email', 'profile'], 'desconhecido')
print(user)
print(type(outro))
# O método fromkeys recebe dois parâmetros: um interável e um valor.
# Ele vai gerar para cada valor do iterável uma chave e irá atribuir a
# esta chave o valor informado
veja = {}.fromkeys('teste', 'valor')
print(veja)
veja = {}.fromkeys(range(1, 11), 'novo')
print(veja)
|
5649e7958215c214968c06259c00898d9421cf86 | Jr-82/python_lessons | /task3_less2.py | 998 | 3.921875 | 4 | list_season = ['Зима', 'Весна', 'Лето', 'Осень']
list_month = ['Декабрь', 'Январь', 'Февраль']
diction_season = {1: 'Зима', 2: 'Весна', 3: 'Лето', 4: 'Осень'}
user_num = int(input('Введите номер месяца: '))
if user_num == 12:
print(f'{list_season[0]} --> {list_month[0]}')
print(f'{diction_season.get(1)} *** {list_month[0]}')
elif user_num == 1:
print(f'{list_season[0]} --> {list_month[1]}')
print(f'{diction_season.get(1)} *** {list_month[1]}')
elif user_num == 2:
print(f'{list_season[0]} --> {list_month[2]}')
print(f'{diction_season.get(1)} *** {list_month[2]}')
elif 3 <= user_num <= 5:
print(list_season[1])
print(diction_season.get(2))
elif 6 <= user_num <= 8:
print(list_season[2])
print(diction_season.get(3))
elif 9 <= user_num <= 11:
print(list_season[3])
print(diction_season.get(4))
else:
print('Двенадцати месяцев достаточно!')
|
393047177d30756ba577257add075131eaf43806 | aa2276016/Learning_Python | /LeetCode/p021_merge_two_sorted_list.py | 693 | 4.15625 | 4 | # p21 Merge two sorted list
# Easy
# Merge two sorted linked lists and return it as a new list.
# The new list should be made by splicing together the nodes of the first two lists.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
l1 = ListNode([1,2,4])
l2 = ListNode([1,3,4])
print(l1)
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
return ListNode(sorted(l1.val + l2.val))
# print(Solution().mergeTwoLists(l1, l2))
# TODO not finished, come back when data structure is learned
|
a15a911fe4a908938a4ea300768a384032a10bd4 | Mariama2006/holbertonschool-higher_level_programming | /0x0A-python-inheritance/2-is_same_class.py | 175 | 3.5 | 4 | #!/usr/bin/python3
"""My class
"""
def is_same_class(obj, a_class):
"""
function
"""
if type(obj) == a_class:
return True
else:
return False
|
0e3d80c71fab28d2785b6f943ad67efb5e1414a1 | mttk/ProjectEuler | /026.py | 876 | 3.609375 | 4 | ### Reciprocal cycles
# https://projecteuler.net/problem=26
def division(n, d):
"""
A cycle is defined by the number being divided and the divisor. Such a pair uniquely defines
the sequence of numbers occurring as a result of the division - if such a pair occurs twice consequently,
then the numbers between the occurrences are the elements of the cycle.
"""
signatures = {}
i = 0
while True:
if n == 0:
break
while n < d:
n *= 10
if n in signatures:
cycle_len = i - signatures[n]
return cycle_len
else:
signatures[n] = i
n = n % d
i += 1
return 0
max_num = 0.
max_cycle = 0.
for i in range(3, 999, 2):
cycle = division(1, i)
if cycle > max_cycle:
max_num = i
max_cycle = cycle
print max_num, max_cycle
|
b7d202e631c9d76259715c776c39df79d254aa8d | LiprikON2/ITMO | /Informatics/labs/lab_03_11.py | 654 | 3.5 | 4 | def encodeHuffman(fileIn, fileOut):
pass
def decodeHuffman(fileIn, fileOut):
pass
def count_chars(file):
textDict = dict()
with open(file, 'r') as f:
for line in f:
for char in line:
if char in textDict:
textDict[char] += 1
else:
textDict[char] = 1
return textDict
print(count_chars('sample.txt'))
def probability_of_chars(textDict):
char_sum = sum(textDict.values())
for char in textDict:
textDict[char] = textDict[char] / char_sum
return textDict
print(probability_of_chars(count_chars('sample.txt'))) |
3a3b579db8bcd4bf144cbcc60fb2619f21304a79 | him-28/Project-Euler | /prob53.py | 394 | 3.671875 | 4 | import time
tStart = time.time()
values = 0
def factorial(x):
y = 1
for i in range(1,x+1):
y = y * i
return y
def calc(n, r):
return factorial(n) / (factorial(r) * factorial(n-r))
for i in range(1,101):
for j in range(1, i):
if calc(i, j) > 1000000:
values += 1
print(values)
print("time:" + str(time.time() - tStart))
|
3efa5fed62d596961b14549d7e9fd1f797d7ed2b | qqss88/Leetcode-1 | /3_Longest_Substring_Without_Repeating_Characters.py | 861 | 4.21875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
Given a string, find the length of the longest substring without repeating characters.
For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
For "bbbbb" the longest substring is "b", with the length of 1.
@author: Jessie
@email: jessie.JNing@gmail.com
"""
class Solution:
# @param {string} s
# @return {integer}
def lengthOfLongestSubstring(self, s):
start, max_len = 0, 0
hash_s = {}
for i in range(len(s)):
if s[i] in hash_s:
start = hash_s[s[i]] + 1
hash_s[s[i]]=i
if i-start+1>max_len:
max_len= i-start+1
return max_len
if __name__=="__main__":
Solution_obj = Solution()
test_s = "abcabcbb"
print Solution_obj.lengthOfLongestSubstring(test_s) |
b824dbd1259a32c9a7b4073a9d980409d29b2919 | nanaboat/data-structures | /Linkedlist/LinkedList.py | 13,922 | 3.96875 | 4 | class Node:
'''Implements a node that stores the value and pointer to next node.'''
def __init__(self, data):
self._data = data
self._nextLink = None
def getData(self):
'''Returns the data in the node.'''
return self._data
def getNextLink(self):
'''Returns the pointer to the next node.'''
return self._nextLink
def setData(self, newData):
'''Insert data into node.'''
self._data = newData
def setNextLink(self, newNext):
'''Set a pointer to next node/reference.'''
self._nextLink = newNext
class UnorderedList:
'''Implements an unorderedList with only a head pointer.'''
def __init__(self):
self._head = None
self._size = 0
def isEmpty(self):
'''Checks if list is empty.Returns a boolean.'''
return self._size == 0
def add_front(self, item):
'''adds a new item to the front of the list. O(1) operation'''
temp = Node(item)
temp.setNextLink(self._head)
self._head = temp
self._size += 1
def pop_front(self):
'''Remove front item and return its value.'''
if self._head is None:
raise IndexError('Out of bounds')
current = self._head
nxt = current.getNextLink()
self._head = nxt
self._size -= 1
return current.getData()
def size(self):
'''returns the number of items in the list.'''
return self._size
def _find(self, item=None, idx=None):
'''Find a node in a list.
Arg:
-item: Integer/Character/String/Object
Returns:
A tuple of the index and the current node and previous node
'''
current = self._head
node = None
pos = 0
while pos < self._size:
if current.getData() == item or pos == idx:
node = current
return pos, node
else:
current = current.getNextLink()
pos += 1
return None, None
def search(self, item):
'''Search for the item in the list.
Arg:
-item: Integer/String/Character/Object
Returns
A boolean.
'''
index, node = self._find(item)
if node:
return True
return False
def value_at(self, index):
'''Returns the value of the nth item at given index.'''
index, node = self._find(idx=index)
if node:
return node.getData()
else:
raise IndexError('Out of bounds')
def remove(self, item):
'''removes the item from the list. It needs the item and modifies
the list. Returns None if item not in list.'''
current = self._head
previous = None
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNextLink()
# item to remove not in List.
if current is None:
raise IndexError('Out of bounds')
# item to be removed is first/head and connected to the head
if previous is None:
self._head = current.getNextLink()
# item removal is anywhere in the list but not the head
else:
previous.setNextLink(current.getNextLink())
self._size -= 1
def append(self, item):
'''adds a new item to the end of the list.'''
temp = Node(item)
current = self._head
end = False
while current is not None and not end:
if current.getNextLink() is None:
current.setNextLink(temp)
end = True
else:
current = current.getNextLink()
if current is None:
self._head = temp
self._size += 1
def insert(self, pos, value):
'''insert value at index, so current item at that index
is pointed to by new item at index.
Raise IndexError if index is out of range
'''
current = self._head
index = 0
found = False
# insert outside the length limits of list.
if pos > self._size - 1 or self._size == 0:
raise IndexError('Out of bounds')
while not found:
if index == pos:
found = True
else:
current = current.getNextLink()
index += 1
current.setData(value)
def __setitem__(self, index, item):
self.insert(index, item)
def index(self, item):
'''returns the position of item in the list.
Raises index error if item not in the list.
'''
index, node = self._find(item)
if node:
return index
else:
raise IndexError('Out of bounds')
def pop(self, index=None):
'''removes and returns the last item in the list. It needs nothing
and returns an item'''
current = self._head
previous = None
end = False
count = 0
value = None
# List is empty.
if current is None:
raise IndexError('Out of bounds')
if index is not None:
while current is not None and not end:
if count == index:
end = True
else:
previous = current
current = current.getNextLink()
count += 1
else:
while current is not None and not end:
if current.getNextLink() is None:
end = True
else:
previous = current
current = current.getNextLink()
# list contains only one item which is at the head
if previous is None:
self._head = None
value = current.getData()
# List has more than one item.
else:
if current.getNextLink() is None:
previous.setNextLink(None)
value = current.getData()
else:
previous.setNextLink(current.getNextLink())
value = current.getData()
self._size -= 1
return value
def __getitem__(self, index):
'''Returns the value of the indexed item.'''
return self.value_at(index)
def __len__(self):
return self.size()
def __iter__(self):
current = self._head
if current:
while current is not None:
yield current.getData()
current = current.getNextLink()
def front(self):
'''Get value of front item.'''
if self._head:
return self._head.getData()
else:
raise IndexError('Out of bounds')
def back(self):
'''Get value at the end of list.'''
current = self._head
end = False
if current is None:
raise IndexError('Out of bounds')
nxt = current.getNextLink()
while not end:
if nxt is None:
end = True
else:
current = nxt
nxt = current.getNextLink()
if end:
return current.getData()
def reverse(self):
'''Reverses the list.'''
previous = None
current = self._head
end = False
if current is None:
raise IndexError('Out of bounds')
nxt = current.getNextLink()
while not end:
current.setNextLink(previous)
previous = current
current = nxt
if nxt:
nxt = nxt.getNextLink()
else:
end = True
self._head = previous
class UnorderedListTail(UnorderedList):
'''Implements an unordered list with both the head and tail.'''
def __init__(self):
super().__init__()
self._tail = None
def add_front(self, item):
'''adds a new item to the list. It needs the item and returns nothing.
Assume the item is not already in the list.'''
temp = Node(item)
# Adding the first item to the list.
if self._head is None:
self._tail = temp
self._head = temp
else:
temp.setNextLink(self._head)
self._head = temp
self._size += 1
def append(self, item):
'''adds a new item to the end of the list making it the last item in
the collection.It needs the item and returns nothing. Assume the
item is not already in the list. '''
temp = Node(item)
if self._head is None:
self._head = temp
self._tail = temp
else:
current = self._tail
current.setNextLink(temp)
self._tail = temp
self._size += 1
def pop(self, index=None):
'''removes and returns the last item in the list. It needs nothing
and returns an item'''
current = self._head
previous = None
end = False
count = 0
value = None
# List is empty.
if current is None:
raise IndexError('Out of bounds')
if index is not None:
while current is not None and not end:
if count == index:
end = True
else:
previous = current
current = current.getNextLink()
count += 1
else:
while not end:
if current.getNextLink() is None:
end = True
else:
previous = current
current = current.getNextLink()
# list contains only one item which is at the head
if previous is None:
self._head = None
value = current.getData()
# List has more than one item.
else:
if current.getNextLink() is None:
previous.setNextLink(None)
self._tail = current
value = current.getData()
else:
previous.setNextLink(current.getNextLink())
value = current.getData()
self._size -= 1
return value
def back(self):
tail = self._tail
if tail:
return tail.getData()
else:
raise IndexError('Out of bounds')
def reverse(self):
'''Reverses the list.'''
previous = None
current = self._head
end = False
if current is None:
raise IndexError('Out of bounds')
nxt = current.getNextLink()
self._tail = current
while not end:
current.setNextLink(previous)
previous = current
current = nxt
if nxt:
nxt = nxt.getNextLink()
else:
end = True
self._head = previous
class OrderedList(UnorderedList):
'''Implements an ordered list.'''
def __init__(self):
super().__init__()
def search(self, item):
current = self._head
found = False
stop = False
while current is not None and not found and not stop:
if current.getData() == item:
found = True
else:
if current.getData() > item:
stop = True
else:
current = current.getNextLink()
return found
def add_front(self, item):
temp = Node(item)
if self._head is None:
self._head = temp
else:
current = self._head
previous = None
found = False
while current is not None and not found:
# item is placed at the head of the list
if current.getData() > item and previous is None:
self._head = temp
temp.setNextLink(current)
found = True
# item place in between the list
elif current.getData() > item and previous.getData() < item:
temp.setNextLink(current)
previous.setNextLink(temp)
found = True
else:
previous = current
current = current.getNextLink()
self._size += 1
def remove(self, item):
'''removes the item from the list. It needs the item and modifies
the list. Returns None if item not in list.'''
current = self._head
previous = None
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNextLink()
# item to remove not in List.
if current is None:
raise IndexError('Out of bounds')
# item to be removed is first/head and connected to the head
if previous is None:
self._head = current.getNextLink()
# item removal is anywhere in the list but not the head
else:
previous.setNextLink(current.getNextLink())
self._size -= 1
# TODO: fix ordered linkedlist class
|
b2c899bb6bf765720bb22fe4caf6ef4fe4b39584 | RyanSamman/KAU-CPIT110 | /Chapter 4/BooleanValue.py | 293 | 3.953125 | 4 | x = 10 > 20 # False
y = 10 < 20 # True
print('x =', x)
print('y =', y)
x = int(False) # 0
y = int(True) # 1
print(x, y)
x = bool(0) # if the number is 0, it will be false
y = bool(1) # any number not 0 will be true
print(x, y)
x = bool(-25)
y = bool(2000)
print(x, y)
|
a8649f5988f35929bf8fb206d9bc8559e5259047 | DHDaniel/mc-tictactoe | /MonteCarloPlayer.py | 5,333 | 3.703125 | 4 |
import copy
import random
class MonteCarloPlayer:
def __init__(self, TTT_board, player, num_trials):
"""
Initialises a machine player which chooses moves based on Monte Carlo simulations.
TTT_board should be of the class TTTBoard
num_trials is the desired number of trials to use in the Monte Carlo simulations
"""
try:
TTT_board.get_square(0, 0)
except:
raise ValueError("Board given does not appear to be of the type TTTBoard.")
self.board = copy.deepcopy(TTT_board)
# keeping a copy of the original
self.original_board = copy.deepcopy(self.board)
# player should be either 1 or 2
self.player = player
self.opponent = 2 if self.player == 1 else 1
self.identifier = self.board.get_identifier(self.player)
self.trials = num_trials
self.scores = [[0 for col in self.board.horizontals[0]] for row in self.board.horizontals]
def update_board(self, new_board):
"""
Takes in a TTTBoard and updates the internal one to the new one
"""
self.board = copy.deepcopy(new_board)
self.original_board = copy.deepcopy(new_board)
# re-setting scores
self.scores = [[0 for col in self.board.horizontals[0]] for row in self.board.horizontals]
def mc_trial(self):
"""
Performs a simulation of the game.
Plays a whole game, making random moves on the board, starting with his own move. Modifies
the internal board, doesn't return anything
"""
turn = True
while self.board.is_full() == False and self.board.is_won() == False:
empty_coord = self.board.random_empty_square()
self.board.play_square(empty_coord[0], empty_coord[1], self.player if turn else self.opponent)
turn = not turn
def mc_update_scores(self):
"""
Updates move scores based on the current state of the board
"""
if self.board.is_won() == False:
# do nothing if game was a draw
return
else:
winning_player = self.board.is_won()
machine_won = True if winning_player == self.identifier else False
# if the machine won, then each square that the machine played in recieves a positive score
# and each square it did not play in recieves a negative score. Empty squares recieve 0.
# if it didn't win, then the opposite happens.
if machine_won:
for horizontal in self.board.horizontals:
for coord in horizontal:
identifier = self.board.get_square(coord[0], coord[1])
if identifier == self.identifier:
self.scores[coord[1]][coord[0]] += 1
elif identifier == 0:
continue
else:
self.scores[coord[1]][coord[0]] -= 1
else:
for horizontal in self.board.horizontals:
for coord in horizontal:
identifier = self.board.get_square(coord[0], coord[1])
if identifier == self.identifier:
self.scores[coord[1]][coord[0]] -= 1
elif identifier == 0:
continue
else:
self.scores[coord[1]][coord[0]] += 1
# If the play was already there when game started, reset score to 0
for y_coord, row in enumerate(self.scores[:]):
for x_coord, score in enumerate(row):
if self.original_board.get_square(x_coord, y_coord) != 0:
self.scores[y_coord][x_coord] = 0
def get_best_move(self):
"""
Returns a random best move using the scores for each one.
"""
current_best = None
best_coords = []
# getting best score
for y_coord, row in enumerate(self.scores):
for x_coord, score in enumerate(row):
if current_best is None:
current_best = score
else:
if score > current_best:
current_best = score
# getting all coordinates that have the 'best score'
for y in xrange(len(self.scores)):
for x in xrange(len(self.scores[0])):
score = self.scores[y][x]
if score == current_best:
best_coords.append((x, y))
# if current_best (in the end) is 0, it means that the move must result in a tie.
# In that case, simply play the last empty coordinate
if current_best == 0:
last = self.original_board.random_empty_square()
return (last[0], last[1])
# returning random best move
return random.choice(best_coords)
def move(self):
for i in xrange(self.trials):
# running one trial and updating board scores
self.mc_trial()
self.mc_update_scores()
# resetting board for next trial
self.board = copy.deepcopy(self.original_board)
return self.get_best_move()
|
ce333be3e5bc1b3766868bf6fd5f526ac0f0cc9a | jrluecke95/python-102 | /long_vowels.py | 773 | 4.34375 | 4 | string = "good"
vowels = ["a", "e", "i", "o", "u"]
empty_string = ""
#for loop that runs through each index in string first
# then checks to see if each string[index] is in the list vowels
# after that - setting the letter to be replaced to string[index of letter] helped simplify things in end expression
# diong the same for the "range" of double vowels - use 2 because +1 doesn't do anything doofus
# and then setting empty string = result of replacement
for i in range(len(string)):
if string[i] in vowels:
if string[i] == string[i+1]:
letter = string[i]
double = string[i:i+2]
empty_string = string.replace(double, letter*5)
print(empty_string)
#loop through string
# if you encouter vowel check if next one is vowel |
beda147914ec1d253603ac64e8ac21b676a5e005 | baiyang20201207/baiyang20201207.github.io | /python学习/song/class/thefirstday/lesson02.py | 1,595 | 3.90625 | 4 | #conding=utf-8
#@time 2020/12/29 14:02
#@AUTHOR sx
'''
运算符:
1.算术运算符:+,-,*,/,//,%,**
2.关系运算符:>,>=,<,<=,==,!=
3.逻辑运算符:not,and ,or
4.赋值运算符:+=,-=,*=,/=,//=,%=,**=
5.成员运算符:in ,not in
'''
a=10
b=3
print(a/b,a//b,a%b,a**b)
print(not(1+2>7),8==8)
a+=b #a=a+b
print(a,b)
t=(1,2,3,4)
print(5 not in t)
'''
类型 :
1.数据类型:整型int(),浮点型float(),布尔型bool(),复数型complex()
2.字符串类型:str() 单引号,双引号,三引号
'''
print(complex(2,4))
x=1.79
x=int(x)
x=[]
x=bool(x)
print(x)
# y=int(input("请输入内容:")) #input语句输入的内容类型为字符,如果有使用其他类型必须强制转换
# print(type(y))
s='hello world'
s1="study python"
print(s,s1)
s2="""
《白雪歌送武判官归京》【唐】岑参
北风卷地白草折,胡天八月即飞雪.
忽如一夜春风来,千树万树梨花开.
散入珠帘湿罗幕,狐裘不暖锦衾薄.
将军角弓不得控,都护铁衣冷犹著.
瀚海阑干百丈冰,愁云惨淡万里凝.
中军置酒饮归客,胡琴琵琶与羌笛.
纷纷暮雪下辕门,风掣红旗冻不翻.
轮台东门送君去,去时雪满天山路.
山回路转不见君,雪上空留马行
"""
print(s2)
s3='他说:"明天请我们吃饭!"'
print(s3)
#字符串单个元素的取值方法:
#字符串名[index]
print(s[6],s[-5])
print(s[10],s[-1])
#多个字符元素的取值方法:
#字符串[start:end:step]
print(s[6:11],s[-6::],s[-6:-2])
print(s[::-1])
s[::]
|
8eabe2107ba628a815833ff7fb98c879243e4f8b | Shreyans145/N_PUZZLE_AI | /First Choice/3.FirstChoiceHillClimbing.py | 2,818 | 3.703125 | 4 | import time
import random
tag = False
def sol_RandomHillClimbing(arr):
x = 500000
c = 0
while True:
distance = get_Manhattan_Distance(arr)
if distance == 0:
return arr
arr = Random_HillClimbing(arr)
c += 1
if(c >= x):
global tag
tag = True
return arr
def Random_HillClimbing(arr):
for i in range(len(arr)):
if arr[i] == 0:
break
while True:
x = random.randint(0,4)
if x == 0:
if i >= 3:
up_Board = list(arr)
up_Board[i] = arr[i-3]
up_Board[i-3] = 0
return up_Board
elif x == 1:
if i < 6:
down_Board = list(arr)
down_Board[i] = arr[i+3]
down_Board[i+3] = 0
return down_Board
elif x == 2:
if i%3 != 0:
left_Board = list(arr)
left_Board[i] = arr[i-1]
left_Board[i-1] = 0
return left_Board
else:
if (i+1)%3 != 0:
right_Board = list(arr)
right_Board[i] = arr[i+1]
right_Board[i+1] = 0
return right_Board
return arr
def get_Manhattan_Distance(arr):
val = 0
for i in range(len(arr)):
val += abs(i/3 - arr[i]/3) + abs(i%3 - arr[i]%3)
return val
def main():
name = "N_Puzzle_RandomHillClimbing"
initial_Time = time.process_time()
success_Case = 0
total_Case = 0
res = name + " result:\n\n"
with open("N_Puzzle_Test.txt", "r") as y:
for line in y:
print("case: ", total_Case)
global tag
tag = False
total_Case += 1
arr = list()
for c in line.split():
arr.append(int(c))
arr = sol_RandomHillClimbing(arr)
if tag:
res += "Failed!"
else:
success_Case += 1
for c in range(len(arr)):
res += str(arr[c]) + " "
res += "\n"
finsh_Time = time.process_time()
res += "\nTotal time: " + str(finsh_Time - initial_Time) + '\n'
res += "Total case number: " + str(total_Case) + ", Success case number: " + str(success_Case) + '\n'
res += "Success rate: " + str(success_Case / float(total_Case)) + '\n'
print(res)
f = open(name + '.txt', 'w')
f.write(res)
f.close()
if __name__ == '__main__':
main() |
c4fc2e3f8a1fa3312bb33054d89a87ebd74b7901 | larsgimse/NodeMCU | /micropython/math_game.py | 536 | 3.875 | 4 | import random
import time
from machine import Pin
led_green = Pin(14, Pin.OUT)
led_red = Pin(12, Pin.OUT)
while True:
led_green.off()
led_red.off()
number_1 = random.randint(2,12)
number_2 = random.randint(2,12)
answer = int(input("What is " + str(number_1) + " * " + str(number_2) + "? "))
if answer == number_1 * number_2:
print("Hurray!")
led_green.on()
time.sleep(2)
else:
print("Wrong! Answer is " + str(number_1 * number_2))
led_red.on()
time.sleep(2)
|
a26dfcfb34a20b6340fff0ce648100025ca8a352 | estela-ramirez/PythonCourses | /LAB 3 Q1.py | 1,340 | 4.125 | 4 | '''
ICS 31 Lab 3 Question 1
Driver: UCI_ID: 18108714 Name: Estela Ramirez Ramirez
Navigator: UCI_ID: 69329009 Name: Karina Regalo
'''
def main():
i = get_n_of_people()
ns, ag = getsAgesAndNames(i)
maxb, index = maxAge(ag)
minb, index2 = minAge(ag)
s = sumAge(ag)
printOldestYoungestAverage(index,index2,s,i,ns,ag)
def get_n_of_people():
return int(input("Number of people: "))
def getsAgesAndNames(number_of_people)->list:
a =[]
b =[]
for x in range(1, number_of_people+1):
name = input("What is Person #{}'s name: ". format(x))
a.append(name)
age = int(input("What is {}'s age? ". format(name)))
b.append(age)
return a, b
def maxAge(b:list)->int:
maxb = 0
for x in b:
if x >= maxb:
maxb = x
index = (b.index(maxb))
return maxb, index
def minAge(b:list)->int:
minb = 100000000000
for x in b:
if x <= minb:
minb = x
index = (b.index(minb))
return minb, index
def sumAge(b:list)->int:
for x in (b):
sumb = sum(b)
def printOldestYoungestAverage(ma,mia,ta,np,ns,ag):
print( ns[mia], "is the youngest and is", ag[mia], "years old")
print( ns[ma], "is the oldest and is ", ag[ma], "years old")
print("Average Age is:",(sum(ag)/len(ag)))
main()
|
24dbbcb5331116ebde11e87f87efb85a7e7ae55b | adamilyas/complex-networks | /week6/colorbar_help.py | 1,664 | 3.59375 | 4 | from matplotlib import pyplot as plt
import matplotlib as mpl
import numpy as np
"""
This file provides the function for plotting the colorbar in case plt.colorbar() fails to
output any colorbar at all.
In your script file, import this module with
import colorbar_help as ch
import networkx as nx
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
# ....
# do your fancy network stuff
# ....
nx.draw(your_network, node_color=your_node_values, cmap='OrRd')
ch.add_colorbar(your_node_values)
#plt.show()
"""
def add_colorbar(cvalues, cmap='OrRd', cb_ax=None):
"""
Add colorbar for old versions of matplotlib.
Use the same cmap as you used for drawing networkx!
Parameters
----------
cvalues : list-like
List of values (or e.g. numpy array) that are color
mapped. In this case thse values should correspond to
the node-wise values of the
cmap : matplotlib colormap name, optional
cb_ax : matplotlib axis object
an axis object where to put the axis
not required for basic usage!
"""
eps = np.maximum(0.0000000001, np.min(cvalues)/1000.)
vmin = np.min(cvalues) - eps
vmax = np.max(cvalues)
norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
scm = mpl.cm.ScalarMappable(norm, cmap)
scm.set_array(cvalues)
if cb_ax is None:
plt.colorbar(scm)
else:
try:
plt.colorbar(cax=cb_ax)
except:
mpl.colorbar.ColorbarBase(cb_ax,
cmap=cmap,
norm=norm,
orientation='vertical')
|
ad4273b2eeaa6f681f954a71474046390c217c01 | HenriqueSoares28/Python-EX | /ex052.py | 343 | 3.8125 | 4 | num = int((input('Digite um número: ')))
tot = 0
for c in range(1, num +1):
if num % c == 0:
print('\033[34m', end='')
tot += 1
else:
print('\033[m', end='')
print(f'{c} ', end='')
print('\033[m')
if tot == 2:
print('O número escolhido é primo!')
else:
print('O número escolhido não é primo!') |
d03967c7f20ce1f930d234cc8f7eda298358e3e5 | ashwin-5g/LPTHW | /ex12.py | 357 | 4.03125 | 4 | age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
weight = raw_input("How much do you weigh? ")
print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
x = raw_input("Enter value for x: ")
y = raw_input("Enter value for y: ")
sum = int(x) + int(y)
print "The sum of the two input numbers is: %d" % sum
print
|
bd8b4fa4480bc55fbfd635ea8f34d6a00e641460 | nemmiz/aoc2016 | /python/02.py | 1,100 | 3.515625 | 4 | #!/usr/bin/python3
def do_moves(lines, start, possible_positions):
x, y = start
for line in lines:
for c in line:
if c == 'U':
nx, ny = x, y-1
elif c == 'D':
nx, ny = x, y+1
elif c == 'L':
nx, ny = x-1, y
elif c == 'R':
nx, ny = x+1, y
if (nx, ny) in possible_positions:
x = nx
y = ny
print(possible_positions[(x,y)], end='')
print()
with open('../input/02.txt') as f:
lines = [line.strip() for line in f.readlines()]
keypad1 = {
(0, 0): 1, (1, 0): 2, (2, 0): 3,
(0, 1): 4, (1, 1): 5, (2, 1): 6,
(0, 2): 7, (1, 2): 8, (2, 2): 9,
}
do_moves(lines, (1, 1), keypad1)
keypad2 = {
(2, 0): '1',
(1, 1): '2', (2, 1): '3', (3, 1): '4',
(0, 2): '5', (1, 2): '6', (2, 2): '7', (3, 2): '8', (4, 2): '9',
(1, 3): 'A', (2, 3): 'B', (3, 3): 'C',
(2, 4): 'D',
}
do_moves(lines, (2, 2), keypad2)
|
e1ba530b1798fd1be9a3735362b487bb644df82b | tannerbender/E05a-Animation | /main2.py | 4,646 | 4.34375 | 4 | #Copy the contents from http://arcade.academy/examples/move_keyboard.html#move-keyboard and see if you can figure out what is going on. Add comments to any uncommented lines
"""
This simple animation example shows how to move an item with the keyboard.
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.move_keyboard
"""
import arcade
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
SCREEN_TITLE = "Move Keyboard Example"
MOVEMENT_SPEED = 3
class Ball:
def __init__(self, position_x, position_y, change_x, change_y, radius, color):
# Take the parameters of the init function above, and create instance variables out of them.
self.position_x = position_x #creating x variable position
self.position_y = position_y #creating y variable position
self.change_x = change_x #creating the variable of the x change
self.change_y = change_y #creating the variable of the y change
self.radius = radius #radius variable of the ball
self.color = color #color variable of the ball
def draw(self): #drawing itself
""" Draw the balls with the instance variables we have. """
arcade.draw_circle_filled(self.position_x, self.position_y, self.radius, self.color) # draw circle with variables
def update(self):
# Move the ball
self.position_y += self.change_y # variable y is equal to itself + whatever the change in y is
self.position_x += self.change_x # variable x is equal to istelf + whatever the change in x is
# See if the ball hit the edge of the screen. If so, change direction
if self.position_x < self.radius: # center of circle is not touching left boundary
self.position_x = self.radius # radius of circle is the distance of the center of the circle to the boundary
if self.position_x > SCREEN_WIDTH - self.radius: # if center of circle is greater than screen width, subtract the radius
self.position_x = SCREEN_WIDTH - self.radius
if self.position_y < self.radius: # center of circle is not touching top and bottom boundaries
self.position_y = self.radius # radius of circle is the distance from the center of the circle to the boundaries of the top and bottom parts of the screen
if self.position_y > SCREEN_HEIGHT - self.radius: # if center of circle is greater than screen height than subract the radius of the circle and show location
self.position_y = SCREEN_HEIGHT - self.radius
class MyGame(arcade.Window):
def __init__(self, width, height, title):
# Call the parent class's init function
super().__init__(width, height, title)
# Make the mouse disappear when it is over the window.
# So we just see our object, not the pointer.
self.set_mouse_visible(False) #if visible cant be true
arcade.set_background_color(arcade.color.ASH_GREY) # set background color of game to grey
# Create our ball
self.ball = Ball(50, 50, 0, 0, 15, arcade.color.AUBURN) #creating the ball
def on_draw(self):
""" Called whenever we need to draw the window. """
arcade.start_render() #rendering game
self.ball.draw() #draw ball
def update(self, delta_time): #update self
self.ball.update() #update location of ball
def on_key_press(self, key, modifiers):
""" Called whenever the user presses a key. """
if key == arcade.key.LEFT: # if key on keyboard is left
self.ball.change_x = -MOVEMENT_SPEED # move ball towards left
elif key == arcade.key.RIGHT: # if not left then right
self.ball.change_x = MOVEMENT_SPEED # move ball to the right
elif key == arcade.key.UP: # if up key is pressed
self.ball.change_y = MOVEMENT_SPEED # move location up on screen
elif key == arcade.key.DOWN: # else must be down
self.ball.change_y = -MOVEMENT_SPEED # move location down on screen
def on_key_release(self, key, modifiers): # defining key release
""" Called whenever a user releases a key. """
if key == arcade.key.LEFT or key == arcade.key.RIGHT: # once either left or right key are released
self.ball.change_x = 0 # ball position will not change
elif key == arcade.key.UP or key == arcade.key.DOWN: # once either up or down key are released
self.ball.change_y = 0 # ball position won't change
def main():
print("my game")
window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
arcade.run()
if __name__ == "__main__":
main() |
aaa847bf6c9c984cf8877200790bd729d5f49c92 | xsong15/codingbat | /list-1/sum2.py | 474 | 4.09375 | 4 | def sum2(nums):
"""
Given an array of ints, return the sum of the first 2
elements in the array. If the array length is less
than 2, just sum up the elements that exist,
returning 0 if the array is length 0
"""
# if sum(nums) < 2:
# return sum(nums)
# elif len(nums) == 0:
# return 0
return sum(nums[:2])
print(sum2([1, 2, 3])) #→ 3
print(sum2([1, 1])) #→ 2
print(sum2([1, 1, 1, 1])) #→ 2
print(sum2([0, 0]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.