blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
d7a610da41df1c2d0f710db3336ea59dd5cecfcd | rafaelperazzo/programacao-web | /moodledata/vpl_data/13/usersdata/75/4939/submittedfiles/flipper.py | 295 | 3.96875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
#Entrada
P= input ('Digite a posição de P:')
R= input ('Digite a posição de R:')
#Processamento e Saida:
if (P==R) and (R==1):
print ('A')
if (P>R):
print ('B')
if (P<R) or ((P==R) and (R==0)):
print ('C')
|
e6a52c25ec837bdf427f25050ebef742cacae46e | NurseQ/Benchmark-of-Algorithms | /algo.py | 8,376 | 4.125 | 4 | # import packages to be used for this program
from random import randint
from statistics import mean
import time
# Selection sort algorithm, adapted from https://www.pythoncentral.io/selection-sort-implementation-guide/
def selectionSort(arr):
for i in range(len(arr)):
# Find the element with lowest value
minPosition = i
for j in range(i+1, len(arr)):
if arr[minPosition] > arr[j]:
minPosition = j
# Swap the element with lowest value at the beginning
temp = arr[i]
arr[i] = arr[minPosition]
arr[minPosition] = temp
return arr
# Quick Sort Algorithm
# adapted from https://stackoverflow.com/questions/18262306/quicksort-with-python/27461889#27461889
def qsort(arr):
less = []
equal = []
greater = []
if len(arr) > 1:
pivot = arr[0]
for x in arr:
if x < pivot:
less.append(x)
elif x == pivot:
equal.append(x)
elif x > pivot:
greater.append(x)
# join the lists together
return qsort(less)+equal+qsort(greater)
# Note that you want equal ^^^^^ not pivot
else: # when you only have one element in your array, just return the array.
return arr
def bucket_sort(arr):
largest = max(arr)
length = len(arr)
size = largest/length
buckets = [[] for _ in range(length)]
for i in range(length):
j = int(arr[i]/size)
if j != length:
buckets[j].append(arr[i])
else:
buckets[length - 1].append(arr[i])
for i in range(length):
insertion_sort(buckets[i])
result = []
for i in range(length):
result = result + buckets[i]
return result
def insertion_sort(arr):
for i in range(1, len(arr)):
temp = arr[i]
j = i - 1
while (j >= 0 and temp < arr[j]):
arr[j + 1] = arr[j]
j = j - 1
arr[j + 1] = temp
# Merge Sort Algorithm
# Adapted from https://www.simplifiedpython.net/merge-sort-python/
def merge(left, right):
result = [] # final result array, that is an empty array
#create two indices and initialize with 0
i,j = 0,0
# Till this condition is true, keep on appending elements into resultant array
while i<len(left) and j<len(right):
if left[i] <= right[j]:
result.append(left[i]) #append ith element of left into resultant array
i+=1
else:
result.append(right[j]) #append jth element of right into resultant array
j+=1
# it is basically specifies that if any element is remaining in the left array from -
# ith to the last index so that it should appended into the resultant array. And similar -
# to the right array.
result += left[i:]
result += right[j:]
return result
# Definition for merge sort
# this takes an input list
def mergesort(lst):
if(len(lst)<= 1): # this means that the list is already sorted.
return lst
mid = int(len(lst)/2)
# left array will be mergesort applied over the list from starting index
# till the mid index
left = mergesort(lst[:mid])
# right array will be mergesort applied recursively over the list from mid index
# till the last index
right = mergesort(lst[mid:])
return merge(left,right) # finally return merge over left and right
# Shell Sort Algoritm
# Adapted from https://interactivepython.org/runestone/static/pythonds/SortSearch/TheShellSort.html
def shellSort(arr):
sublistcount = len(arr)//2
while sublistcount > 0:
for startposition in range(sublistcount):
gapInsertionSort(arr,startposition,sublistcount)
sublistcount = sublistcount // 2
# this uses the insertion sort algorithm to sort the gap sequence
def gapInsertionSort(arr,start,gap):
for i in range(start+gap,len(arr),gap):
currentvalue = arr[i]
position = i
while position>=gap and arr[position-gap]>currentvalue:
arr[position]=arr[position-gap]
position = position-gap
arr[position]=currentvalue
# this function takes one parameter to produce an array of n amount of random numbers
def random_array(n):
aray = []
for i in range(0, n, 1):
aray.append(randint(0, 10000))
return aray
num_runs = 10
elements = [100, 250, 500, 750, 1000, 1250, 2500, 3750, 5000, 6250, 7500, 8750, 10000]
# this function takes the first element of array elements and passess it to the next for loop where it calculates
# the mean of 10 runs of the function selectionSort.
def selrunTime():
times = []
for i in elements:
arr = random_array(i)
selresults = []
for r in range(num_runs):
start_time = time.time()
selectionSort(arr)
end_time = time.time()
time_elapsed = end_time - start_time
selresults.append(time_elapsed)
s = round(mean(selresults),3)
times.append(s)
return times
# this function takes the first element of array elements and passess it to the next for loop where it calculates
# the mean of 10 runs of the function qruntime.
def qrunTime():
qtimes = []
for i in elements:
arr = random_array(i)
qresults = []
for r in range(num_runs):
start_time = time.time()
qsort(arr)
end_time = time.time()
time_elapsed = end_time - start_time
qresults.append(time_elapsed)
q = round(mean(qresults),3)
qtimes.append(q)
return qtimes
# this function takes the first element of array elements and passess it to the next for loop where it calculates
# the mean of 10 runs of the function bucketrunTime.
def bucketrunTime():
btimes = []
for i in elements:
arr = random_array(i)
bucketresults = []
for r in range(num_runs):
start_time = time.time()
qsort(arr)
end_time = time.time()
time_elapsed = end_time - start_time
bucketresults.append(time_elapsed)
b = round(mean(bucketresults),3)
btimes.append(b)
return btimes
# this function takes the first element of array elements and passess it to the next for loop where it calculates
# the mean of 10 runs of the function mergerunTime.
def mergerunTime():
mtimes = []
for i in elements:
arr = random_array(i)
mergeresults = []
for r in range(num_runs):
start_time = time.time()
qsort(arr)
end_time = time.time()
time_elapsed = end_time - start_time
mergeresults.append(time_elapsed)
m = round(mean(mergeresults),3)
mtimes.append(m)
return mtimes
# this function takes the first element of array elements and passess it to the next for loop where it calculates
# the mean of 10 runs of the function shellrunTime.
def shellrunTime():
stimes = []
for i in elements:
arr = random_array(i)
shellresults = []
for r in range(num_runs):
start_time = time.time()
qsort(arr)
end_time = time.time()
time_elapsed = end_time - start_time
shellresults.append(time_elapsed)
s = round(mean(shellresults),3)
stimes.append(s)
return stimes
# import packages needed
import numpy as np
import pandas as pd
# the main function for the program
def main():
# converts the output to an numpy array
a = np.array(selrunTime())
b = np.array(qrunTime())
c = np.array(bucketrunTime())
d = np.array(mergerunTime())
e = np.array(shellrunTime())
# creates a 2D array out of individual arrays
result = np.column_stack((a,b,c,d,e)).T
algoList = ["Selection Sort", "Quick Sort", "Bucket Sort", "Merge Sort", "Shell Sort"]
# uses pandas to format the output (overkill).
x = pd.DataFrame(result, algoList, elements)
# send copy to csv file for data wrangling in other software
#x.to_csv('file1.csv')
print(x.to_string())
if __name__ =="__main__":
main()
|
56d009a51f872b2d974c4155b3ae9e55580968f6 | pla0599/adm1n | /game_v1.0.0 | 878 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2019-2020 LX
# All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
import random
answer = random.randint(1,10)
print("==========Play a game==========")
shuru = input("Input a number between 1 to 10 and press Enter:")
Num = int(shuru)
if Num == answer:
print("1 shoot 1 kill, Nice dude!")
else:
while Num != answer:
if Num > answer:
shuru = input("Wrong, input a smaller number:")
else:
shuru = input("Wrong, input a bigger number:")
Num = int(shuru)
print("Finally guessed right U stupid motherfucker")
|
0af6b99e2a016399b79eae501b543c6ea136f4a0 | mathias-madsen/information_theory | /edit_distance.py | 4,425 | 4.125 | 4 | import numpy as np
def edit_distance_analysis(word1, word2):
"""" Obtained details on how to convert one word into the other.
Notes:
¯¯¯¯¯¯
The edit commands considered are:
- correct transmission of one letter (cost=0)
- spurious deletion from the input stream (cost=1)
- spurious insertion into the output stream (cost=1)
- corrupted transmission of one letter (cost=1)
- transposed transmission of two letters (cost=1)
Parameters:
¯¯¯¯¯¯¯¯¯¯¯
word1 : str
The first word, nominally considered the observed "input stream."
word1 : str
The second word, nominally considered the observed "output stream."
Returns:
¯¯¯¯¯¯¯¯
distance matrix : array of shape (len(word1) + 1, len(word2) + 1)
A matrix of edit distances recording in entry (i, j) the smallest
number of edits necessary to convert the string word1[:i] into
the string word2[:j].
commands : list of strings
An minimal and ordered list of commands that, when executed, will
convert word1 into word2. When there are several optimal programs
that achieve this goal, an arbitrary selection is made among them.
"""
n = len(word1) + 1
m = len(word2) + 1
dist = np.zeros((n, m), dtype=np.uint64)
cmds = dict()
dist[0, 0] = 0
cmds[0, 0] = []
for i in range(1, n):
dist[i, 0] = i # i deletions
cmds[i, 0] = cmds[i - 1, 0] + ["delete %s from input" % word1[i - 1]]
for j in range(1, m):
dist[0, j] = j # j insertions
cmds[0, j] = cmds[0, j - 1] + ["insert %s into output" % word2[j - 1]]
for i in range(1, n):
for j in range(1, m):
deletion_cost = dist[i - 1, j] + 1
insertion_cost = dist[i, j - 1] + 1
substitution_increment = 0 if word1[i - 1] == word2[j - 1] else 1
substitution_cost = dist[i - 1, j - 1] + substitution_increment
possible_costs = [deletion_cost, insertion_cost, substitution_cost]
if i > 1 and j > 1:
transposition_cost = dist[i - 2, j - 2] + 1
pair1 = word1[i - 2 : i]
pair2 = word2[i - 2 : i]
if pair1 == pair2[::-1]:
possible_costs.append(transposition_cost)
winner = np.argmin(possible_costs)
dist[i, j] = possible_costs[winner]
if winner == 0:
command = "delete %s from input" % word1[i - 1]
cmds[i, j] = cmds[i - 1, j] + [command]
elif winner == 1:
command = "insert %s into output" % word2[j - 1]
cmds[i, j] = cmds[i, j - 1] + [command]
elif winner == 2 and substitution_increment == 0:
command = "transmit %s" % word1[i - 1]
cmds[i, j] = cmds[i - 1, j - 1] + [command]
elif winner == 2 and substitution_increment == 1:
command = "corrupt %s into %s" % (word1[i - 1], word2[j - 1])
cmds[i, j] = cmds[i - 1, j - 1] + [command]
elif winner == 3:
command = "transpose %s" % (word1[i - 2 : i])
cmds[i, j] = cmds[i - 2, j - 2] + [command]
else:
raise Exception("Unexpected argmin: %s" % winner)
return dist, cmds[n - 1, m - 1]
def edit_distance(word1, word2):
""" Compute the number of edits separating the two words.
Notes:
¯¯¯¯¯¯
The edit commands considered are:
- correct transmission of one letter (cost=0)
- spurious deletion from the input stream (cost=1)
- spurious insertion into the output stream (cost=1)
- corrupted transmission of one letter (cost=1)
- transposed transmission of two letters (cost=1)
Returns:
¯¯¯¯¯¯¯¯
distance : uint64
The smallest number of edits necessary to convert word1 into word2.
"""
matrix, commands = edit_distance_analysis(word1, word2)
return matrix[-1, -1]
if __name__ == "__main__":
testwords = "AB BA CATS BATS STAB TABS".split(" ")
testwords.append("")
testwords.append("A")
for word1 in testwords:
for word2 in testwords:
distance, recipe = edit_distance_analysis(word1, word2)
print((word1, word2), distance[-1, -1])
print(recipe)
print()
|
e7145ecfd701a38e0437b1c9e323d78bc324745e | Vitoria0/Activities-Python | /Cap-2/043-IMC.py | 1,036 | 3.765625 | 4 | peso = float(input('Qual é o seu peso? (Kg) '))
altura = float(input('Qual é a sua altura? (m) '))
imc = peso / (altura ** 2)
print('O IMC dessa pessoa é de {:.1f}'.format(imc))
if imc < 17:
print('Muito abaixo do peso')
print('O que pode acontecer?\nQueda de cabelo, infertilidade, ausência menstrual')
elif imc < 18.5:
print('Abaixo do peso')
print('O que pode acontecer?\nFadiga, stress, ansiedade')
elif imc < 25:
print('Peso normal')
print('O que pode acontecer?\nMenor risco de doenças cardíacas e vasculares')
elif imc < 30:
print('Acima do peso')
print('O que pode acontecer?\nFadiga, má circulação, varizes')
elif imc < 35:
print('Obesidade Grau I')
print('O que pode acontecer?\nDiabetes, angina, infarto, aterosclerose')
elif imc <= 40:
print('Obesidade Grau II')
print('O que pode acontecer?\nApneia do sono, falta de ar')
else:
print('Obesidade Grau III')
print('O que pode acontecer?\nRefluxo, dificuldade para se mover, escaras, diabetes, infarto, AVC')
|
3204a8a5ce13fa08c44477348a803626a591a80e | ashwynh21/rnn | /declarations/account.py | 3,812 | 3.828125 | 4 | """
We define this account class because we require a defined sort of score board for our agent that will allow it to
gauge quantitatively its performance.
"""
from typing import Dict
from declarations.action import Action
from declarations.position import Position
from declarations.result import Result
from declarations.state import State
class Account(object):
balance: float
risk: float
ledger: Dict[str, Result]
positions: Dict[str, Position]
def __init__(self, balance):
self.balance = balance
self.positions = {}
self.ledger = {}
self.risk = 0.02
"""
Since our definition here is purely score boarding we need functions to update the properties that we have defined.
So the account will also have a rule for the way it handles positions because right now our algorithm for closing
a position is not yet well defined so we will for now opt with defining a structured closing strategy.
"""
def record(self, k: str, v: Position):
"""
A function that will allow to open a position...
:return:
"""
self.balance = v.balance
self.positions[k] = v
def archive(self, k, v: Result):
"""
A function that will allow us to close one of the positions that we have in the positions property that we
have defined.
:return:
"""
self.balance = self.balance + v.profit
del self.positions[k]
self.ledger[k] = v
"""
Now we define a function that will get the closable positions as a dictionary
We are going to redesign our closing function to better incorporate other factors of the position, the price of the
market and other factors that would be relevant to the position.
"""
def closable(self, state: State, action: Action) -> Dict[str, Position]:
"""
We should only need the state of the environment since all the values to evaluate the validity of the
position are based on computations between the two properties.
:param action:
:param state:
:return:
"""
data = {}
for k, v in self.positions.items():
if action.action != 2:
v.bias.pop(0)
v.bias.append(action.action)
# so once we have the profit we need to get the next action from the agent, so we add it to the args list
# so if the position is in the same direction as the action we hold otherwise we close.
# this decision.
# we add the condition that if the position bias is less than 0, then we close the position.
# len(list(filter(lambda b: b != v.action.action, v.bias))) >= 2 or
close = v.elapsed > 120 or v.stoppedout(state.price()) or v.takeprofit(state.price())
if close:
data[k] = v
else:
v.elapsed = v.elapsed + 1
return data
def reset(self, balance: float):
self.balance = balance
"""
We are going to need a function to calculate the risk that the account can manage before opening a position.
"""
def stoploss(self) -> float:
return self.balance * self.risk
"""
We define a function that calculates the volume of the position that we are going to create by using the account
risk parameter.
"""
def getvolume(self, price: float, stop: float, pair: str):
# if the pair is a JPY major or minor then our multiplier will be:
multiplier = 0
if 'JPY' not in pair:
multiplier = 0.0001
else:
multiplier = 0.01
risk = self.stoploss()
loss = abs((price - stop) / multiplier)
pip = risk / loss
return pip / multiplier
|
eb046f8fc2c260942a28676bb2649b628f19e220 | codpro880/project_euler | /python/problem__18.py | 1,781 | 3.8125 | 4 | # Just copy/pasta-ed from project euler
problem_triangle_str = """75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
"""
def sum_up_from_bottom(triangle_str):
tri_arr = parse_triangle_into_array(triangle_str)
while len(tri_arr) > 1:
tri_arr = sum_bottom_row(tri_arr)
return tri_arr[0]
def sum_bottom_row(tri_arr):
bottom_row = tri_arr[-1]
upper_row = tri_arr[-2]
result_row = []
for first, second, upper_row_item in zip(bottom_row, bottom_row[1:], upper_row):
max_ = max(first, second)
result_row.append(max_ + upper_row_item)
tri_arr[-2] = result_row
tri_arr = tri_arr[:-1]
return tri_arr
def parse_triangle_into_array(triangle_str):
rows_str = triangle_str.split("\n")
triangle_arr = [[int(x) for x in row.split(' ') if x] for row in rows_str]
if triangle_arr[-1]:
return triangle_arr
else:
return triangle_arr[:-1]
if __name__ == "__main__":
""" Some quick tests...TODO: move to test suite. """
triangle_str = """3
7 4
2 4 6
8 5 9 3
"""
tri_arr = parse_triangle_into_array(triangle_str)
assert tri_arr[0] == [3]
assert tri_arr[1] == [7, 4]
assert tri_arr[2] == [2, 4, 6]
assert tri_arr[3] == [8, 5, 9, 3]
bottom_row_summed = sum_bottom_row(tri_arr)
assert bottom_row_summed[-1] == [8 + 2, 9 + 4, 9 + 6]
result = sum_up_from_bottom(triangle_str)
assert result[0] == 23
print(sum_up_from_bottom(problem_triangle_str))
|
60b961524aa20fd75cbf040027e9828256987df0 | acarbonaro/project-euler | /euler008.py | 2,262 | 3.59375 | 4 | """
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?
"""
from functools import reduce
THOUSAND_DIGITS = int("73167176531330624919225119674426574742355349194934"\
"96983520312774506326239578318016984801869478851843"\
"85861560789112949495459501737958331952853208805511"\
"12540698747158523863050715693290963295227443043557"\
"66896648950445244523161731856403098711121722383113"\
"62229893423380308135336276614282806444486645238749"\
"30358907296290491560440772390713810515859307960866"\
"70172427121883998797908792274921901699720888093776"\
"65727333001053367881220235421809751254540594752243"\
"52584907711670556013604839586446706324415722155397"\
"53697817977846174064955149290862569321978468622482"\
"83972241375657056057490261407972968652414535100474"\
"82166370484403199890008895243450658541227588666881"\
"16427171479924442928230863465674813919123162824586"\
"17866458359124566529476545682848912883142607690042"\
"24219022671055626321111109370544217506941658960408"\
"07198403850962455444362981230987879927244284909188"\
"84580156166097919133875499200524063689912560717606"\
"05886116467109405077541002256983155200055935729725"\
"71636269561882670428252483600823257530420752963450", 10)
def greatest_adjacent_product(target_number, adjacent):
"""
Take a number and the desired number of adjacent digits to test, and return
the largest product of a given sequential group of `adjacent` length digits
"""
target_string = str(target_number)
product = 0
y = 0
for x in range(len(target_string)):
new_product = list_product(list(target_string[x:(x + adjacent)]))
if int(new_product) > int(product):
product = new_product
return product
def list_product(target_list):
return reduce(lambda x, y: int(x) * int(y), target_list)
def test():
return greatest_adjacent_product(THOUSAND_DIGITS, 4)
def solution():
return greatest_adjacent_product(THOUSAND_DIGITS, 13)
if __name__ == '__main__':
print(solution())
|
cbd619e3b5abcebd66ba2f4d28338aad472ae8f2 | guilhermejcmarinho/Praticas_Python_Elson | /02-Estrutura_de_Decisao/06-Maior_de_tres.py | 438 | 4.1875 | 4 | numero01 = int(input('Informe o primeiro numero:'))
numero02 = int(input('Informe o segundo numero:'))
numero03 = int(input('Informe o terceiro numero:'))
if numero01>numero02 and numero01>numero03:
print('Primeiro numero: {} é o maior.'.format(numero01))
elif numero01<numero02 and numero02>numero03:
print('Primeiro numero: {} é o maior.'.format(numero02))
else:
print('Primeiro numero: {} é o maior.'.format(numero03))
|
a0695231f854782e55a3fded51bfa06b1ec15407 | sanyam-dev/EnC0de-DeCo83 | /Binary_En_De-Code.py | 1,132 | 4.09375 | 4 | """
Author : Sanyam Jha
Code : Play around with your friends OR store your secrets with this Binary Encoder - Decoder
"""
# This Code Converts String to Binary
def str_to_bin(s):
res_str = ""
for i in range(len(s)):
bin1 = '{0:08b}'.format(ord(s[i]))
res_str = res_str + " " + bin1
return res_str[1:]
# This Code Converts Binary to String
def binary_string(n):
num = 0
count = 0
l = [0, 1]
for _ in range(len(n)):
if int(n[-1]) not in l:
break
elif n[-1] == " ":
return int(0000000)
else:
num += pow(2, count)*int(n[-1])
n = n[:-1]
count += 1
return int(num)
N = input("Convert String to Binary?")
if N == "Y":
s = input("Enter String: ")
res = str_to_bin(s)
print(res)
elif N == "N":
bin_str = input("Enter Binary String:")
l1 = list(map(str, bin_str.split()))
res = []
for i in range(len(l1)):
res.append(chr(binary_string(l1[i])))
res_str = ''
res_str = res_str.join(res)
print(res_str)
else:
print("Run Again and write either 'Y' or 'N'") |
724e4a2fd695d0eaaf845dd8aa23b3e0295ad446 | AmitabhKotha/MyCaptainPython | /FileExtension.py | 487 | 4.125 | 4 | fileEx ={
"py":"python",
"cpp":"c++",
"doc":"Word",
"docx":"Word",
"rtf":"Rich Text Format",
"wpd":"WordPerfect Document",
"pdf":"Portable Document File"
"txt":"text"
}
filename = input("Input the Filename: ")
exten = filename.split(".")
#print(fileEx[exten[-1]])
if exten[-1] in fileEx.keys():
print ("The extension of the file is : " + repr(fileEx[exten[-1]]))
else :
print ("The extension of the file is : " + repr(exten[-1]))
|
f74700bbd58a7f8c62c76bb8bf3c2d50f3d439be | jiechenyi/jyc-record- | /Algorithm/leetcode/81.搜索旋转排序数组II.py | 974 | 3.8125 | 4 | """
81.搜索旋转排序数组II
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] )。
编写一个函数来判断给定的目标值是否存在于数组中。若存在返回 true,否则返回 false。
"""
def search(nums, target):
n = len(nums)
p = n
for i in range(n):
if i>0 and nums[i] < nums[i-1]:
p = i
break
def bs(left,right):
while left<=right:
mid = int(left + (right - left) / 2)
if nums[mid] == target:
return True
if nums[mid] > target:
right = mid-1
else:
left = mid+1
return False
if target == nums[0]:
return True
if target > nums[0]:
return bs(0, p-1)
if target < nums[0]:
return bs(p,n-1)
nums = [1,3]
target = 3
print(search(nums,target)) |
6c684064fe9ed80bea9c4f899150a5e4791d4020 | marcelcosme/URI | /PYTHON/2449(Important)(accepted).py | 443 | 3.578125 | 4 | def soma_dois(numero1, numero2, ideal):
aumenta = ideal - numero1
numero1 += aumenta
numero2 += aumenta
return numero1, numero2, abs(aumenta)
numeros, ideal = map(int, input().split())
x = list(map(int, input().split()))
aumenta_total = 0
for i in range(numeros - 1):
if x[i] != ideal:
x[i], x[i + 1], aumenta_agora = soma_dois(x[i], x[i + 1], ideal)
aumenta_total += aumenta_agora
print(aumenta_total)
|
f85530c2ce7396e6e8dfd519c92553d0cc9136b9 | chrisxue815/leetcode_python | /problems/test_0005_iteration.py | 814 | 3.59375 | 4 | import unittest
import utils
# O(n^2) time. O(1) space. Palindrome.
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
max_lo = 0
max_len = 0
start = 0
while start < n:
lo = start - 1
hi = start + 1
while hi < n and s[hi] == s[hi - 1]:
hi += 1
start = hi
while lo >= 0 and hi < n and s[lo] == s[hi]:
lo -= 1
hi += 1
length = hi - lo
if length > max_len:
max_len = length
max_lo = lo
return s[max_lo + 1:max_lo + max_len]
class Test(unittest.TestCase):
def test(self):
utils.test(self, __file__, Solution)
if __name__ == '__main__':
unittest.main()
|
edafb24b836622b8d84c7d1c06b5d7518f30a5f0 | asilvino/tempnotebook | /openkattis/towers.py | 2,375 | 3.5 | 4 | #! /usr/bin/python2
import sys
import math
import StringIO
# import timeit
t1 = "2^1^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2\n"
t2 = "100^10^1^10^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100^100\n"
t3 = "3^5 \n"
t4 = "100\n"
t5 = "20^10^21\n"
sys.stdin = StringIO.StringIO("5\n"+t1+t2+t3+t4+t5+"2\n"+t1+t3)
# sys.stdin = StringIO.StringIO("4\n2^2^2\n3^4\n15\n9^2")#3^4\n15\n9^2
# start = timeit.default_timer()
minVALUE = -sys.maxsize - 1
def logN(val , rep):
valFinal = val
for i in range(rep):
valFinal = (minVALUE) if (valFinal)<=0 else math.log(valFinal)
return valFinal
def treatOnes(stringExp):
isOne= False
newString = []
for number in stringExp.split("^"):
if int(number)==1:
isOne = True
newString.append(number)
if(not isOne):
newString.append(number)
return "^".join(newString)
def letter_cmp(a, b):
a = treatOnes(a)
b = treatOnes(b)
numLog = max([a.count("^"),b.count("^")])
a = a+"^1"*(numLog-a.count("^"))
b = b+"^1"*(numLog-b.count("^"))
a = map(int,a.split("^"))
b = map(int,b.split("^"))
aVal = 0
bVal = 0
for i in range(numLog):
finalA = a[i+1]if len(a)-2==i else 1
finalB = b[i+1]if len(b)-2==i else 1
aVal += (logN(a[i],numLog-i))*(finalA)
bVal += (logN(b[i],numLog-i))*(finalB)
if aVal >= bVal:
return 1
else:
return -1
def letter_cmp2(a, b):
a = treatOnes(a)
b = treatOnes(b)
numLog = max([a.count("^"),b.count("^")])
a = a+"^1"*(numLog-a.count("^"))
b = b+"^1"*(numLog-b.count("^"))
a = map(int,a.split("^"))
b = map(int,b.split("^"))
aVal = 1
bVal = 1
for i in range(numLog+1)[::-1]:
aVal *= (a[i] if 0!=i else math.log(a[i]))
bVal *= (b[i] if 0!=i else math.log(b[i]))
print aVal
print bVal
if aVal >= bVal:
return 1
else:
return -1
print letter_cmp2("3^4", "100")
def main():
count = 0
for line in sys.stdin:
num = int(line)
order = []
for num2 in range(num):
stringPow = sys.stdin.readline()
stringPow = stringPow.strip().replace("\n","")
order.append(stringPow)
order.sort(letter_cmp2)
count += 1
if count>1:
print ""
print 'Case {0:1d}:'.format(count)
print "\n".join([aa for aa in order])
# main()
# stop = timeit.default_timer()
# print stop - start
|
3269098ba37f6f0c515a32fca43cfd902849c008 | archeranimesh/python3_OOPs | /SRC/Chapter_02-Objects-In-Python/point_v03.py | 1,032 | 4.1875 | 4 | import math
class Point:
"Represents a point in two-dimensinal geometric coordinates"
def __init__(self, x=0, y=0):
"""Initialize the postion of a new point. The x and y coordinate
can be specified. If they are not, the point defaults to the origin. """
self.move(x, y)
# Move method
def move(self, x, y):
"""Move the point to a new locationin 2-d space."""
self.x = x
self.y = y
# self is a manditory name.
def reset(self):
"""Reset the point back to the geometric origin: 0, 0"""
self.move(0, 0)
# Calculate distance
def calculate_distance(self, other):
"""Calculate the distance from this point to a second point passed as a parameter.
This function uses the Pythagorean Theorem to calculate the distance between the two points.
The difference is returned as a flot."""
return math.sqrt(((self.x - other.x) ** 2) + ((self.y - other.y) ** 2))
if __name__ == "__main__":
help(Point)
|
59bdc67d23c081190d6d53e79bd6059b30f1c678 | druv022/ML | /main_1/polynomial_regression.py | 1,675 | 3.90625 | 4 | import numpy as np
import matplotlib.pyplot as plt
class polynomial_regression():
"""description of class"""
def __init__(self):
return
def designMatrix(self,x,m):
"""designMatrix(self,x,m)
returns np.asarray(design matrix)
Parameters
-----------------------
x: np array of input
m: highest order of polynomial
Returns
-----------------------
design matrix: np array
Note
-----------------------
The feature matrix or design matrix"""
phi = []
for i in x:
matric = []
for j in range(0, m + 1):
matric.append(np.power(i,j))
phi.append(matric)
return np.asarray(phi)
def fit_polynomial(self,x,t,m,lambda_reg=0):
""" fit_polynomial(self,x,t,m,lambda_reg)
returns w_ml, design_matrix
Parameters
---------------------
x: np array of inputs
t: np array of targets
m: highest order of polynomial
lambda_reg: regularization parameter
Returns
--------------------
w_ml: np array of weights of maximum-likelihood
design_matrix: np 2D array
This methods finds the maximum-likelihood solution of a M-th order polynomial for
some datasetx. The error function minimised wrt w is squared error. Bishop 3.1.1"""
phi = self.designMatrix(x,m)
phi_trans = np.transpose(phi)
a = phi_trans.dot(phi) + lambda_reg*np.identity(phi.shape[1])
b = np.linalg.inv(a)
c = b.dot(phi_trans)
w_ml = c.dot(t)
return w_ml, phi
|
bacecf6e098c2beef963dcdcd0820ca5f8a8b15b | KemalAltwlkany/preference-articulation | /PreferenceArticulation/BenchmarkObjectives.py | 2,591 | 3.953125 | 4 | import math as math
class MOO_Problem:
"""
Class is never to be instantiated in the first place, its just a wrapper to keep all the benchmark functions used
in one nice class, which should be used as static functions.
"""
@staticmethod
def BK1(x):
"""
The BK1 test problem.
In the work of S. Huband, this test problem is labeled "BK1"
From T.T.Binh, U. Korn - "An evolution strategy for the multiobjective optimization"; page 4/6
A simple bi-objective problem
f1(x1, x2) = x1**2 + x2**2
f2(x1, x2) = (x1-5)**2 + (x2-5)**2
Region is defined as x1 € [-5, 10] and x2 € [-5, 10]
Characteristics:
f1: Separable, Unimodal
f2: Separable, Unimodal
Pareto front convex
The Pareto front is defined for x1 € [0, 5] and x2 € [0,5].
This is logical, because the first function is optimized for (0,0) and the second for (5, 5). Any inbetween solutions
due to the linear derivative of the 2 objectives is a trade-off.
R1 - y, R2 - no, R3 - no, R4 - no, R5 - no, R6 - no, R7 - no
:param x: a list of floats containing the solution's vector of decision variables. Basically, x = Sol.x
:return: a 2 element list, containing the evaluated objectives; f1, f2 respectively.
"""
f1 = x[0]**2 + x[1]**2
f2 = (x[0] -5)**2 + (x[1] - 5)**2
return [f1, f2]
@staticmethod
def IM1(x):
"""
The IM1 Test problem.
In the work of S. Huband, this test problem is labeled "IM1"
From: H. Ishibuchi,T. Murata;
"A multi-objective genetic local search algorithm and its application to flowshop scheduling"
Test problem 2:
minimize: f1(x1, x2) 2*sqrt(x1)
f2(x1, x2) = x1*(1-x2) + 5
x1 € [1, 4], x2 € [1, 2]
Interesting problem because of a nonconvex fitness space. Weighted algorithms perform poorly on nonconvex spaces.
f1 - unimodal
f2 - unimodal
R1 - no, R2 - yes, R3 - no, R4 - no, R5 - yes, R6 - yes, R7 - yes
Fitness space is CONCAVE.
Pareto optimal front is obtain for x2=2.
Cited from:
M. Tadahiko, H. Ishibuchi - MOGA: Multi-Objective Genetic Algorithms
:param x: a list of floats containing the solution's vector of decision variables. Basically, x = Sol.x
:return: a 2 element list, containing the evaluated objectives; f1, f2 respectively.
"""
f1 = 2*math.sqrt(x[0])
f2 = x[0]*(1-x[1]) + 5
return [f1, f2]
|
5c29b88507b575a06887bc7998b35a73889f455d | C-milo/georgian-data-programing | /Assignment5/sqllite_exercise.py | 3,606 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 17 19:39:15 2019
@author: Nuthan
"""
'''
Using Python and SQLite (or SQL server if you desire) create a groups database
Create two tables one that contains the names and IDs of your group members and one that contains course names and course IDs
Create a one to many relationship between the two tables that show which students are in each course
'''
import sqlite3
try:
conn = sqlite3.connect('testdata.db')
conn.execute("PRAGMA foreign_keys = ON")
except Error as e:
print(e)
exit()
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS COURSE')
cur.execute('CREATE TABLE COURSE(\
course_id integer PRIMARY KEY,\
course_name text NOT NULL)')
cur.execute('DROP TABLE IF EXISTS STUDENT')
cur.execute('CREATE TABLE STUDENT(\
student_id integer PRIMARY KEY,\
Student_name text NOT NULL,\
course1 integer,\
course2 integer,\
course3 integer,\
course4 integer,\
course5 integer,\
course6 integer,\
FOREIGN KEY (course1)\
REFERENCES course(course_id) ON DELETE SET NULL ON UPDATE CASCADE\
FOREIGN KEY (course2)\
REFERENCES course(course_id) ON DELETE SET NULL ON UPDATE CASCADE\
FOREIGN KEY (course3)\
REFERENCES course(course_id) ON DELETE SET NULL ON UPDATE CASCADE\
FOREIGN KEY (course4)\
REFERENCES course(course_id) ON DELETE SET NULL ON UPDATE CASCADE\
FOREIGN KEY (course5)\
REFERENCES courses(course_id) ON DELETE SET NULL ON UPDATE CASCADE\
FOREIGN KEY (course6)\
REFERENCES course(course_id) ON DELETE SET NULL ON UPDATE CASCADE)')
cur.execute('INSERT INTO course (course_id, course_name) VALUES(?, ?)', (1, 'Data Programming'))
cur.execute('INSERT INTO course (course_id, course_name) VALUES(?, ?)', (2, 'Data Manipulation Techniques'))
cur.execute('INSERT INTO course (course_id, course_name) VALUES(?, ?)', (3, 'Data Systems Architecture'))
cur.execute('INSERT INTO course (course_id, course_name) VALUES(?, ?)', (4, 'Business Process'))
cur.execute('INSERT INTO course (course_id, course_name) VALUES(?, ?)', (5, 'Math for Data Analytics'))
cur.execute('INSERT INTO course (course_id, course_name) VALUES(?, ?)', (6, 'Information Encoding Standards'))
cur.execute('INSERT INTO student (student_id, student_name, course1, course2)\
VALUES (?, ?, ?, ?)', (1, 'Nuthan', 1, 2))
cur.execute('INSERT INTO student (student_id, student_name, course_id, course2)\
VALUES (?, ?, ?, ?)', (2, 'Reyhan', 3, 4))
cur.execute('INSERT INTO student (student_id, student_name, course_id)\
VALUES (?, ?, ?)', (3, 'Camilo', 5))
conn.commit()
cur.execute('SELECT course.name, student.student_id, student.student_name\
FROM student\
INNER JOIN course on course.course_id = student.course1 OR\
course.course_id = student.course2 OR\
course.course_id = student.course3 OR\
course.course_id = student.course4 OR\
course.course_id = student.course5 OR\
course.course_id = student.course6\
ORDER BY course.course_name')
rows = cur.fetchall()
cur.close()
for row in rows:
print(row) |
0b66c8e6e885028304bc52ef56ac630cf6983145 | dundunmao/LeetCode2019 | /104. Maximum Depth of Binary Tree.py | 4,761 | 3.890625 | 4 | # 给定一个二叉树,找出其最大深度。
#
# 二叉树的深度为根节点到最远叶子节点的距离。
#
# 您在真实的面试中是否遇到过这个题? Yes
# 样例
# 给出一棵如下的二叉树:
#
# 1
# / \
# 2 3
# / \
# 4 5
# 这个二叉树的最大深度为3.
# Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param root: The root of binary tree.
@return: An integer
"""
# traverse
def __init__(self):
self.result = 0
def maxDepth(self, root):
self.traverse(root,1)
return self.result
def traverse(self, root, depth):
if root is None:
return
if depth > self.result:
self.result = depth
if root.left:
self.traverse(root.left, depth+1)
if root.right:
self.traverse(root.right, depth+1)
# divide&conquer
def maxDepth(self, root):
# write your code here
if root is None:
return 0
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return max(left,right) + 1
class Solution1:
"""
@param root: The root of binary tree.
@return: An integer
"""
def maxDepth(self, root):
result = [0] #不想用class variable时,就把result变成一个array,只对array里的第一个数做变化,result不能是int,因为into是值传递,array是reference传递.
self.traverse(root, 1, result)
return result[0]
def traverse(self, root, depth, result):
if root is None:
return
result[0] = max(result[0], depth)
if root.left:
self.traverse(root.left, depth + 1, result)
if root.right:
self.traverse(root.right, depth + 1, result)
class Solution3:
"""
@param root: The root of binary tree.
@return: An integer
"""
# traverse
def __init__(self):
self.result = 0
self.path = []
def maxDepth(self, root):
p = []
self.traverse(root,1,p)
return self.result,self.path
def traverse(self, root, depth,p):
if root is None:
return
p.append(root)
if depth > self.result:
self.result = depth
self.path = p[:]
if root.left:
self.traverse(root.left, depth+1, p)
if root.right:
self.traverse(root.right, depth+1, p)
p.pop()
class Solution4:
def maxDepth(self, root):
# write your code here
if root is None:
return 0
return self.helper(root)
def helper(self,root):
if root is None:
return 0,[]
[left,l_path] = self.helper(root.left)
[right,r_path] = self.helper(root.right)
p = [root]
if not p:
print("********")
if left > right:
if l_path:
return [left+1, p+l_path]
else:
return [left, p]
else:
if r_path:
return [right+1, p+r_path]
else:
return [right, p]
import random
class MyTreeNode:
def __init__(self, val):
self.val = val
self.children = [None] * 16
class Solution6:
def maxDepth(self, root: TreeNode) -> int:
new_root = self.copy_tree(root)
if not new_root:
return 0
return self.f(new_root)
def f(self, root):
if not root:
return 0
res = 0
for child in root.children:
child_max_depth = self.f(child)
res = max(res, child_max_depth)
return res + 1
def copy_tree(self, root):
if not root:
return None
my_root = MyTreeNode(root.val)
my_root.children[random.randint(0, 7)] = self.copy_tree(root.left)
my_root.children[random.randint(0, 7) + 8] = self.copy_tree(root.right)
return my_root
if __name__ == '__main__':
# TREE 1
# Construct the following tree
# 1
# / \
# 2 3
# / \
# 4 5
# / \
# 6 7
# \
# 8
P = TreeNode(1)
P.left = TreeNode(2)
P.left.left = TreeNode(4)
P.left.right = TreeNode(5)
P.left.right.left = TreeNode(6)
P.left.right.right = TreeNode(7)
P.left.right.right.right = TreeNode(8)
P.right = TreeNode(3)
#
#
# Q = Node(26)
# Q.left = Node(10)
# Q.left.left = Node(4)
# Q.left.right = Node(6)
# Q.right = Node(3)
# # Q.right.right = Node(3)
s = Solution6()
print(s.maxDepth(P))
|
c7f10a666cc7d40a12a0d2671fa67f50372ce5ba | emredenizozer/algorithms | /AID.py | 1,753 | 3.890625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'findMatch' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. STRING_ARRAY possibleMatches
# 2. STRING crossword
#
def findMatch(possibleMatches, crossword):
sanitizedCrossword = crossword.replace('.', '').lower()
sanitizedCrosswordIndexes = []
result = ""
found = True
for i in range(len(crossword)):
if crossword[i] != '.':
sanitizedCrosswordIndexes.append(i)
for item in possibleMatches:
if len(crossword) == len(item):
for i in range(len(sanitizedCrosswordIndexes)):
if found and crossword[sanitizedCrosswordIndexes[i]] == item[sanitizedCrosswordIndexes[i]].lower():
continue;
else:
found = False
break;
if found:
result = item.lower()
break;
else:
continue
return result
if __name__ == '__main__':
possibleMatches = ["vaporeon", "jolteon", "espeon", "tolteon"]
crossword = "...or..."
result = findMatch(possibleMatches, crossword)
crossword = "...eon"
result = findMatch(possibleMatches, crossword)
print(result)
'''
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
possibleMatches_count = int(input().strip())
possibleMatches = []
for _ in range(possibleMatches_count):
possibleMatches_item = input()
possibleMatches.append(possibleMatches_item)
crossword = input()
result = findMatch(possibleMatches, crossword)
fptr.write(result + '\n')
fptr.close()
''' |
ac0f42d9d771005a2641afbbb75a17a05930f457 | shirataaki/Python | /SymmeticTree.py | 902 | 3.84375 | 4 | # ノードクラスの定義
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 root == None:
return True
return self.isMirror(root, root)
def isMirror(self, t1, t2):
if not t1 and not t2: # t1,t2どちらもfalseの時
return True # 左右対称
if not t1 or not t2: # どちらかがtrueでない時
return False # 左右非対称
return t1.val == t2.val and self.isMirror(t1.right, t2.left) and self.isMirror(t1.left, t2.right)
if __name__ == '__main__':
root1 = [1,2,2,3,4,4,3]
Sol = Solution(root1)
Sol.isSymmetric()
|
06948cfe8945efa767ed9cc1b9ad0cb33d515daa | andrelima19/Projetos_Python | /Developer/Python_Definitivo/Exercícios/Condicionais_If_Else/venv/Ex 34 – Aumentos múltiplos.py | 609 | 3.8125 | 4 | # Exercício Python 34: Escreva um programa que pergunte o salário de um funcionário e
# calcule o valor do seu aumento. Para salários superiores a R$1250,00, calcule um aumento de 10%.
# Para os inferiores ou iguais, o aumento é de 15%.
salario = float(input('Informe o salário: '))
if salario > 1250:
aumento = (salario) * 10/100
print(f'Seu aumento foi de: R$ {aumento},00\n'
f'Seu novo salário é: R${(salario + aumento)},00')
else:
aumento = (salario * 15/100)
print(f'Seu aumento foi de: R$ {aumento},00\n'
f'Seu novo salário é: R${(salario + aumento)},00') |
fdc37b0391d4d75e3ab4862bd8759d37ed064540 | Conquerk/test | /python/day18/code/super.py | 447 | 3.671875 | 4 | #此示例 示意用super函数显示的调用被覆盖的方法
class A:
def work(self):
print("A.work被调用")
class B(A):
def work(self):
"""此方法覆盖父类的work"""
print("B.work被调用")
def mywork(self):
#调用自己的方法
#调用父类的方法
self.work()
super(B,self).work()
b=B()
# b.work()
# A.work(b)
# super(B,b).work()
b.mywork() |
582b5d3d807272ab41be1aede8a35cc6bd2e555b | zedikram/I0320116_Zedi-Ikram-El-Fathi_Tugas4 | /I0320116_Exercise 4.10.py | 139 | 3.515625 | 4 | string: Hello World
skipping: x x x x x #characters marked with x
final str: HloWrd
#string
str = "Hello World"
#skip
new_str = str[0::2] |
f52d5438a310cb4dceafaf29dbe4027fca8b94ab | ArifulSourov/Problem-solving | /Quick Sort.py | 1,305 | 3.625 | 4 | elements = [23, 1, 4, 33, 14, 7, 11, 30]
def quick_sort(elements, start, end):
if start < end:
pi = partion(elements, start, end)
quick_sort(elements, start, pi-1)
quick_sort(elements, pi+1, end)
def partion(elements, start, end):
pivot_index = start
pivot = elements[pivot_index]
while start < end:
while start < len(elements) and elements[start] <= pivot:
start += 1
while elements[end] > pivot:
end -= 1
if start < end:
swap(start, end, elements)
swap(pivot_index, end, elements)
return end
def partition_lomuto(elements, start, end):
pivot = elements[end]
p_index = start
for i in range(start, end):
if elements[i] <= pivot:
swap(i, p_index, elements)
p_index += 1
swap(p_index, end, elements)
return p_index
def swap(a, b, arr):
if a != b:
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
quick_sort(elements, 0, len(elements)-1)
print(elements)
tests = [
[11,9,29,7,2,15,28],
[3, 7, 9, 11],
[25, 22, 21, 10],
[29, 15, 28],
[],
[6]
]
for elements in tests:
quick_sort(elements, 0, len(elements)-1)
print(f'sorted array: {elements}')
|
a6d02fcfe6210c4e15d87d6601b98dcf11a76aed | chenxu0602/LeetCode | /1346.check-if-n-and-its-double-exist.py | 1,191 | 3.75 | 4 | #
# @lc app=leetcode id=1346 lang=python3
#
# [1346] Check If N and Its Double Exist
#
# https://leetcode.com/problems/check-if-n-and-its-double-exist/description/
#
# algorithms
# Easy (36.87%)
# Likes: 240
# Dislikes: 37
# Total Accepted: 65.8K
# Total Submissions: 178.8K
# Testcase Example: '[10,2,5,3]'
#
# Given an array arr of integers, check if there exists two integers N and M
# such that N is the double of M ( i.e. N = 2 * M).
#
# More formally check if there exists two indices i and j such that :
#
#
# i != j
# 0 <= i, j < arr.length
# arr[i] == 2 * arr[j]
#
#
#
# Example 1:
#
#
# Input: arr = [10,2,5,3]
# Output: true
# Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.
#
#
# Example 2:
#
#
# Input: arr = [7,1,14,11]
# Output: true
# Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.
#
#
# Example 3:
#
#
# Input: arr = [3,1,7,11]
# Output: false
# Explanation: In this case does not exist N and M, such that N = 2 * M.
#
#
#
# Constraints:
#
#
# 2 <= arr.length <= 500
# -10^3 <= arr[i] <= 10^3
#
#
#
# @lc code=start
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
# @lc code=end
|
5d85798847de1c6516b71236e3ca9518bb59144c | phgilliam/100DaysOfCode | /PracticePython/ex8.py | 725 | 3.8125 | 4 | import random
def comp_rps():
seq = ['r','p','s']
return str(random.choice(seq))
def game(comp,play):
if play == 'r' and comp == 's':
return 'Player Wins!'
elif play == 'p' and comp == 'r':
return 'Player Wins!'
elif play == 's' and comp == 'p':
return 'Player Wins!'
elif play == 'q':
return 'Thanks for playing!'
elif play != 'r' or play != 'p' or play != 's' or play != 'q':
return 'Enter \'r\',\'p\',\'s\' or \'q\''
else:
return 'Computer Wins'
x = input('Type \'q\' to quit, press anything to continue: ')
while x != 'q':
x = input('\'r\' for rock, \'p\' for paper \'s\' for scissors: ')
y = comp_rps()
print(game(y,x))
|
12836db6995280c1992bd03774cb3fee31e3606a | miaviles/Data-Structures-Algorithms-Python | /random_interview_questions/seven_sided_dice.py | 663 | 4.09375 | 4 | from random import randint
# Given a dice which rolls from 1 to 5, simulate a uniform 7 sided dice!
def dice5():
return randint(1, 5)
def convert5to7():
# For constant re-roll purposes
while True:
# Roll the dice twice
roll_1 = dice5()
roll_2 = dice5()
# Convert the combination to the range 1 to 25
# range of 0-20 and range of 1-5
num = ((roll_1-1) * 5) + (roll_2)
# print 'The converted range number was:',num
# this number is arbitrary
if num > 21:
# re-roll if we are out of range
continue
return num % 7 + 1
print(convert5to7())
|
4141391de313279a9bf0f271f942f835838d6087 | ravikumarvj/DS-and-algorithms | /Graphs/hamilton.py | 2,282 | 3.671875 | 4 | ### COPIED ### VERIFIED
from graph import NGraph
def print_all_hamilton_path_r(g, start, path, visited):
# All nodes are visited. Found a hamilton path.
if len(visited) == len(g.vert_list):
print(path)
return
node = g.vert_list[start]
for neigh in node.get_neighs():
if neigh not in visited: # Go through the unvisited nodes to find a path
path.append(neigh)
visited.add(neigh)
print_all_hamilton_path_r(g, neigh, path, visited)
path.pop()
# Done with neigh, free it so that it can be part of another path
visited.remove(neigh)
def print_all_hamilton_path(g, start):
path = [start]
visited = set()
visited.add(start) # ADD start to visited here
# Find all paths starting from 'start' node and see if all nodes are visited
print_all_hamilton_path_r(g, start, path, visited)
def print_all_hamilton_cycles_r(g, start, end, path, visited):
visited.add(start)
path.append(start)
if start == end:
# print path, only if we reach back 'start' after visiting all nodes
if len(visited) == len(g.vert_list):
print(path)
path.pop() # pop the node before return
visited.remove(start)
return
node = g.vert_list[start]
for neigh in node.get_neighs():
if neigh not in visited:
print_all_hamilton_cycles_r(g, neigh, end, path, visited)
path.pop()
visited.remove(start)
def print_all_hamilton_cycles(g, start):
path = []
visited = set()
path.append(start) # start will be there is path twice (start and end)
# start is not visited yet
node = g.vert_list[start]
# Go through all the neighbours of start and find a path ending at start
for neigh in node.get_neighs():
print_all_hamilton_cycles_r(g, neigh, start, path, visited)
if __name__ == '__main__':
g = NGraph()
g.add_edge(1, 2)
g.add_edge(1, 4)
g.add_edge(2, 3)
g.add_edge(2, 7)
g.add_edge(3, 4)
g.add_edge(3, 5)
g.add_edge(3, 6)
g.add_edge(3, 7)
g.add_edge(4, 6)
g.add_edge(5, 6)
g.add_edge(5, 7)
# g.add_edge(6, 8)
print_all_hamilton_path(g, 5)
print('****')
print_all_hamilton_cycles(g, 7) |
5c05343b01de0ba400d93704cc5e352d221d7872 | neerajsharma9195/count-sketch-feature-selection | /src/utils/hash_generator.py | 1,323 | 3.515625 | 4 | import random
from src.utils.utils import isPrime
class HashGeneration():
def __init__(self, num_hash, size):
self.num_hash = num_hash
self.size = size
self.primes = []
self.first = []
self.second = []
self.generate_hash_function()
def generate_hash_function(self):
# ((Ax + B) mod prime) % size_of_array
primes = [i for i in range(self.size + 1, self.size + 3000) if isPrime(i)]
self.primes = random.sample(primes, self.num_hash)
self.first = [random.randint(1, 1000) for i in range(self.num_hash)]
self.second = [random.randint(1, 1000) for i in range(self.num_hash)]
def get_hash_sign_and_value(self, number):
hash_values = [0] * self.num_hash
sign_values = [0] * self.num_hash
for i in range(self.num_hash):
hash_val = ((self.first[i] * number + self.second[i]) % self.primes[i])
hash_values[i] = hash_val % self.size
sign_values[i] = 1 if hash_val % 2 == 0 else -1
return hash_values, sign_values
def get_hash_value(self, number):
hash_values = [0] * self.num_hash
for i in range(self.num_hash):
hash_values[i] = ((self.first[i] * number + self.second[i]) % self.primes[i]) % self.size
return hash_values
|
9b4e27d79ea8b3a45da1cf35d19e27838bc38465 | a-harper/pygamelearning | /guessing.py | 625 | 3.90625 | 4 | __author__ = 'harpera'
import random
answer = random.randrange(1, 100)
guess = 0
attemptCount = 1
attemptLimit = 7
print("Hi! I'm thinking of a random number between 1 and 100.")
while guess != answer:
if attemptCount > attemptLimit:
print("Aw, you ran out of tries. The number was", answer)
break
print("Attempt: ", attemptCount)
guess = int(input("Guess what number I am thinking of: "))
if guess > answer:
print("Too high")
if guess < answer:
print("Too low")
if guess == answer:
print("Correct! The answer was:", answer)
break
attemptCount += 1 |
ca9651b03dca037b0c1404ffe0196f529dbbd690 | iiLincolnii/Homecoming | /22.py | 401 | 3.609375 | 4 | def main():
basis=int(input("输入一个基础数: "))
n=int(input('输入该数长度: '))
arr=[0]*n
b=basis
sum=0
for i in range(n):
arr[i]=basis
sum +=basis
basis=basis * 10 + b
print("%d="%sum,end='')
for i in range(n):
print("%d"%arr[i],end='')
if i < n-1:
print("+",end='')
if __name__=='__main__':
main()
|
c1019b17f2d68b5e00dc233698bef4122a6c7a75 | CrazyIEEE/algorithm | /OnlineJudge/LeetCode/第1个进度/1315.祖父节点值为偶数的节点和.py | 1,858 | 3.59375 | 4 | #
# @lc app=leetcode.cn id=1315 lang=python3
#
# [1315] 祖父节点值为偶数的节点和
#
# https://leetcode-cn.com/problems/sum-of-nodes-with-even-valued-grandparent/description/
#
# algorithms
# Medium (80.69%)
# Likes: 34
# Dislikes: 0
# Total Accepted: 7.1K
# Total Submissions: 8.8K
# Testcase Example: '[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]'
#
# 给你一棵二叉树,请你返回满足以下条件的所有节点的值之和:
#
#
# 该节点的祖父节点的值为偶数。(一个节点的祖父节点是指该节点的父节点的父节点。)
#
#
# 如果不存在祖父节点值为偶数的节点,那么返回 0 。
#
#
#
# 示例:
#
#
#
# 输入:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
# 输出:18
# 解释:图中红色节点的祖父节点的值为偶数,蓝色节点为这些红色节点的祖父节点。
#
#
#
#
# 提示:
#
#
# 树中节点的数目在 1 到 10^4 之间。
# 每个节点的值在 1 到 100 之间。
#
#
#
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
def preorder(root):
if root:
if not root.val % 2:
for p in (root.left, root.right):
if p:
nonlocal res
res += p.left.val if p.left else 0
res += p.right.val if p.right else 0
preorder(root.left)
preorder(root.right)
res = 0
preorder(root)
return res
# @lc code=end
|
26fb53b4f453836de7b05aa02902eb205b0ed035 | OliviaT1029/Summer-Camp-Project | /Substitute.py | 585 | 3.859375 | 4 | import random
alphabet = "abcdefghijklmnopqrstuvwxyz"
def main():
key = make_key(alphabet)
original = input("Message: ").lower()
ciphertext = encrypt(original, key)
plaintext = decrypt(ciphertext, key)
print()
print("Original text: ", original)
print("Encrypted text:", ciphertext)
print("Decrypted text:", plaintext)
print()
def encrypt(text, key):
def decrypt(text, key):
def make_key(alphabet):
shuffled = list(alphabet)
random.shuffle(shuffled)
return ''.join(shuffled)
if __name__ == "__main__":
main() |
cecb0fc3866c66088f2c231af9b110787dbe0d1f | AyberkYavuz/body_type_estimator | /core/file_handler.py | 805 | 3.96875 | 4 | import pickle
class PickleHandler:
"""PickleHandler which is used for saving, loading and dumping python objects.
"""
def save_object(self, path, obj):
"""Saves the python object.
Args:
path: str. Saving location of the python object.
obj: object. Python object to be saved.
"""
with open(path, 'wb') as handle:
pickle.dump(obj, handle, protocol=pickle.HIGHEST_PROTOCOL)
def load_object(self, path):
"""Loads the pickle file as python object.
Args:
path: str. Location of the pickle file.
Returns:
python_object: object. Python object.
"""
with open(path, 'rb') as handle:
python_object = pickle.load(handle)
return python_object
|
7b91555a2044d1c5e22825831e1716a72554a0e5 | kaufmann42/Machine-Learning-Work | /HW2/cm.py | 1,134 | 3.515625 | 4 | # John Kaufmann
# 3/16/2016
# BME4931
#
# print a confusion matrix given the predicted classifiers, the actual classifiers and the name of the structure
def print_ConfusionMatrix(predicted, actual, name):
actual = predicted
total = actual.shape[0]
one = 0
two = 0
three = 0
four = 0
#construct confusion matrix
for i in range(0,total):
if predicted[i] == 0 and actual[i] == 0:
one += 1
elif predicted[i] == 1 and actual[i] == 0:
two += 1
elif predicted[i] == 0 and actual[i] == 1:
three += 1
elif predicted[i] == 1 and actual[i] == 1:
four += 1
#print everythin
print("***" + name + "***")
print("\t\t"+"Predicted Negative\t"+"Predicted Positive\t")
print("Negative Cases\t"+str(one)+"\t\t\t"+str(two)+"\t")
print("Positive Cases\t"+str(three)+"\t\t\t"+str(four)+"\t")
print("\n++Statistics++")
print("The accuracy was: "+"%.2f"%float((one + four)/(one+two+three+four)))
print("The recall was: "+ "%.2f"%float(four/(four+three)))
print("The precision was: "+ "%.2f"%float(four/(four+two)))
|
b15b2fbe8aeea17f97af482aa7e208d1dcd64ec4 | DimoDimchev/Softuni-Python-OOP | /Decorators/even_numbers.py | 281 | 3.75 | 4 | def even_numbers(function):
def wrapper(*args, **kwargs):
func = function(*args, **kwargs)
return [num for num in func if num % 2 == 0]
return wrapper
# @even_numbers
# def get_numbers(numbers):
# return numbers
#
# print(get_numbers([1, 2, 3, 4, 5])) |
b133fd79aee52d51607fdca83b9d184a6eaf1156 | GabrielCzar/Analise-de-Algoritmos | /monitoria/06-12/recursivo.py | 477 | 3.703125 | 4 | itens = [5, 11, 5, 1]
def tesouro(soma, i):
if soma == 0 and i == 0:
return True
if not soma == 0 and i == 0:
return False
if soma == 0 and not i == 0:
return True
global itens
return tesouro (soma, i - 1) or tesouro(soma - itens[i], i - 1)
def main():
global itens
soma = 0
n = 3
for item in itens:
soma += item
if soma % 2 == 0:
print tesouro(int(soma / 2), n)
else:
print False
main()
|
d49ec9c3e318fc535b5be4f43dd4c0ea3386ca02 | PranjalBalar/Algorithms | /Arithmetic/EightQueens.py | 1,435 | 4 | 4 | # -*- coding: utf-8 -*-
#This program places 8 queens on a chessboard
#It uses backtracking to find the solution
global N
N = 8
def display(board):
for i in range(N):
for j in range(N):
print board[i][j],
print
def isSafe(board, row, col):
for i in range(col):
if board[row][i] == 1:
return False
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def placement(board, col):
if col >= N:
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
if placement(board, col + 1) == True:
return True
board[i][col] = 0
return False
def solve():
board = [ [0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]
]
if placement(board, 0) == False:
print "Solution does not exist"
return False
display(board)
return True
solve()
|
8f1ab4e41d40a13918efe67e79054258f5da398e | Dave-weatherby/All-Projects | /Python-Projects/flowChartToCode/flowChartToCode.py | 549 | 3.71875 | 4 | def main():
startData = [100, 2, 323, 66, 65, 67, 99, 27, 212, 8]
sortedData = []
# main for loop
for y in range(0, 10):
largest = 0
# sorting from largest to smallest
for x in range(0, 10):
if startData[x] > largest and startData[x] != -1:
largest = startData[x]
Index = x
# appending new order to new list
sortedData.append(largest)
startData[Index] = -1
# printing loop
for n in range(0, 10):
print(sortedData[n])
main()
|
14457f19aa27d2cea152d0369a15355d011e9984 | endy-see/AlgorithmPython | /SwordOffer/61-PrintZhiTree.py | 2,909 | 3.9375 | 4 | """
按之字形顺序打印二叉树
题目:请实现一个函数按照之字形打印二叉树,即第一层按照从左到右的顺序打印,
第二层按照从右至左的顺序打印,第三层按照从左到右的顺序打印,其他层以此类推
思路:
1. 两个栈实现 -> 逻辑清晰 快 容易写
2. 用双端队列 用flag控制打印方向(好是好,但是不知道什么时候该遍历下一层,这种方法先放着吧)
flag=True 从左往右打印 从左边弹出节点 从右边加入其孩子节点 先入左孩子再入右孩子
flag=False 从右往左打印 从右边弹出节点 从左边加入其孩子节点 先入右孩子再入左孩子
count 记录每次打印的节点个数
"""
from collections import deque
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def Print(self, pRoot):
# write code here
if not pRoot:
return []
result = []
res = []
left_to_right_list = []
right_to_left_list = []
left_to_right_list.append(pRoot)
while len(left_to_right_list) != 0 or len(right_to_left_list) != 0:
while left_to_right_list:
cur_node = left_to_right_list.pop()
res.append(cur_node.val)
if cur_node.left:
right_to_left_list.append(cur_node.left)
if cur_node.right:
right_to_left_list.append(cur_node.right)
if len(res) != 0:
result.append(res)
res = []
while right_to_left_list:
cur_node = right_to_left_list.pop()
res.append(cur_node.val)
if cur_node.right:
left_to_right_list.append(cur_node.right)
if cur_node.left:
left_to_right_list.append(cur_node.left)
if len(res) != 0:
result.append(res)
res = []
return result
def Print1(self, pRoot):
# write code here
if not pRoot:
print('None')
queue = deque()
queue.append(pRoot)
is_end = False
flag = True
while len(queue) != 0:
# 从左往右打印 从队列左边出节点
if flag:
node = queue.popleft()
is_end = True
queue.append(node.left)
queue.append(node.right)
flag = False
else:
print('not finished!')
obj = Solution()
obj = Solution()
root = TreeNode(8)
tn1 = TreeNode(6)
tn2 = TreeNode(9)
root.left = tn1
root.right = tn2
tn3 = TreeNode(5)
tn4 = TreeNode(7)
tn1.left = tn3
tn1.right = tn4
tn5 = TreeNode(7)
tn6 = TreeNode(5)
tn2.left = tn5
tn2.right = tn6
print(obj.Print(root))
|
895710e9b7ab0b9d8bacfdb8939ea0750a597344 | yang4978/LeetCode | /Python3/0515. Find Largest Value in Each Tree Row.py | 1,307 | 3.734375 | 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 largestValues(self, root: TreeNode) -> List[int]:
if not root:
return []
queue = [root]
res = []
while queue:
max_value = -float('inf')
for _ in range(len(queue)):
node = queue.pop(0)
max_value = max(max_value,node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(max_value)
return res
# if not root:
# return []
# queue = [(root,1)]
# res = []
# while queue:
# node,layer = queue.pop(0)
# if layer>len(res):
# res.append(node.val)
# else:
# res[layer-1] = max(res[layer-1],node.val)
# if node.left:
# queue.append((node.left,layer+1))
# if node.right:
# queue.append((node.right,layer+1))
# return res
|
f979bda62d0af287ef35cb3b70a7c9b29907ebd3 | yamashitamasato/atcoder | /atcoder009A.py | 66 | 3.5 | 4 | N=int(input())
if(N%2==0):
print(N/2)
else:
print((N/2)+1) |
c20075cea6ee0450d736e68a0f666d90b8dd5f53 | mraza2024/iq_game_edge | /iq_game_edge.py | 2,156 | 4.375 | 4 | #how smart are you?
print("Welcome to the Intellectual Game! You will see 10 questions that will test your general knowledge and intelligence. Your goal is to answer all the questions correctly, otherwise the game will stop. At the end of the game, the program will show your result. Good luck!")
questions=["Which of these is a type of hat? (a)Sausage roll, b)Pork pie, c)Scotch egg, d)Potato crisp",
"Which of these have to pass a test on ‘The Knowledge’ to get a licence? a) Taxi drivers, b) Bus drivers, c) Police officers, d) Ambulance drivers",
"Which of these phrases refers to a brief success? a)Blaze in the pot, b)Spark in the tub, c)Flare in the jug, d)Flash in the pan",
"The young of which creature is known as a squab? a)Salmon, b)Horse, c)Pigeon, d)Octopus,
"Which of these US presidents appeared on the television series 'Laugh-In?' a)Lyndon Johnson b)Richard Nixon c)Jimmy Carter d)Gerald Ford"
"Which insect shorted out an early supercomputer and inspired the term 'computer bug'? a)Moth b)Roach c)Fly d)Japanese beetle"
"Which of the following men does not have a chemical element named for him? a)Albert Einstein b)Niels Bohr c)Isaac Newton d)Enrico Fermi]
answers=["b",
"a",
"d",
"c",
"b"
"a"
"c"
]
recomends=[]
import random
x=random.randint(0,4)
print ("Question 1:" + questions[x])
answer_right=answers[x]
answer_user=input("What is your answer?")
if answer_right==answer_user:
print("Wow! Your answer is right!")
while answer_right==answer_user:
x=random.randint(0,4)
print ("Question 1:" + questions[x])
answer_right=answers[x]
answer_user=input("What is your answer?")
else:
print("Unfortunately, your answer is wrong. However, you can i,prove your knowledge by reading or watching the next: "+recomends[x])
print("You have answered "+str(NUMBER OF RIGHT QUESTIONS)+" questions right.")
#also we need to show the user his level somehow, like 1-3 questions - average level, 4-6 - above average, 7-10 - extraordinarily smart)
print("Thank you for taking part in our quiz!")
|
40f7e9d4b43bdb587bf0ab97ee0aa834547fccf2 | pideviq/quizzes | /Python/reverse_and_add.py | 2,254 | 4.15625 | 4 | ''' == EN ==
The problem is as follows: choose a number, reverse it's digits and add it
to the original. If the sum is not a palindrome (which means, it is not the
same number from left to right and right to left), repeat this procedure.
For example:
195 (initial number) + 591 (reverse of initial number) = 786
786 + 687 = 1473
1473 + 3741 = 5214
5214 + 4125 = 9339 (palindrome)
In this particular case the palindrome 9339 appeared after the 4th addition.
This method leads to palindromes in a few step for almost all of the
integers. But there are interesting exceptions. 196 is the first number for
which no palindrome has been found. It is not proven though, that there is
no such a palindrome.
Input: a string with an integer n < 10,000. Assume each test case has an
answer if it is computable with less than 100 iterations (additions),
otherwise return a blank string.
Output: a string with the number of iterations (additions) to compute the
palindrome and the resulting palindrome (they should be on one line and
separated by a single space character) or a blank string if no palindrome
was found.
'''
def palindrome(number):
number = number.strip()
for count in range(1, 101):
number = str(int(number) + int(number[::-1]))
length = len(number)
# define indexes to split the number for check
if length % 2 == 0:
i = int(length / 2)
sep = (i, i)
else:
i = int(length // 2)
sep = (i, i + 1)
# check if number is a palindrome
if number[:sep[0]] == number[sep[1]:][::-1]:
return '%d %s' % (count, number)
return ''
if __name__ == '__main__':
test_cases = [('195', '4 9339'),
('2711', '1 3883'),
('4741', '3 25652'),
('1706', '1 7777'),
('4291', '3 25652'),
('375', '15 8836886388'),
('3857', '2 15851'),
('119', '2 1331'),
('196', '')]
for test in test_cases:
assert palindrome(test[0]) == test[1], 'failed %s' % test[0]
|
fa754ac465e633bd84fe145e1445274a1b19a640 | KKosukeee/CodingQuestions | /LeetCode/266_palindrome_permutation.py | 1,066 | 3.921875 | 4 | """
Solution for 266. Palindrome Permutation
https://leetcode.com/problems/palindrome-permutation/
"""
from collections import defaultdict
class Solution:
"""
Runtime: 28 ms, faster than 97.34% of Python3 online submissions for Palindrome Permutation.
Memory Usage: 13.6 MB, less than 50.00% of Python3 online submissions for Palindrome Permutation.
"""
def canPermutePalindrome(self, s: str) -> bool:
"""
Given a string, determine if a permutation of the string could form a palindrome.
Example 1:
Input: "code"
Output: false
Example 2:
Input: "aab"
Output: true
Example 3:
Input: "carerac"
Output: true
Args:
s(str):
Returns:
bool:
"""
counter = defaultdict(int)
odd_count = 0
for char in s:
counter[char] += 1
if counter[char] % 2 == 0:
odd_count -= 1
else:
odd_count += 1
return odd_count <= 1
|
653053886fb93a20a941069b8f97897c757be92c | jimibarra/cn_python_programming | /15_aggregate_functions/15_03_my_enumerate.py | 445 | 4.21875 | 4 | '''
Reproduce the functionality of python's .enumerate()
Define a function my_enumerate() that takes an iterable as input
and yields the element and its index
'''
def my_enumerate(sequence):
my_list = []
count = 0
for item in sequence:
my_tuple = (count, item)
my_list.append(my_tuple)
count +=1
return my_list
my_list = ['a', 'b', 'c', 'd']
result = my_enumerate(my_list)
print(result)
|
28dcd707d2fc0da0238092eb4306141449123f1a | johanwahyudi/Cryptography | /Classic/Transposition-Cipher/Encrypt.py | 2,017 | 4.0625 | 4 | #!/usr/bin/env python
from string import lowercase, uppercase
#library cuma untuk besar kecil huruf saja
#fungsi enkripsi caesar
def caesar_en(text, key):
result = []
for c in text:
if c in lowercase:
enkripsi = lowercase.index(c)
enkripsi = (enkripsi + key) % 26
result.append(lowercase[enkripsi])
print result
elif c in uppercase:
enkripsi = uppercase.index(c)
enkripsi = (enkripsi + key) % 26
result.append(uppercase[enkripsi])
else:
result.append(c)
return "".join(result)
#fungsi transposition
def permutasi(key, pesan, key02):
ciphertext = [''+","]*key
for kolom in range(key):
c = kolom
while c < len(pesan):
ciphertext[kolom] += pesan[c]
c += key
print ciphertext
data = ''.join(ciphertext)
#split data, di buat list
pecah = data.split(',')
print pecah
#fungsi acak kolom :
key1 = key02
a = []
l = list(map(int,key1))
for i in range(0,len(l)):
a.append(pecah[l[i]+1])
ciphertext02 =''.join(a)
datafix = data.replace(",","")
print "kunci acak kolom :"+key1
print "Ciphertext sebelum di acak : "+datafix
print "Ciphertext Setelah di acak kolomnya : "
return ciphertext02
def main():
pesan = raw_input("masukkan pesan :")
rot = input("masukkan kunci ROT :")
print "hasil Enkripsi dengan ROT "+str(rot)+" :"
print caesar_en(pesan,rot)
pesan1 = caesar_en(pesan,rot)
key = input("masukkan jumlah kolom :")
# kunci acak kolom di mulai dari nol, misal jumlah kolom 3, maka range
#untuk kunci acak kolom adalah 0-2, akan error apabila melebihi angka itu
key02 = raw_input("masukkan kunci acak kolom : ")
print "pesan Asli (plaintext) : "+pesan
print "hasil Enkripsi dengan ROT "+str(rot)+" :"
print caesar_en(pesan,rot)
print permutasi(key, pesan1, key02)
if __name__ == '__main__':
main()
|
e25e7be39934dd4a27bb4bf1b7a87ffbfef2621d | ElazarNeeman/python_zth | /overview/p22_functions/task2_ref.py | 985 | 4.21875 | 4 | # write a function 'above_avg' which can take an arbitrary number of arguments and returns a list contains
# only the elements that are above the average
def above_avg(*args):
avg = sum(args) / len(args)
return list(filter(lambda e: e > avg, args))
print(above_avg(10, 2, 4, 9, 34, 3, 15))
# write a function 'is_sample_above_avg_factory' which takes a list of samples and returns a new function that:
# - takes a sample and tells if the sample is above the avg of samples.
# - prints the sample and the avg on each call in format: 'sample is 32, avg is 15'
# - avg should be calculates only once
def is_sample_above_avg_factory(samples):
avg = sum(samples) / len(samples)
def is_sample_above_avg(sample):
print(f"sample is {sample}, avg is {avg}")
return sample > avg
return is_sample_above_avg
is_sample_above_avg = is_sample_above_avg_factory([10, 2, 4, 9, 34, 3, 15])
print(is_sample_above_avg(12))
print(is_sample_above_avg(10))
|
ad9791162854c5299a00ee39fd7d18fcb54a785d | benjiemalinao87/LearnPythonTheHardWay | /Functions/func.py | 411 | 3.671875 | 4 |
# get name function,name& mobile hardcoded
def print_two(arg1, arg2):
print(f"Enter your name: {arg1}")
print(f'Enter you mobile: {arg2}')
# get name&mobile form users input
# this just takes one argument
def print_one(arg1):
print(f"Enter age: {arg1}")
# this one takes no arguments
def print_none():
print("I got nothin'.")
print_two("Benjie","04050505")
print_one('30')
print_none() |
4210c248c291a573248f5fcb53ca91222df5f125 | dejuata/Mario-Smart | /app/game/agent/node.py | 2,528 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Basado en https://www.cs.us.es/cursos/iati-2012/
from game.utilities.utilities import find_position as find_mario
class Node:
"""
Un nodo se define como:
• El estado del problema
• Una referencia al nodo padre
• El operador que se aplicó para generar el nodo
• Profundidad del nodo
• El costo de la ruta desde la raíz hasta el nodo
"""
def __init__(self, state, parent=None, action=None, path_cost=0, inmune=False, start=False):
self.state = state
self.parent = parent
self.action = action
self.path_cost = path_cost
self.depth = 0
self.mario = find_mario(self.state, 2)
self.inmune = inmune
self.start = start
if parent:
self.depth = parent.depth + 1
def __repr__(self):
return "<Node {}>".format(self.state)
def __lt__(self, node):
return self.state < node.state
def expand(self, problem):
"""
List of nodes generated by the possible actions applied to the initial state
"""
return [self.child_node(problem, action) for action in problem.actions(self.state, self.mario)]
def child_node(self, problem, action):
"""
Successor of a node by an applicable action
"""
result = problem.result_of_actions((self.state, self.inmune, self.start), action, self.mario)
next_node = result
inmune = self.inmune
start = self.start
if type(result) is tuple:
next_node = result[0]
inmune = True
if type(result) is list and len(result) == 2:
next_node = result[0]
start = True
return Node(
state=next_node,
parent=self,
action=action,
inmune=inmune,
start=start,
path_cost = problem.path_cost(
c = self.path_cost,
state = self.state,
action = action,
mario = self.mario,
inmune=inmune,
start=start
)
)
def solution(self):
"""
Return the sequence of actions to go from the root to this node.
"""
return [node.action for node in self.path()[1:]]
def path(self):
"""
Return a list of nodes forming the path from the root to this node.
"""
node, path_back, cost = self, [], []
while node:
path_back.append(node)
cost.append(node.path_cost)
node = node.parent
return list(reversed(path_back))
def __eq__(self, other):
return isinstance(other, Node) and self.state == other.state
def state_to_tuple(self):
return tuple(tuple(row) for row in self.state)
|
ad4645a495dbbfdcbf48e6426db56899e078cb52 | 2226171237/Algorithmpractice | /NewKe/t2.py | 2,177 | 3.71875 | 4 | '''
题目描述
对于一个给定的正整数组成的数组 a[] ,如果将 a 倒序后数字的排列与 a 完全相同,我们称这个数组为“回文”的。
例如, [1, 2, 3, 2, 1] 的倒序是他自己,所以是一个回文的数组;而 [1, 2, 3, 1, 2] 的倒序是 [2, 1, 3, 2, 1] ,
所以不是一个回文的数组。对于任意一个正整数数组,如果我们向其中某些特定的位置插入一些正整数,那么我们总是能构
造出一个回文的数组。输入一个正整数组成的数组,要求你插入一些数字,使其变为回文的数组,且数组中所有数字的和尽
可能小。输出这个插入后数组中元素的和。例如,对于数组 [1, 2, 3, 1, 2] 我们可以插入两个 1 将其变为回文的数组
[1, 2, 1, 3, 1, 2, 1] ,这种变换方式数组的总和最小,为 11 ,所以输出为 11 。
'''
from collections import deque
class Solution:
def reLoopAray(self, L):
def _loopArray(L):
n = len(L)
if n == 1:
return L[0]
if n == 0:
return 0
if L[0] == L[-1]:
return L[0] + L[-1] + _loopArray(L[1:-1])
else:
A = L[0] + L[0] + _loopArray(L[1:])
B = L[-1] + L[-1] + _loopArray(L[:-1])
return min(A, B)
return _loopArray(L)
def loopAray(self, L):
n = len(L)
if n == 0:
return 0
if n == 1:
return L[0]
P = [[0 for _ in range(n)] for _ in range(n)]
i = 0
while i < n:
P[i][i] = L[i]
i += 1
k = 1
while k < n:
i = 0
j = k
while i < n and j < n:
if L[i]!=L[j]:
P[i][j] = min(L[i] + L[i] + P[i + 1][j], L[j] + L[j] + P[i][j - 1])
else:
P[i][j]=P[i+1][j-1]+L[i]+L[i]
i += 1
j += 1
k+=1
for p in P:
print(p)
return P[0][n - 1]
if __name__ == '__main__':
S=Solution()
L=[1,2,3,1,2,3,5,4]
print(S.loopAray(L)) |
927f4bc708c1ffb46ac5c4ef885d9c9198d30588 | endoeduardo/snake | /objects.py | 1,180 | 3.515625 | 4 | import pygame
from random import randint
class Apple():
"""Configurações da maçã"""
def __init__(self, settings):
self.settings = settings
#Criando uma surface pra maçã
self.skin = pygame.Surface((self.settings.apple_width, self.settings.apple_height))
self.skin.fill(self.settings.apple_color)
#Gerando uma posição aleatória pra maçã
self.pos = (randint(0, (settings.screen_width - 10))//10*10, randint(0, (settings.screen_height - 10))//10*10)
class Snake():
"""Configuração da cobra"""
def __init__(self, settings):
self.settings = settings
#Criando uma suface para a cobra
self.skin = pygame.Surface((self.settings.snake_width, self.settings.snake_height))
self.skin.fill(self.settings.snake_color)
#Lista que armazena a posição da cobra
self.pos = [(settings.screen_width//2, settings.screen_height//2),
(settings.screen_width//2 + 10, settings.screen_height//2),
(settings.screen_width//2 + 20, settings.screen_height//2)]
#Direção inicial da cobra
self.snake_direction = "down" |
2a66adf329dc2feaad9df713bbe57ea20317960d | madhatter1069/terminal-connect-four | /connectfour_functions.py | 3,065 | 4 | 4 | ##Jared Clark 76551956 and Jack Callahan 37163374
import connectfour
def create_game():
'''creates a new game and game board.'''
this_game=connectfour.new_game()
return this_game
def use_drop(gamestate: connectfour.GameState, col_num: int):
'''takes the game move and uses the drop function'''
gamestate=connectfour.drop(gamestate, col_num)
return gamestate
def use_pop(gamestate: connectfour.GameState, col_num: int):
'''takes the game move and uses the pop function'''
game_state=connectfour.pop(gamestate, col_num)
return game_state
def game_move(gamestate: connectfour.GameState):
'''ask the user to type their game move'''
game_move=input(_players_turn(gamestate))
return game_move.upper()
def column_number(move: str):
'''takes the game move and returns the column number and converts it to an int'''
if move.startswith('DROP '):
column_number=int(move[4:].strip())-1
return column_number
elif move.startswith('POP'):
column_number=int(move[3:].strip())-1
return column_number
def _printed_column_numbers():
'''prints the number of each column above the play board'''
col_num=0
for col_num in range(connectfour.BOARD_COLUMNS):
print(f' {col_num+1} ', end='')
print()
def create_board():
''' prints a blank board at the start of every game'''
_printed_column_numbers()
for row in range(connectfour.BOARD_ROWS):#for each row in T
for column in range(connectfour.BOARD_COLUMNS): # for each column in this row
print(' • ', end="")
print()
######################################VVVVVVVVVDONT TOUCH EVER!!!!!!!!!!!!!!!!!!!!!!!#############
def show_played_pieces(board:connectfour.GameState):
'''prints the board part of the gamestate tuple in the correct print out'''
_printed_column_numbers()
for row in range(connectfour.BOARD_ROWS):
for column in range(connectfour.BOARD_COLUMNS):
if board.board[column][row]==1:
print(' R ',end='')
elif board.board[column][row]==2:
print(' Y ',end='')
else:
print(' O ',end='')
print()
######################################^^^^^^^^^^DONT TOUCH EVER!!!!!!!!!!!!!!!!!!!!!!!#############
def print_winner(game_state: connectfour.GameState):
'''checks if there is a winner of the game yet and prints who it is if there is.'''
if connectfour.winner(game_state)==0:
return
elif connectfour.winner(game_state)==1:
print('WINNER: RED')
return
elif connectfour.winner(game_state)==2:
print('WINNER: YELLOW')
return
def _players_turn(game_state: connectfour.GameState):
'''gives the color of who's turn it is.'''
turn=''
if game_state.turn==1:
turn='RED: '
elif game_state.turn==2:
turn='YELLOW: '
return turn
def end_game(game_state: connectfour.GameState):
if connectfour.winner(game_state)!=0:
return False
|
2889144f0532f20229cec0b7e481cb210f1aa9de | BrianFreeman0620/Movie_Database | /Movie Database.py | 10,819 | 4.125 | 4 | # Imports the needed code to open excel files, create graphics windows, and
# quickly run math equations
import pandas as pd
from graphics import *
from math import *
# Finds the distance between two objects given two lists of numbers
def minkowskiDist(v1,v2,p):
sumOfV = 0
for value in range(len(v1)):
try:
sumOfV += (abs(float(v1[value]) - float(v2[value]))) ** p
except:
pass
minkowskiValue = sumOfV ** (1/p)
return minkowskiValue
# Using the minkowski distance, finds the closest [number] of movies
def nearestMovies(new, feature, number):
similarMovies = []
for i in range(number):
minimum = "none"
for vector in feature:
if new == feature[vector]:
pass
elif vector in similarMovies:
pass
else:
if minimum == "none":
minimum = minkowskiDist(new, feature[vector], 2)
neighbor = vector
elif minimum > minkowskiDist(new, feature[vector], 2):
minimum = minkowskiDist(new, feature[vector], 2)
neighbor = vector
similarMovies.append(neighbor)
if i == 0:
nearestMovie = neighbor
return similarMovies, nearestMovie
# Checks if a button is clicked in the graphics window
def clicked(button,p):
c=button.getCenter()
r=button.getRadius()
return sqrt((p.getX()-c.getX())**2+(p.getY()-c.getY())**2) < r
def main():
# Imports the data from the excel file Move Data.xlsx
infile = pd.read_excel('Movie Data.xlsx', 'Sheet1')
tryMovie = "yes"
# Creates lists for all values in the list by type
movieList = []
budgetList = []
criticList = []
audienceList = []
salesList = []
# Adds the data to the five lists
for movie in infile["Name of Movie"]:
movieList.append(movie)
for budget in infile["Budget (Millions)"]:
budgetList.append(budget)
for critic in infile["Critic Score"]:
criticList.append(critic)
for audience in infile["Audience Score"]:
audienceList.append(audience)
for sales in infile["Box Office (Millions)"]:
salesList.append(sales)
movieDict = {}
movieListCount = 0
# Adds the data into the dictionary movieDict to easily be able to refer
# to later
for movie in movieList:
movieDict[movie] = [budgetList[movieListCount],
criticList[movieListCount], audienceList[movieListCount],
salesList[movieListCount]]
movieListCount += 1
# Creates the graphics window and text explaining what the program does
win = GraphWin("Brian Freeman Final Project", 1000, 500)
words = Text(Point(500,100),"""Using the data from hundreds of movies, this program will be able to predict the box office in millions of dollars \n
of a hypothetical movie given its budget, critic scores, and audience scores. \n
Warning! Budgets above 200 million dollars may be less accurate due to the limited of real movies \n
above that amount \n
Also, the run button may need to be clicked multiple times to work""")
words.setSize(8)
words.draw(win)
# Asks the user for a hypothetical budget for a movie
inputBudgetBox = Entry(Point(600,300),10)
inputBudgetBox.setFill("white")
inputBudgetBox.setTextColor("green")
inputBudgetBox.draw(win)
inputBudgetText = Text(Point(300,300), "In millions of dollars, what is the budget of the movie?")
inputBudgetText.draw(win)
# Asks the user for a hypothetical critic score for a movie
inputCriticBox = Entry(Point(600,350),10)
inputCriticBox.setFill("white")
inputCriticBox.setTextColor("red")
inputCriticBox.draw(win)
inputCriticText = Text(Point(300,350), "From 0-100, what is the critic score for the movie?")
inputCriticText.draw(win)
# Asks the user for a hypothetical audience score for a movie
inputAudienceBox = Entry(Point(600,400),10)
inputAudienceBox.setFill("white")
inputAudienceBox.setTextColor("blue")
inputAudienceBox.draw(win)
inputAudienceText = Text(Point(300,400), "From 0-100, what is the audience score for the movie?")
inputAudienceText.draw(win)
# Creates the button that compares inserted data to the dictionary's data
clickCircle = Circle(Point(600,450),25)
clickCircle.setFill("green")
clickCircle.draw(win)
clickCircleText = Text(Point(600,450),"Run")
clickCircleText.draw(win)
# Creates a film reel and draws it in the winow
movieBase = Circle(Point(150,150), 75)
movieBase.setFill("Black")
movieBase.draw(win)
movieFilm = Polygon([Point(225,150), Point(200,175), Point(250,225), Point(275,200)])
movieFilm.setFill("Black")
movieFilm.draw(win)
movieHole1 = Circle(Point(200,150), 10)
movieHole1.setFill("white")
movieHole1.draw(win)
movieHole2 = Circle(Point(150,200), 10)
movieHole2.setFill("white")
movieHole2.draw(win)
movieHole3 = Circle(Point(100,150), 10)
movieHole3.setFill("white")
movieHole3.draw(win)
movieHole4 = Circle(Point(150,100), 10)
movieHole4.setFill("white")
movieHole4.draw(win)
movieHole5 = Circle(Point(185,185), 10)
movieHole5.setFill("white")
movieHole5.draw(win)
movieHole6 = Circle(Point(115,185), 10)
movieHole6.setFill("white")
movieHole6.draw(win)
movieHole7 = Circle(Point(185,115), 10)
movieHole7.setFill("white")
movieHole7.draw(win)
movieHole8 = Circle(Point(115,115), 10)
movieHole8.setFill("white")
movieHole8.draw(win)
# Makes sure the program runs until the user decides to quit
while tryMovie == "yes":
p = win.getMouse()
while not clicked(clickCircle, p):
p = win.getMouse()
# Receives information from the text boxes
inputBudget = float(inputBudgetBox.getText())
inputCritic = float(inputCriticBox.getText())
inputAudience = float(inputAudienceBox.getText())
inputMovie = [inputBudget, inputCritic, inputAudience]
sumOfBoxOffice = 0
count = 0
# Checks if the budget is less than 250 million dollars
if inputBudget <= 250:
# Finds the closest movies and gives it more weight than the next
# closest
similarMovies, nearestMovie = nearestMovies(inputMovie, movieDict, 20)
for movie in similarMovies:
sumOfBoxOffice += (2 ** (20 - count)) * movieDict[movie][3]
count += 1
estimatedBoxOffice = round(sumOfBoxOffice/2097151, 2)
else:
# Finds the three lines of best fit using the audience score, budget,
# and critic score
# When there are two capital letters, it is multiplying the
# corresponding values together, ie CB is critic score times budget
similarMovies, nearestMovie = nearestMovies(inputMovie, movieDict, 1)
sumOfBudget = 0
sumOfBsquare = 0
sumOfBB = 0
sumOfCritic = 0
sumOfCsquare = 0
sumOfCB = 0
sumOfAudience = 0
sumOfAsquare = 0
sumOfAB = 0
for movie in movieDict:
sumOfBudget += movieDict[movie][0]
sumOfCritic += movieDict[movie][1]
sumOfAudience += movieDict[movie][2]
sumOfBsquare += (movieDict[movie][0]) ** 2
sumOfCsquare += (movieDict[movie][1]) ** 2
sumOfAsquare += (movieDict[movie][2]) ** 2
sumOfBB += movieDict[movie][0] * movieDict[movie][3]
sumOfCB += movieDict[movie][1] * movieDict[movie][3]
sumOfAB += movieDict[movie][2] * movieDict[movie][3]
sumOfBoxOffice += movieDict[movie][3]
count += 1
aB = ((sumOfBoxOffice * sumOfBsquare) - (sumOfBudget * sumOfBB)) / ((count * sumOfBsquare) - (sumOfBudget ** 2))
aC = ((sumOfBoxOffice * sumOfCsquare) - (sumOfCritic * sumOfCB)) / ((count * sumOfCsquare) - (sumOfCritic ** 2))
aA = ((sumOfBoxOffice * sumOfAsquare) - (sumOfAudience * sumOfAB)) / ((count * sumOfAsquare) - (sumOfAudience ** 2))
bB = ((count * sumOfBB) - (sumOfBudget * sumOfBoxOffice)) / ((count * sumOfBsquare) - (sumOfBudget ** 2))
bC = ((count * sumOfCB) - (sumOfCritic * sumOfBoxOffice)) / ((count * sumOfCsquare) - (sumOfCritic ** 2))
bA = ((count * sumOfAB) - (sumOfAudience * sumOfBoxOffice)) / ((count * sumOfAsquare) - (sumOfAudience ** 2))
boxBudget = aB + (bB * inputBudget)
boxCritic = aC + (bC * inputCritic)
boxAudience = aA + (bA * inputAudience)
# The budget is given more weight over the critic and audience scores
estimatedBoxOffice = round((5/9 * boxBudget) + (2/9 * (boxCritic + boxAudience)), 2)
# The calculated box office and related information is printed in the
# graphics window
results = "The estimated box office is \n$" + str(estimatedBoxOffice) + " million dollars"
boxOfficeResults = Text(Point(800, 350), results)
boxOfficeResults.draw(win)
closestMovieStr = "The closest movie is " + str(nearestMovie) + "\nwith budget of $"+ str(movieDict[nearestMovie][0]) + " million \nand scores of " + str(movieDict[nearestMovie][1])+ " and "+ str(movieDict[nearestMovie][2])
closestMovie = Text(Point(750, 250),closestMovieStr)
closestMovie.draw(win)
# Changes the color and funtion of the buttons to run again
clickCircle.undraw()
clickCircleText.undraw()
clickCircle = Circle(Point(600,450),25)
clickCircle.setFill("red")
clickCircle.draw(win)
clickCircleText = Text(Point(600,450),"Clear")
clickCircleText.draw(win)
# Allows the user to input new values
p = win.getMouse()
boxOfficeResults.undraw()
clickCircle.undraw()
clickCircleText.undraw()
closestMovie.undraw()
clickCircle = Circle(Point(600,450),25)
clickCircle.setFill("green")
clickCircle.draw(win)
clickCircleText = Text(Point(600,450),"Run")
clickCircleText.draw(win)
main() |
2087d9cd98007d836cd39520f3acbc41edbafe77 | fragoso988/treinos_python | /PythonExercicios/aula010.py | 3,362 | 4.125 | 4 | import random
from datetime import date
print("Desafio 028")
print("""\nEscreva um programa que faça o computador pensar em um número inteiro entre 0 e 5.
Peça para o usuário descobrir qual o número.\n""")
sorteio = random.randint(0,5)
n = int(input("Digite um número de 0 a 5: "))
if(n == sorteio):
print("Parabéns, você acertou!")
else:
print("Você errou, você escolheu o número {} e o número certo era {}." .format(n, sorteio))
print("\nDesafio 029")
print("""Escreva um programa que leia a velocidade de um carro.
Se ele ultrapassar 80Km/h mostre uma mensagem dizendo que ele foi multado.
A multa vai custar R$7,00 por cada km acima do limite.\n""")
velocidade = float(input("Digite a velocidade: "))
if (velocidade > 80):
print("Você ultrapassou o limite de 80Km/h, dirigindo a {}." .format(velocidade))
multa = (velocidade - 80) * 7.00
print("Você deverá pagar uma multa de R${:.2f}." .format(multa))
else:
print("Você passou dentro do limite de velocidade.")
print("\nDesafio 030")
print("""Cria um programa que leia um número inteiro e mostre na tela se ele é par ou impar""")
n = int(input("Digite um número: "))
if ((n % 2)==0):
print("O número é par.")
else:
print("O número é impar.")
print("\nDesafio 031")
print("""Desenvolva um programa que pergunte a distancia de uma viagem em KM.
Para viagens até 200Km, cobre a passagem por R$0.50 o Km.
Acima de 200Km cobre R$0.45""")
km = float(input("Quantos Km será a viagem: "))
if (km <= 200):
valor = km * 0.50
print("O valor da viagem será de R${:.2f}" .format(valor))
else:
valor = km * 0.45
print("O valor da viagem será de R${:.2f}." .format(valor))
print("""\nDesafio 032
Faça um programa que leia um ano qualquer e mostre se ele é bissexto""")
ano = int(input('\nQue ano quer analisar? Coloque 0 para o ano atual. '))
if ano == 0:
ano = date.today().year
if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0:
print("O ano {} é BISSEXTO" .format(ano))
else:
print("O ano {} NÃO é BISSEXTO" .format(ano))
print("""\nDesafio 033
Faça um programa que leia 3 números e mostre qual é o maior e qual o menor.""")
n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite o segundo número: "))
n3 = int(input("Digite o terceiro número: "))
lista = (n1, n2, n3)
maior = max(lista)
menor = min(lista)
print("O maior número é {} e o menor número é {}." .format(maior, menor))
print("""\nDesafio 034
Escreva um programa que aumente o salário de um funcionário em 10% caso os salário seja acima de R$1250,00.
Caso seja maior ou igual, o aumento deve ser de 15%\n""")
salario = float(input("Digite o salário: "))
if (salario > 1250):
aumento = (salario * 0.10) + salario
porcentagem = 10
else:
aumento = (salario * .15) + salario
porcentagem = 15
print("Seu salário é de R${}, então terá um aumento de {}%. Passando agora a ser R${:.2f}". format(salario, porcentagem, aumento))
print("\nDesafio 35")
print("Analizador de triangulo")
r1 = float(input("Digite o primeiro segmento: "))
r2 = float(input("Digite o segundo segmento: "))
r3 = float(input("Digite o terceiro segmento: "))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print("Os segmentos podem formar triangulo!")
else:
print("Os segmentos não podem formar triangulo.")
|
7b2d0547005a77626a4cfff28b48986ed2cbf173 | jasonsinger16/PFB2017_problemsets | /Python_probset6/ps6_02.py | 512 | 3.75 | 4 | #!/usr/bin/env python
# Substitute every occurrence of "Nobody" in the file 'Python_06_nobody.txt' with "Catherine"
# Write an output file with Catherine's name ==> Catherine.txt
poem_file = open('Python_06_nobody.txt', 'r')
poem_subbed = open('Python_06_Catherine.txt', 'w')
poem_text = poem_file.read()
poem_text_subbed = poem_text.replace("Nobody","Catherine")
poem_subbed.write(poem_text_subbed)
poem_file.close()
poem_subbed.close()
print("Wrote 'Python_06_Catherine.txt'")
#print(poem_text_subbed)
|
d9499db129b557c05f1045aff9f9bde1dcd23689 | JWKennington/apsjournals | /apsjournals/util.py | 924 | 4.03125 | 4 | """Miscellaneous utilities
"""
import datetime
def month_name_to_num(m: str):
"""Convert a month name to a number
Args:
m:
str, the name of the month
Returns:
int, the month number
"""
return datetime.datetime.strptime(m, '%B').month
def parse_start_end(tr: str):
"""Parse the start and end date from a string
Args:
tr:
str, the time range
Returns:
Tuple[datetime.date, datetime.date]
"""
start, end = tr.split(' - ')
if end == 'Present':
year = datetime.date.today().year
end = datetime.date(year, datetime.date.today().month, 1)
start = datetime.date(year, month_name_to_num(start), 1)
else:
year = int(end.split(' ')[-1])
end = datetime.date(year, datetime.date.today().month, 1)
start = datetime.date(year, month_name_to_num(start), 1)
return start, end
|
4eb6f5915ba650f59edbea6f877be1a9b9885884 | TatsuLee/pythonPractice | /leet/l110.py | 701 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def dfs(self, root, d):
if root is None:
return d, True
dl, flag = self.dfs(root.left, d+1)
if not flag:
return dl, False
dr, flag = self.dfs(root.right, d+1)
if not flag:
return dr, False
return max(dl, dr), abs(dl-dr) < 2
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
return self.dfs(root, 0)[1]
|
417a0f3ccc24b2a5aa2d9d009b5ba06c6c8fec42 | zeroam/dev-study | /d20200507/simple_server.py | 905 | 3.53125 | 4 | import socket
HOST = "127.0.0.1"
PORT = 9000
RESPONSE = b"""\
HTTP/1.1 200 OK
Content-type: text/html
Content-length: 14
<h1>Hello</h1>"""
# AF_INET(ipv4 주소를 사용하는, IP), SOCK_STREAM(연결형 통신, TCP)의 소켓 생성 => TCP/IP 소켓 생성
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 해당 소켓을 재사용할 수 있도록 옵션 설정
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 소켓의 IP 주소 및 포트 설정
server_socket.bind((HOST, PORT))
# 최대 1개 까지 connection(연결) 유지
server_socket.listen(1)
print(f"Listening on {HOST}:{PORT}")
while True:
client_connection, client_address = server_socket.accept()
print(f"New connection from {client_address}")
# RESPONSE 데이터 전달
client_connection.sendall(RESPONSE)
# 해당 소켓과 접속 끊음
client_connection.close()
|
a57c94fa53980ea1beb6c8641a46f8976f3a67ae | violenttestpen/DataStructureAlgorithms | /Sort/InsertionSort.py | 420 | 3.765625 | 4 | # insertion sort [O(n**2)]
def isort(array):
a = array[:]
# start from the second element
for i in range(1, len(array)):
# move left
x = i - 1
while x >= 0:
if a[x] > a[x + 1]:
a[x], a[x + 1] = a[x + 1], a[x]
else:
# all previous elements are assumed to be sorted already
break
x -= 1
return a
|
afeccaf1f7d9b2c317c0c63fb773258d162ef865 | CaptainLazarus/Python-Assignments | /Ass 3/10.py | 374 | 4.0625 | 4 | from statistics import median
size = int(input("Enter the size of array "))
arr = []
for i in range(size):
ele = int(input())
arr.append(ele)
mean = sum(arr)/len(arr)
Median = median(arr)
count_ = 0
for i in arr:
if arr.count(i) > count_:
count_ = arr.count(i)
k = i
mode = k
print("The Mean , Median , Mode are {} ,{} ,{} respectively".format(mean,Median,mode)) |
3fa17260900582b293669ff40af5cd895f065504 | iamslash/examplesofml | /keras/basic.py | 553 | 3.625 | 4 | # regression ANN example
def main(_epochs):
import keras
import numpy
x = numpy.array([0, 1, 2, 3, 4])
y = 2 * x + 1
model = keras.models.Sequential()
model.add(keras.layers.Dense(1, input_shape=(1,)))
model.compile('SGD', 'mse')
model.fit(x[:3], y[:3], epochs=2000, verbose=0)
print("Tgts: ", y[3:])
print("Pred: ", model.predict(x[3:]).flatten())
if __name__ == '__main__':
import sys
if len(sys.argv) != 2:
print('USAGE) python basic.py [epochs]')
sys.exit()
main(sys.argv[1]) |
4943825d62e9cb7d007ebd047e8764482335c4e7 | ivanoel/db.sqlite3 | /dbprecos.py | 1,246 | 3.65625 | 4 | #!/usr/bin/python3
# __autor__ == '__Ivanoel__'
# Banco de Dados SQLite, tem varias funções e objetos que acessam o banco.
import sqlite3
# criamos o .db
conexao = sqlite3.connect('preços.db')
# cursores são objetos utilizados para enviar comandos e
# receber resultados do db chamando o método cursor().
cur = conexao.cursor()
# vamos criar uma tabela chamada preços o comando usando do sql eh create.
cur.execute('''create table preços(
nomeP text,
precoP text)
''')
# o método execute enviar o comando ao banco de dados (db).
# o comando insert precisa da tabela onde vai ser inseridos os dados e
# tbm do nome do campos respectivos valores.
# (into) faz parte do comando insert, eh escrito antes da tabela.
# Os valores que vamos inserir na tabela sao especificos tbm entre parenteses
# na segunda parte do comando insert que começa apos a palavra (values).
cur.execute('''
insert into preços(nomeP, precoP)
values(?, ?)
''', ("Arroz", "4.50"))
# irão substituir as interrogações qndo for executado
# commit eh uma opração que modificar o db.
conexao.commit()
# (close) fechamos cursor e conexao com o db.
cur.close()
conexao.close()
|
d3f360c479692ac45265ba823044b69e9b58b613 | Taoge123/OptimizedLeetcode | /LeetcodeNew/python/LC_363.py | 2,899 | 3.859375 | 4 |
"""
560. Subarray Sum Equals K
974. Subarray Sums Divisible by K
325. Maximum Size Subarray Sum Equals k
1074. Number of Submatrices That Sum to Target
363. Max Sum of Rectangle No Larger Than K
"""
"""
Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k.
Example:
Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
Explanation: Because the sum of rectangle [[0, 1], [-2, 3]] is 2,
and 2 is the max number no larger than k (k = 2).
Note:
The rectangle inside the matrix must have an area > 0.
What if the number of rows is much larger than the number of columns?
"""
"""
0 1 2 3 4
0 2 1 -3 -4 5
1 0 6 3 4 1
2 2 -2 -1 4 -5
3 -3 3 1 0 3
0- 2 3 0 -4 1
1- 0 6 9 13 14
2- 2 0 -1 3 -2
3--3 0 1 1 4
L
R
currSum
maxSum
maxLeft
maxRight
maxUp
maxDown
"""
import bisect
class SolutionBetter:
def maxSumSubmatrix(self, matrix, k):
m, n = len(matrix), len(matrix[0])
res = float('-inf')
for left in range(n):
nums = [0] * m
for right in range(left, n):
for i in range(m):
nums[i] += matrix[i][right]
res = max(res, self.kadane(nums, k))
return res
def kadane(self, nums, k):
curSum, maxSum = 0, float('-inf')
dp = [0]
for i, num in enumerate(nums):
curSum += num
idx = bisect.bisect_left(dp, curSum - k)
if idx != len(dp):
maxSum = max(maxSum, curSum - dp[idx])
bisect.insort(dp, curSum)
return maxSum
class SolutionTLE:
def maxSumSubmatrix(self, matrix, k):
if not matrix or not matrix[0]:
return 0
curSum, maxSum = float('-inf'), float('-inf')
M, N = len(matrix), len(matrix[0])
for left in range(N):
curArr = [0] * M
for right in range(left, N):
for m in range(M):
curArr[m] += matrix[m][right]
curSum = self.getSumArray(curArr, M, k)
if curSum > maxSum:
maxSum = curSum
return maxSum
def getSumArray(self, arr, M, k):
sums = [0] * (M + 1)
for i in range(M):
sums[i + 1] = arr[i] + sums[i]
res = float('-inf')
for i in range(M):
for j in range(i + 1, M + 1):
curSum = sums[j] - sums[i]
if curSum <= k and curSum > res:
res = curSum
return res
# matrix = [[1,0,1],[0,-2,3]]
# k = 2
# matrix = [[2, 1,-3,-4, 5],
# [0, 6, 3, 4, 1],
# [2,-2,-1, 4,-5],
# [-3, 3, 1, 0, 3]]
# k = 100
# matrix = [[2],[0],[3],[4],[4]]
# k = 4
matrix = [[1,0,1],[0,-2,3]]
k = 2
a = SolutionBetter()
print(a.maxSumSubmatrix(matrix, k))
|
654b003cf635c2503ded7dd2acb2d34c7974616f | cahern10/openAsset | /sectionA/Exercise1/magickWrapper.py | 1,619 | 3.9375 | 4 | import subprocess
import os
import sys
"""
validateInputPath checks to see if the input path
provided by the user is valid
:param inputPath: contains the string of the path
:return: passes back true if the function does not error out
"""
def validateInputPath(inputPath):
if not os.path.exists(inputPath):
print('input file does not exist!')
sys.exit(2)
return True
"""
getCMD validates and builds the arguements in order to
return the command to run magick
:param argv: contains the command line arguements
:return: passes back the command if the function does not error out
"""
def getCMD(argv):
cmd = ''
if ( len(argv) == 2 and validateInputPath(argv[0])):
cmd = 'magick convert ' + str(argv[0]) + ' ' + str(argv[1])
elif ( len(argv) == 4 and validateInputPath(argv[0])):
cmd = 'magick convert ' + str(argv[0]) + ' -resize ' + str(argv[3]) + ' ' + str(argv[1])
else:
print ('Number of input parameters are not correct. Please enter as: ')
print ('python magickWrapper.py <inputfile.jpeg> <outputfile> OR')
print ('python magickWrapper.py <inputfile.jpeg> <outputfile> -resize <value>')
sys.exit(2)
return cmd
"""
processCommand runs the magickwrapper command build above
:param cmd: contains the string command to run
"""
def processCommand(cmd):
try:
subprocess.call(cmd, shell=True)
print('Command processed and completed')
except:
print('command failed :(')
def main(argv):
cmd = getCMD(argv)
processCommand(cmd)
if __name__ == "__main__":
main(sys.argv[1:]) |
1c6432116f4ee180bd54cdac8d79a7a696495983 | ZhouPan1998/DataStructures_Algorithms | /pythonds/trees/binary_tree.py | 2,087 | 4.0625 | 4 | # -*- coding: utf-8 -*-
from typing import Union
class BinaryTree:
"""二叉树"""
def __init__(self, item=None):
self.__data = item
self.__left = None
self.__right = None
@property
def data(self):
return self.__data
@data.setter
def data(self, item):
self.__data = item
@property
def left_child(self) -> Union["BinaryTree", None]:
return self.__left
@left_child.setter
def left_child(self, node: Union["BinaryTree", None]):
self.__left = node
@property
def right_child(self) -> Union["BinaryTree", None]:
return self.__right
@right_child.setter
def right_child(self, node: Union["BinaryTree", None]):
self.__right = node
def insert_left(self, item=None):
node = BinaryTree(item)
if self.left_child is not None:
node.left_child = self.left_child
self.left_child = node
def insert_right(self, item=None):
node = BinaryTree(item)
if self.right_child is not None:
node.right_child = self.right_child
self.right_child = node
# 外部前序遍历(递归实现)
def preorder(tree: BinaryTree):
if tree is None:
return
print(tree.data, end=' ')
preorder(tree.left_child)
preorder(tree.right_child)
# 外部中序遍历(递归实现)
def inorder(tree: BinaryTree):
if tree is None:
return
inorder(tree.left_child)
print(tree.data, end=' ')
inorder(tree.right_child)
# 外部后序遍历(递归实现)
def postorder(tree: BinaryTree):
if tree is None:
return
postorder(tree.left_child)
postorder(tree.right_child)
print(tree.data, end=' ')
if __name__ == '__main__':
tree = BinaryTree('a')
print(tree.data)
print(tree.left_child)
tree.insert_left('b')
print(tree.left_child)
print(tree.left_child.data)
tree.insert_right('c')
print(tree.right_child)
print(tree.right_child.data)
tree.right_child.data = 'hello'
print(tree.right_child.data)
|
063a730e4a036736c290b9436d681770d38e39f9 | shubin-denis/algorithms-and-data-structures-Python | /Lesson_1/Task_9.py | 491 | 4.34375 | 4 | # Вводятся три разных числа. Найти, какое из них является средним
# (больше одного, но меньше другого).
x = int(input('первое число: '))
y = int(input('второе число: '))
z = int(input('третье число: '))
if z > x > y:
print(f'Среднее число: {x}')
elif z > y > x:
print(f'Среднее число: {y}')
else:
print(f'Среднее число: {z}')
|
52b8cbd54306de4652462476fcff8e1dc36ba3e9 | tonumikk/Learn-Python | /ex21.py | 1,159 | 4.15625 | 4 | def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d /%d" % (a, b)
return a /b
print "Let's do some math with just functions!"
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes: ", what, "Can you do it my hand?"
# Figuring out the puzzle
# First we add two values age and the other value
divide1 = divide(iq, 2)
multiply1 = multiply(weight, divide1)
subtract1 = subtract(height, multiply1)
what_new = add(age, subtract1)
print "Let's see if this does it: ", what_new
# Let's create a different formula ... Let's make it height divided by age plus weight
new_what = add(divide(height, age), weight)
print "Let's now print the new formula: ", new_what
|
1021f155bedec8c20327ee238d47ab9d61083304 | MiniOK/companyone | /src/scripts/conversion/shutil_test.py | 749 | 3.59375 | 4 | # 文件复制
# -*- coding:utf-8 -*-
import shutil
# file_path = r"C:\Users\miniloveliness\Desktop\test_code\test.txt"
# new_path = r"C:\Users\miniloveliness\Desktop\new.txt"
# shutil.copyfileobj(open(file_path, 'r', encoding='utf-8'), open(new_path, 'w', encoding='utf-8'))
# class EvaException(BaseException):
# # def __init__(self,msg):
# # self.msg=msg
# # def __str__(self):
# # return self.msg
# #
# # try:
# # raise EvaException('类型错误')
# # except EvaException as e:
# # print(e)
if __name__ == '__main__':
with open('../output/finish.txt', 'w', encoding='utf-8') as finish:
print(finish)
print('1111111111111111')
finish.write('1111\n')
finish.write('1111')
|
7dce2978078f533ef5fbde4d0938fa6559b8da08 | lbrusaoconnell/Python-Server-Practice | /c.py | 4,619 | 3.53125 | 4 | import socket
import threading
import time
import turtle
HEADER = 64
PORT = 2021
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
#SERVER = '47.149.222.226'
SERVER = '192.168.1.56'
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
print(client.recv(2048).decode(FORMAT))
def generate_board():
#screen size
screen_width = 800
screen_length = 800
#side length of each square
square_size = 80
#how many squares there are per lane
lane_length = 8
#how many lanes there are (since we want the board to be a square, the amount of lanes is equal to the amount of squares per lane)
lanes = lane_length
#makes the window
wn = turtle.Screen()
wn.bgcolor("lightgreen")
wn.setup(width=screen_width, height=screen_length)
wn.tracer(0)
#creates the turtle
pen = turtle.Turtle()
pen.penup()
pen.goto(-((square_size * lane_length)/2),((square_size * lane_length)/2))
pen.pendown()
#makes the turtle go foward "square_length" units and then turn 90 degrees 4 times to make a square
def box():
for i in range(4):
pen.forward(square_size)
pen.right(90)
#creates the board with all the squares
def board():
#sets the x and y coordinates to half the size of the board
#Which is found by multiplying the size of each square by how many squares there are per column and dividing it by 2
x = -((square_size * lane_length)/2)
y = (square_size * (lane_length / 2))
count = 0
#makes a horizontal column then lower the y value of the turtle so that it can create another column directly underneath the first
for k in range(lanes):
#makes a box "lane_length" amounts of times, and moves them over one box size each time so that they're created lined up next to each other
for j in range(lane_length):
#changes the count from even to odd or odd to even every time a box is created
count += 1
#makes different squares black or white
pen.begin_fill()
if (int(count) % 2) == 0:
pen.fillcolor("black")
else:
pen.fillcolor("white")
box()
pen.end_fill()
#moves the turtle to the right one box length
x += square_size
pen.penup()
pen.goto(x,y)
pen.pendown()
#adds one so that the pen filling pattern alternates
count += 1
#brings the turtle back to the far left side of the board and lowers it one column
x = -((square_size * lane_length)/2)
y -= square_size
pen.penup()
pen.goto(x,y)
pen.pendown()
#creates the turtle
quadrants = turtle.Turtle()
quadrants.hideturtle()
quadrants.penup()
#writes A-H and 1-8 on horizontal axis and the vertical axis respectively
def x_axis_letters():
y = -372
x = -292
counter = 0
letters = ["A", "B", "C", "D", "E", "F", "G", "H"]
for a in range(8):
quadrants.goto(x, y)
quadrants.write(letters[counter], font=("Arial", 30, "normal"))
x += 80
counter += 1
def y_axis_numbers():
x2 = -355
y2 = 257
counter2 = 0
numbers = ["8", "7", "6", "5", "4", "3", "2", "1"]
for b in range(8):
quadrants.goto(x2, y2)
quadrants.write(numbers[counter2], font=("Arial", 30, "normal"))
y2 -= 80
counter2 += 1
#executes the function, board
board()
x_axis_letters()
y_axis_numbers()
#gets the mouse coordinates on click
def get_mouse_click_coor(x, y):
global square_coord
chessX = " "
chessY = " "
mouse_x = x
mouse_y = y
#print(mouse_x, mouse_y)
if (mouse_x in range(-320, -240)):
chessX = "A"
if (mouse_x in range(-240, -160)):
chessX = "B"
if (mouse_x in range(-160, -80)):
chessX = "C"
if (mouse_x in range(-80, 0)):
chessX = "D"
if (mouse_x in range(0, 80)):
chessX = "E"
if (mouse_x in range(80, 160)):
chessX = "F"
if (mouse_x in range(160, 240)):
chessX = "G"
if (mouse_x in range(240, 320)):
chessX = "H"
if (mouse_y in range(-320, -240)):
chessY = "1"
if (mouse_y in range(-240, -160)):
chessY = "2"
if (mouse_y in range(-160, -80)):
chessY = "3"
if (mouse_y in range(-80, 0)):
chessY = "4"
if (mouse_y in range(0, 80)):
chessY = "5"
if (mouse_y in range(80, 160)):
chessY = "6"
if (mouse_y in range(160, 240)):
chessY = "7"
if (mouse_y in range(240, 320)):
chessY = "8"
if not (" " in chessX + chessY):
square_coord = chessX + chessY
send(square_coord)
turtle.onscreenclick(get_mouse_click_coor)
turtle.mainloop()
generate_board() |
60bf40eb3cb1e04260a0699ace274cb46441f0c7 | GabrielBrotas/Python | /modulo 2/Exercicios/Ex059 - Menu de opcoes.py | 1,064 | 4.0625 | 4 | # prpgrama que leia 2 valores e mostre um menu na tela
# 1 somar, 2 multiplicar, 3 maior, 4 menor e 5 sair
n1 = int(input('valor 1: '))
n2 = int(input('valor 2: '))
c = 0
s = 0
print('''numero 1 = {} e numero 2 = {}. Qual operacao realizar?'
[1] soma
[2] multiplicacao
[3] maior
[4] menor
[5] sair'''.format(n1, n2))
while c != 5:
c = int(input('Digite a operacao: '))
if c == 1:
s = n1 + n2
print('A soma de n1 e n2: ', s)
elif c == 2:
m = n1 * n2
print('A multiplicacao de n1 e n2: ', m)
elif c == 3:
if n1 > n2:
print('O maior numero: ', n1)
elif n2 > n1:
print('O maior numero: ', n2)
else:
print('Os numeros sao iguais')
elif c == 4:
if n1 < n2:
print('O menor numero: ', n1)
elif n2 < n1:
print('O menor numero: ', n2)
else:
print('Os numeros sao iguais')
elif c == 5:
print('EXIT')
else:
print('Digite uma opcao valida')
|
dc07a8eb340dde953c1ffbef42622b6f05f0fab9 | rfk/autoself | /autoself/testmeta.py | 443 | 3.515625 | 4 |
import autoself
__metaclass__=autoself.autoself
class Test1:
def __init__(color,size):
self.color = color
self.size = size
def show():
print "I am a " + self.size + ", " + self.color + " thing"
def myclass():
return cls
t = Test1("blue","big")
if not t.color == "blue":
raise ValueError()
if not t.size == "big":
raise ValueError()
if not t.myclass() == Test1:
raise ValueError()
|
8ca0ea303b0fb3e9ca96723fc4556d14e517ac6d | bawuju/LeetcodeSolution | /python/599.py | 1,881 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
class Solution(object):
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
index_sum = -1
result = []
map1 = {}
for index in range(len(list1)):
map1[list1[index]] = index
for index in range(len(list2)):
c = list2[index]
if c not in map1.keys():
continue
sum_loop = map1[c] + index
if index_sum == -1:
index_sum = sum_loop
result.append(c)
continue
if sum_loop > index_sum:
continue
elif sum_loop == index_sum:
result.append(c)
else:
index_sum = sum_loop
result.clear()
result.append(c)
return result
if __name__ == '__main__':
assert Solution().findRestaurant(["Shogun", "Tapioca Express", "Burger King", "KFC"],
["KFC", "Shogun", "Burger King"]) == ["Shogun"]
assert Solution().findRestaurant(["Shogun", "Tapioca Express", "Burger King", "KFC"],
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]) == [
"Shogun"]
assert Solution().findRestaurant(["Shogun", "Tapioca Express", "Burger King", "KFC"],
["KFC", "Burger King", "Tapioca Express", "Shogun"]) == ["KFC", "Burger King",
"Tapioca Express",
"Shogun"]
assert Solution().findRestaurant(["k", "KFC"], ["k", "KFC"]) == ["k"]
|
65974ea3211a2b1dc8e8fccf44d484d4d9f7ae17 | Andromeda2333/ImageProcessing | /Demo_6_17_2014/test/test_thread_1.py | 1,268 | 3.8125 | 4 | #coding=utf-8
'''
Created on 2014年7月12日
@author: lenovo
'''
import time
import threading
from mutex import mutex
from itertools import count
# def timer(no, interval):
# cnt = 0
# while cnt<10:
# print 'Thread:(%d) Time:%s\n'%(no, time.ctime())
# time.sleep(interval)
# cnt+=1
# threading.
#
#
# def test(): #Use thread.start_new_thread() to create 2 new threads
# threading.start_new_thread(timer, (1,1))
# threading.start_new_thread(timer, (2,2))
#
# if __name__=='__main__':
# test()
class Test(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.runNum=num
def run(self):
global count,mutex
threadName=threading.current_thread().getName()
for x in xrange(0,int(self.runNum)):
mutex.acquire()
count=count+1
mutex.release()
print threadName,x,count
time.sleep(1)
if __name__=='__main__':
global count,mutex
threads=[]
num=4
count=1
mutex=threading.Lock()
for x in xrange(0,num):
threads.append(Test(10))
for t in threads:
t.start()
for t in threads:
t.join()
|
275736008b7c3f50a84a4290e7a485611612f5d1 | saddaf88/Coding-Challenge | /HackerRank/if-else.py | 779 | 4.3125 | 4 | # Task
# Given an integer, , perform the following conditional actions:
#
# If is odd, print Weird
# If is even and in the inclusive range of to , print Not Weird
# If is even and in the inclusive range of to , print Weird
# If is even and greater than , print Not Weird
# Input Format
#
# A single line containing a positive integer, .
#
# Constraints
#
# Output Format
#
# Print Weird if the number is weird. Otherwise, print Not Weird.
#
# Sample Input 0
#
# 3
# Sample Output 0
#
# Weird
if __name__ == '__main__':
n = int(input().strip())
if n % 2 == 1:
print("Weird")
else:
if n in range(2, 6):
print("Not Weird")
elif n in range(6, 21):
print("Weird")
elif n > 20:
print("Not Weird") |
eb4dd738071d04695f6e8364eaacce3439282c4d | ArunCSK/MachineLearningAlgorithms | /PyGames/maze1.py | 10,817 | 3.671875 | 4 | import random
import pygame
import time
pygame.init()
WHITE = (255,255,255)
GREY = (20,20,20)
BLACK = (0,0,0)
PURPLE = (100,0,100)
RED = (255,0,0)
BLUE = (0, 0, 255)
size = (1200,700)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Maze Generator")
done = False
clock = pygame.time.Clock()
width = 25
cols = int(size[0] / width)
rows = int(size[1] / width)
# This sets the WIDTH and HEIGHT of each grid location
WIDTH = 30
HEIGHT = 30
# This sets the margin between each cell
MARGIN = 1
ROWS = 20
COLUMNS = 35
# Draw the grid
for row in range(ROWS):
for column in range(COLUMNS):
color = WHITE
pygame.draw.rect(screen,
color,
[(MARGIN + WIDTH) * column + MARGIN,
(MARGIN + HEIGHT) * row + MARGIN,
WIDTH + MARGIN ,
HEIGHT + MARGIN ])
pygame.display.flip()
pygame.display.update()
done = False
current_cell = (0,0)
next_cell = (0,0)
visited_cells = []
next_cells = []
stack = []
walls = [True, True, True, True]
x = 0
y = 0
top = (0,0)
bottom = (0,0)
left = (0,0)
right = (0,0)
diagonal = (0,0)
while not done:
time.sleep(0.005)
y,x = current_cell
visited_cells.append(current_cell)
if y-1 >= 0: #check top cell
top = (y-1, x)
if top not in visited_cells and top not in next_cells:
next_cells.append(top)
if x-1 >= 0 : #check left cell
left = (y, x-1)
if left not in visited_cells and left not in next_cells:
next_cells.append(left)
if y+1 <= COLUMNS -1: #check bottom cell
bottom = (y+1, x)
if bottom not in visited_cells and bottom not in next_cells:
next_cells.append(bottom)
if x+1 <= ROWS -1: #check right cell
right = (y, x+1)
if right not in visited_cells and right not in next_cells:
next_cells.append(right)
pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y + MARGIN, (MARGIN + WIDTH) * x + MARGIN, WIDTH + MARGIN, HEIGHT + MARGIN])
pygame.display.update()
#print(next_cells)
if len(next_cells) > 0:
next_cell = random.choice(next_cells)
y1,x1 = current_cell
y2,x2 = next_cell
x = int(x1) - int(x2)
y = int(y1) - int(y2)
if x == -1:
#pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y1 + MARGIN + MARGIN, (MARGIN + WIDTH) * x1 + MARGIN , WIDTH , HEIGHT ]) # current cell move right
#TOP
pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y1 + MARGIN, (MARGIN + WIDTH) * x1 + MARGIN, WIDTH + MARGIN, HEIGHT + MARGIN])
pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN ,WIDTH + MARGIN , MARGIN ])
#LEFT
pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN ,MARGIN, HEIGHT + MARGIN])
#BOTTOM
pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN + WIDTH ,WIDTH + MARGIN, MARGIN])
#pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y2 , (MARGIN + WIDTH) * x2 + MARGIN, WIDTH, HEIGHT]) # update next cell left
pygame.display.update()
if x == 1:
pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y1 + MARGIN, (MARGIN + WIDTH) * x1 + MARGIN, WIDTH + MARGIN, HEIGHT + MARGIN])
#pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y1 , (MARGIN + WIDTH) * x1 + MARGIN , WIDTH , HEIGHT]) # current cell move left
#RIGHT
pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + WIDTH + MARGIN, (WIDTH + MARGIN) * x1 + MARGIN,MARGIN , HEIGHT + MARGIN])
#TOP
pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN ,WIDTH + MARGIN , MARGIN ])
#BOTTOM
pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN + WIDTH ,WIDTH + MARGIN, MARGIN])
#pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y2 + MARGIN + MARGIN, (MARGIN + WIDTH) * x2 + MARGIN, WIDTH, HEIGHT]) # update next cell right
pygame.display.update()
if y == -1:
pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y1 + MARGIN, (MARGIN + WIDTH) * x1 + MARGIN, WIDTH + MARGIN, HEIGHT + MARGIN])
#pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + WIDTH) * x1 + MARGIN + MARGIN , WIDTH , HEIGHT]) # current cell move down
#TOP
pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN ,WIDTH , MARGIN ])
#LEFT
pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN ,MARGIN, HEIGHT + MARGIN])
#RIGHT
pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + WIDTH + MARGIN, (WIDTH + MARGIN) * x1 + MARGIN,MARGIN , HEIGHT + MARGIN])
#pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y2 + MARGIN, (MARGIN + WIDTH) * x2 , WIDTH, HEIGHT + MARGIN]) # update next cell up
pygame.display.update()
if y == 1:
pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y1 + MARGIN, (MARGIN + WIDTH) * x1 + MARGIN, WIDTH + MARGIN, HEIGHT + MARGIN])
#pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + WIDTH) * x1 , WIDTH , HEIGHT]) # current cell move up
#RIGHT
pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + WIDTH + MARGIN, (WIDTH + MARGIN) * x1 + MARGIN,MARGIN , HEIGHT + MARGIN])
#LEFT
pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN ,MARGIN, HEIGHT + MARGIN])
#BOTTOM
pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN + WIDTH ,WIDTH + MARGIN, MARGIN])
#pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y2 + MARGIN, (MARGIN + WIDTH) * x2 + MARGIN + MARGIN, WIDTH, HEIGHT]) # update next cell down
pygame.display.update()
current_cell = next_cell
y,x = current_cell
pygame.draw.rect(screen, RED,[(MARGIN + WIDTH) * y + MARGIN, (MARGIN + WIDTH) * x + MARGIN, WIDTH, HEIGHT])
pygame.display.update()
stack.append(current_cell)
next_cells.clear()
elif len(stack) > 0:
next_cell = stack.pop()
y1,x1 = current_cell
y2, x2 = next_cell
x = int(x1) - int(x2)
y = int(y1) - int(y2)
# if x == -1:
# #pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y1 + MARGIN + MARGIN, (MARGIN + WIDTH) * x1 + MARGIN , WIDTH , HEIGHT ]) # current cell move right
# #TOP
# pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN ,WIDTH + MARGIN , MARGIN ])
# #LEFT
# pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN ,MARGIN, HEIGHT + MARGIN])
# #BOTTOM
# pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN + WIDTH ,WIDTH + MARGIN, MARGIN])
# #pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y2 , (MARGIN + WIDTH) * x2 + MARGIN, WIDTH, HEIGHT]) # update next cell left
# pygame.display.update()
# if x == 1:
# #pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y1 , (MARGIN + WIDTH) * x1 + MARGIN , WIDTH , HEIGHT]) # current cell move left
# #RIGHT
# pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + WIDTH + MARGIN, (WIDTH + MARGIN) * x1 + MARGIN,MARGIN , HEIGHT + MARGIN])
# #TOP
# pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN ,WIDTH + MARGIN , MARGIN ])
# #BOTTOM
# pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN + WIDTH ,WIDTH + MARGIN, MARGIN])
# #pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y2 + MARGIN + MARGIN, (MARGIN + WIDTH) * x2 + MARGIN, WIDTH, HEIGHT]) # update next cell right
# pygame.display.update()
# if y == -1:
# #pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + WIDTH) * x1 + MARGIN + MARGIN , WIDTH , HEIGHT]) # current cell move down
# #TOP
# pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN ,WIDTH , MARGIN ])
# #LEFT
# pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN ,MARGIN, HEIGHT + MARGIN])
# #RIGHT
# pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + WIDTH + MARGIN, (WIDTH + MARGIN) * x1 + MARGIN,MARGIN , HEIGHT + MARGIN])
# #pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y2 + MARGIN, (MARGIN + WIDTH) * x2 , WIDTH, HEIGHT + MARGIN]) # update next cell up
# pygame.display.update()
# if y == 1:
# #pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + WIDTH) * x1 , WIDTH , HEIGHT]) # current cell move up
# #RIGHT
# pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + WIDTH + MARGIN, (WIDTH + MARGIN) * x1 + MARGIN,MARGIN , HEIGHT + MARGIN])
# #LEFT
# pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN ,MARGIN, HEIGHT + MARGIN])
# #BOTTOM
# pygame.draw.rect(screen,BLACK,[(MARGIN + WIDTH) * y1 + MARGIN , (MARGIN + HEIGHT) * x1 + MARGIN + WIDTH ,WIDTH + MARGIN, MARGIN])
# #pygame.draw.rect(screen, BLUE,[(MARGIN + WIDTH) * y2 + MARGIN, (MARGIN + WIDTH) * x2 + MARGIN + MARGIN, WIDTH, HEIGHT]) # update next cell down
# pygame.display.update()
current_cell = next_cell
y,x = current_cell
pygame.draw.rect(screen, RED,[(MARGIN + WIDTH) * y2 + MARGIN, (MARGIN + WIDTH) * x2 + MARGIN, WIDTH, HEIGHT])
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# ##### pygame loop #######
running = True
while running:
for event in pygame.event.get():
# check for closing the window
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False |
b0cf02c345dd94786ab302e99ee9e5b5ff98ab0a | zainllw0w/skillbox | /lessons 21/HomeWork/task3.py | 169 | 3.5625 | 4 | def f(n, k=1, i=1, my_list=[1]):
if i == n:
return my_list[-1]
my_list.append(k)
last_num = my_list[-2]
return f(n, k+last_num, i+1)
print(f(6)) |
9830a1b0bd3bd18feecba5ab19ec9ef787a4a3c2 | amulshrestha/Python-Projects | /Find IP Address of any Website/findIP.py | 1,478 | 4.375 | 4 | '''
Get IP Address of any website using python
Author: Amul Shrestha
'''
#Importing necessary packages.
import socket
#Displaying Banner
print("""
_____ _ _ ___ ____ __
| ___(_)_ __ __| | |_ _| _ \ ___ / _| __ _ _ __ _ _
| |_ | | '_ \ / _` | | || |_) | / _ \| |_ / _` | '_ \| | | |
| _| | | | | | (_| | | || __/ | (_) | _| | (_| | | | | |_| |
|_| |_|_| |_|\__,_| |___|_| \___/|_| \__,_|_| |_|\__, |
|___/
__ __ _ _ _
\ \ / /__| |__ ___(_) |_ ___
\ \ /\ / / _ \ '_ \/ __| | __/ _ /
\ V V / __/ |_) \__ \ | || __/
\_/\_/ \___|_.__/|___/_|\__\___|
Author: Amul Shrestha
""")
#Asking input of the website which IP needs to find
site = input("Enter the website: ")
#Get host hostname
hostname = socket.gethostname()
#Displaying hostname
print('Your Hostname is: ' + hostname)
#Getting host IP
host_ip = socket.gethostbyname(hostname)
#Displaying host IP
print('Your Ip Address is: ' + host_ip)
#Fetching the IP of the website
ip = socket.gethostbyname(site)
#Displaying IP of the Website
print('The IP Address of ' + site + ' is: ' + ip)
print("""
_____ _ _
|_ _| |__ __ _ _ __ | | __ _ _ ___ _ _
| | | '_ \ / _` | '_ \| |/ / | | | |/ _ \| | | |
| | | | | | (_| | | | | < | |_| | (_) | |_| |_
|_| |_| |_|\__,_|_| |_|_|\_\ \__, |\___/ \__,_(_)
|___/
""")
|
dd5257077929dc33201ed04414dcf68281814ef5 | OlehYavoriv/Ping-pong | /pongEngine.py | 3,927 | 3.609375 | 4 | from random import uniform, choice
from typing import Union, Tuple, List
class Ball:
def __init__(self, game, radius, speed):
self._game = game
self._speed = speed
self._radius = radius
self.__dx = 0
self.__dy = 0
self.__x = game.width / 2 - self._radius
self.__y = game.height / 2 - self._radius
@property
def position(self):
return self.__x, self.__y
@property
def dx(self):
return self.__dx
@property
def dy(self):
return self.__dy
@property
def radius(self):
return self._radius
def starting_position(self):
self.__dx = 0
self.__dy = 0
self.__x = self._game.width / 2 - self._radius
self.__y = self._game.height / 2 - self._radius
def shoot(self):
self.__dx = choice([-1, 1]) * uniform(self._speed * 0.2, self._speed * 0.8)
self.__dy = choice([-1, 1]) * (self._speed - abs(self.__dx))
def update(self):
self.__x += self.__dx
self.__y += self.__dy
if self.__y < self._radius * 2 or self.__y > self._game.height - self._radius * 2:
self.__dy = -self.__dy
self._game.score = [self.__x < self._radius, self.__x > self._game.width - self._radius]
if self.__x < self._radius or self.__x > self._game.width - self._radius:
self._game.starting_position()
if self._game.left_paddle.intersect(self) or self._game.right_paddle.intersect(self):
self.__dx = -self.__dx
class Padle:
def __init__(self, game, speed, left=True):
self._game = game
self._speed = speed
self._left = left
self.__x = game.width * 0.05 if left else game.width * 0.95
self._height = game.height * 0.15
self.__y = game.height / 2 - self._height / 2
self._width = self._height / 10
def moveUp(self):
self.__y -= self._speed
if self.__y < 0:
self.__y = 0
def moveDown(self):
self.__y += self._speed
if self.__y + self.height > self._game.height:
self.__y = self._game.height - self.height
def starting_position(self):
self.__x = self._game.width * 0.05 if self._left else self._game.width * 0.95
self.__y = self._game.height / 2 - self._height / 2
@property
def position(self):
return self.__x, self.__y
@property
def width(self):
return self._width
@property
def height(self):
return self._height
def intersect(self, ball):
ball_x, ball_y = ball.position
radius = ball.radius
return ((ball_x - radius < self.__x + self.width and self._left) or \
(ball_x + radius > self.__x and not self._left)) and \
ball_y < self.__y + self.height and \
ball_y > self.__y
class PongGameEngine:
def __init__(self,
size: Union[Tuple[int, int], List[int]],
ball_radius=2, ball_speed=5,
paddle_speed=5):
self.__width, self.__height = size
self.ball = Ball(self, ball_radius, ball_speed)
self.left_paddle = Padle(self, paddle_speed)
self.right_paddle = Padle(self, paddle_speed, left=False)
self.__score = [0, 0]
@property
def width(self):
return self.__width
@property
def height(self):
return self.__height
@property
def score(self):
return self.__score
@score.setter
def score(self, score):
self.__score = [self.__score[0] + score[0], self.__score[1] + score[1]]
def starting_position(self):
self.ball.starting_position()
self.left_paddle.starting_position()
self.right_paddle.starting_position()
def restart(self):
self.__score = [0, 0]
self.starting_position()
def update(self):
self.ball.update()
|
417bb0b4d940ae081b2f94003dea3dcfcf130e67 | nishikaverma/Python_progs | /sum.py | 203 | 3.859375 | 4 |
print("there sum is",int(input('enter 1st no'))+int(input('enter 2nd no.')))
print('Enter two no.s for addition')
a=int(input())
b=int(input())
s=a+b
print("a=",a,"b=",b)
print('There sum is:',s)
|
bd821944cf162d368b3d6b347d88d458e4fa501b | Prathiksha-Hegde/Leetcode-Solutions | /008_Min_Stack.py | 717 | 4 | 4 | class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.list_values =[]
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.list_values.insert(len(self.list_values),x)
def pop(self):
"""
:rtype: void
"""
self.list_values.pop()
def top(self):
"""
:rtype: int
"""
top_element = self.list_values[-1]
return top_element
def getMin(self):
"""
:rtype: int
"""
min_element = min(self.list_values)
return min_element
|
0301aebb67c460c82a84c6d52a131ad8b9e334cf | ajdeve/python | /Shuffling (Zip, Accumulate, Sum, Good Pairs).py | 1,886 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # shuffle the array
# ### zip
# In[46]:
nums = [2,5,1,3,4,7]
n = 3
# In[77]:
def shuffleArray(nums, n):
list1 = []
list2 = []
list3 = []
for i in range(0,n):
list1.append(nums[i])
for j in range(n,len(nums)):
list2.append(nums[j])
for a, b in zip(list1, list2):
#mixing two lists is a job of zip
list3 +=[a,b]
return list3
print(shuffleArray(nums,3))
# In[ ]:
def shuffle(self, nums: List[int], n: int) -> List[int]:
res = []
for i, j in zip(nums[:n],nums[n:]):
res += [i,j]
return res
# # Running Sum of 1d Array
# ## Generator 방법
# In[19]:
nums = [1,2,3,4]
# In[30]:
def run_sum_gen(nums):
cumsum = 0
for elt in nums:
cumsum += elt
yield cumsum
new_nums = list(run_sum_gen(nums))
# This takes basically no additional memory (only one float/int):
for x in run_sum_gen(nums):
print(x)
# ## Classic While
# In[31]:
def runningSum(self, nums):
i = 1
while i<len(nums):
nums[i]+=nums[i-1]
i+=1
return nums
# ## Accumulate
# In[ ]:
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
return accumulate(nums)
# ## Numpy
# In[29]:
import numpy as np
new_nums = np.cumsum(nums)
new_nums
# # Number of Good Pairs
#
# In[80]:
nums = [1,2,3,1,1,3]
# In[90]:
import itertools as it
def good(nums):
list=[]
for i in it.combinations(nums,2):
if i[0] == i[1]:
list.append(i[0])
list.append(i[1])
return list
good(nums)
# In[136]:
def good(nums):
count = 0
N = len(nums)
for i in range(N):
for j in range(i +1, N):
if nums[i] == nums[j]:
count+=1
return count
good(nums)
|
0ea5f775dc2ed46a9e29204678079f320b79a5e8 | jesuarva/Python-TicTacToe | /tic-tac-toe.py | 2,856 | 3.609375 | 4 | #Defining MAIN board
board ="""
*---------------*
| |
{a} | {b} | {c}
---+---+---
{d} | {e} | {f}
---+---+---
{g} | {h} | {i}
| |
*---------------*
"""
#Defining the positjons on board.
#dict(positon) = how current game is going
#dict(available) = available positions in current game
position = {'a': ' ', 'b': ' ', 'c': ' ',
'd': ' ', 'e': ' ', 'f': ' ',
'g': ' ', 'h': ' ', 'i': ' '}
available = {'a': 'a', 'b': 'b', 'c': 'c',
'd': 'd', 'e': 'e', 'f': 'f',
'g': 'g', 'h': 'h', 'i': 'i'}
win_row_column = {'a': '1-1', 'b': '1-2', 'c': '1-3',
'd': '2-1', 'e': '2-2', 'f': '2-3',
'g': '3-1', 'h': '3-2', 'i': '3-3'}
win_check = {'p11': '', 'p12': '', 'p13': '',
'p21': '', 'p22': '', 'p23': '',
'p31': '', 'p32': '', 'p33': ''}
# row = [1]
# column = [3]
# # check = str(row[0])+str(column[0])
# win_check[str(row[0])+str(column[0])] = 'X'
# print win_check
# win_row.append(win['f'][0])
# win_column.append(win['f'][2])
# type(win['a'])
# print str(win['33'])
# board_available = board.format(**available)
def board_game():
print '''\n ON GOING GAME'''+board.format(**position)
return ''
def board_available():
print '''\n chose available'''+board.format(**available)
return ''
# print board_game()
# print 'Select a position in the board for the next move:\nTo selct the position type the letter to chose it'+board_available
# To set current player.
# TODO def select_input():
player = ['O']
winner = [False]
row = [0,'','','']
column = [0,'','','']
# Set next move
# TODO check input is correct
def next_move():
# next_move = 'f'
next_move = raw_input(str(player[0])+"""'s turn.
Chose available position in the board
and hit enter:\n""")
position[next_move] = player[0]
# print position
available[next_move] = ' '
# print available
row[0] = win_row_column[next_move][0]
column[0] = win_row_column[next_move][2]
win_check['p'+str(row[0])+str(column[0])] = player[0]
# print board_available
# print board.format(**available)
def is_winner():
for i in range(1,4):
# print i
row[i] = win_check['p'+str(row[0])+str(i)]
column[i] = win_check['p'+str(i)+str(column[0])]
# print row
# print column
row_check = set(row[1:4])
column_check = set(column[1:4])
# print len(row_check)
# print row_check
# print len(column_check)
# print column_check
if len(row_check) == 1 or len(column_check) ==1:
winner[0] = True
# print is_winner
# print player[0]+' win!!'
def change_player():
if player[0] == 'X':
player[0] = 'O'
else:
player[0] = 'X'
def game():
print '''Welcome to Tic-Tac-Toe by jesuarva.
First player's move goes with "X", the Second player goes with "O"'''
while winner[0] != True:
change_player()
board_game()
board_available()
next_move()
is_winner()
print '''
GAME OVER:
And the winner is: '''+player[0]
game() |
f946cdd45f6bed21d06d6ee48a3ff954df1ee706 | abdulahia/Hangman | /Hangman.py | 5,965 | 4.375 | 4 | ######################################################################
# Author(s): Ahmed Abdulahi
# Username(s): abdulahia
#
# Assignment: P01 final project
#
# Purpose: The game of hangman: will invite the user to guess words from possible word bank and by guessing letter by
# letter the turtle will be drawing the hangman.
######################################################################
# Acknowledgements: Kite at Youtube and William Romano
# link of Youtube video : https://www.youtube.com/watch?v=m4nEnsavl6w&t=449s
#
# licensed under a Creative Commons
# Attribution-Noncommercial-Share Alike 3.0 United States License.
##################################################################################
import turtle
from wordss import words
import random
class Hangman:
"""
The player will given the chance to guess to guess the word in less then 6 tries before the hangman is
fully drawn. In the game of hangman, the person is drawn in 6 parts which is why we have 6 pre drawn parts
plus the tree.
"""
def __init__(self):
"""
:param mooley: our turtle that we would be using through out
"""
super().__init__()
self.mooley = turtle.Turtle()
self.mooley.hideturtle()
self.mooley.color("red")
self.mooley.speed("fastest")
def tree(self):
"""
The tree where the hangman hangs from
:return: None
"""
self.mooley.penup()
self.mooley.goto(-250, -100)
self.mooley.pendown()
self.mooley.goto(0, -100)
self.mooley.goto(-150, -100)
self.mooley.goto(-150, 150)
self.mooley.goto(-0, 150)
self.mooley.goto(0, 100)
def draw_head(self):
"""
the head of the hangman / first guess
:return: None
"""
self.mooley.penup()
self.mooley.goto(0, 70)
self.mooley.pendown()
self.mooley.circle(15)
def draw_body(self, ):
"""
the body of the hangman / second guess
:return:
"""
self.mooley.goto(0, -20)
def draw_left_leg(self):
"""
the left leg of the hangman / third guess
:return:
"""
self.mooley.goto(-33, -50)
def draw_right_leg(self,):
"""
the right leg of the hangman / fourth guess
:return:
"""
self.mooley.penup()
self.mooley.goto(0, -20)
self.mooley.pendown()
self.mooley.goto(33, -50)
def draw_left_arm(self,):
"""
the left arm of the hangman / fifth guess
:return:
"""
self.mooley.penup()
self.mooley.goto(0, 40)
self.mooley.pendown()
self.mooley.goto(-33, 20)
def draw_right_arm(self):
"""
the right arm of the hangman / sixth guess
:return:
"""
self.mooley.penup()
self.mooley.goto(0, 40)
self.mooley.pendown()
self.mooley.goto(33, 20)
class Game:
"""
This is the game of hangman, where it all comes alive
"""
def __init__(self):
self.wn = turtle.Screen()
self.wn.bgcolor("light blue")
self.mooley = turtle.Turtle()
self.mooley.color("red")
def word(self):
"""
Our random word that we will get everytime it runs
:return:
"""
random_word = random.choice(words)
return random_word
def fill_dash_lines(self,random_word):
"""
dashes that represent the length of the word and fills out when they are right
:return:
"""
dash = "_" * len(random_word) # creates the dashlines based on length of the word
print(dash)
# allow us to write on the turtle screen
def write(self, txt):
"""
Will write text on the turtle screen several times i.e when the player loses or wins
:param txt: The text that writes on the screen
:return: None
"""
self.txt = txt
self.mooley.hideturtle()
self.mooley.penup()
self.mooley.setpos(-120, -175)
self.mooley.write(self.txt, move=False, align='center', font=("Arial", 30, "bold"))
def main():
d = Hangman()
d.tree()
h1 = Game()
word_chosen = h1.word()
h1.write("_ " * len(word_chosen))
h1.fill_dash_lines(word_chosen)
guessed = False
guesses = 6 # number of guesses allowed
already_guessed = []
while not guessed and guesses > 0:
user = h1.wn.textinput("hangman", "guess a letter? ")
if len(str(user)) == len(str(word_chosen)):
if user == word_chosen:
print(" you have won")
if len(user) == 1:
if user in word_chosen:
print(" you guessed", user, "right")
new_list = ""
already_guessed.append(user)
for letter in word_chosen:
if letter in user:
new_list += letter
else:
new_list += (" _ ")
h1.write(new_list)
if user == word_chosen:
print(" you have won")
if user not in word_chosen:
guesses -= 1
if guesses == 5:
d.draw_head()
if guesses == 4:
d.draw_body()
if guesses == 3:
d.draw_left_leg()
if guesses == 2:
d.draw_right_leg()
if guesses == 1:
d.draw_left_arm()
if guesses == 0:
d.draw_right_arm()
h1.write(20)
h1.write("YOU LOST, GAME OVER!!!")
if guesses != 0 and "".join(already_guessed).strip() == word_chosen.strip():
print(" you have won!")
h1.write(" you have won")
if __name__ == '__main__':
main()
|
cc7f62fe4da210761ba3e7fa85dc5e9de4d1e6c8 | RGonzaloLeandro/python-initial-course | /Promedio.py | 246 | 3.953125 | 4 | def promediar(a,b,c):
resultado = (a + b + c)/3
return resultado
nota_1 = int(input("Primera nota?"))
nota_2 = int(input("Segunda nota?"))
nota_3 = int(input("Tercera nota?"))
print("El promedio es:", promediar(nota_1, nota_2, nota_3))
|
49c1cf70f69b20595a4c0de9c8aaf75ecffe7eda | wltrallen2/Python-TechDegree-Project-2 | /ciphers/transposition.py | 4,288 | 4.15625 | 4 | from .ciphers import Cipher
class Transposition(Cipher):
"""This class encodes and decodes messages using the Rail Fence Cipher
(a version of the Transposition cipher as defined at
https://en.wikipedia.org/wiki/Transposition_cipher). The initializer
requires an int that represents the number of rails to use, but
it defaults to 3 if no int is passed.
This version of Transposition requires that all characters be uppercase
letters with no whitespace or other special characters.
"""
def __init__(self, num_rails = 3):
"""The initializer accepts an int <num_rails> and sets then
instance variable <num_rails>. If no int is passed, the initializer
will set the default number of rails to 3.
It also defines the arguments_dict variable to indicate that this
cipher requires an int for the 'Number of Rails'.
"""
super().__init__()
self.arguments_dict = {'Number of Rails': int}
if not(str(num_rails).isnumeric() and int(num_rails) > 1):
num_rails = 3
self.num_rails = int(num_rails)
def set_arguments(self, args_dict):
"""Sets the number of rails to use in the enryption and decryption
process by using the value that is attached to the key 'Number of
Rails' in the arguments_dict.
"""
self.num_rails = args_dict['Number of Rails']
def encrypt(self, message):
"""Returns the ecrypted message using the Rail
Fence Tranposition Cipher as described at
https://en.wikipedia.org/wiki/Transposition_cipher.
"""
rails = [''] * self.num_rails
rail_increment = 1
rail_index = 0
for letter in message:
if letter.isalpha():
rails[rail_index] += letter.upper()
rail_index += rail_increment
if self.__index_at_or_out_of_bounds(rail_index,
range(self.num_rails)):
rail_increment *= -1
return ''.join(rails)
def decrypt(self, message):
"""Returns the decrypted message using the Rail
Fence Tranposition Cipher as described at
https://en.wikipedia.org/wiki/Transposition_cipher.
"""
coded_chars_list = list([''] * len(message))
new_index = 0
for rail_index in range(self.num_rails):
ltr_index = rail_index
alternating_factor = 'A'
while ltr_index < len(message) and new_index < len(message):
coded_chars_list[ltr_index] = message[new_index]
new_index += 1
ltr_index, alternating_factor = \
self.__get_next_index_for(ltr_index,
self.num_rails,
rail_index,
alternating_factor)
return ''.join(coded_chars_list)
def __get_next_index_for(self, index, num_rails,
rail_index, alternating_factor):
"""Returns a tuple which includes an int value and an
alternating_factor.
The int value is used during the decryption process
to determine the next index value (its position in the decoded message)
for a letter in the encoded_message, which has been encoded using the
Rail Fence Transposition Cipher.
The alternating_factor is used in the algorithm to determine
whether the message is travelling up or down the rails.
"""
if rail_index == num_rails - 1:
rail_index = 0
increment = (2 * num_rails) - (2 * rail_index) - 2
if rail_index == 0:
return index + increment, 'A'
elif alternating_factor == 'A':
return index + increment, 'B'
else:
increment = (2 * rail_index)
return index + increment, 'A'
def __index_at_or_out_of_bounds(self, index, range):
"""Returns True if the passed index is at or outside of the bounds
of the given range. Otherwise, returns False.
"""
if (index <= range.start) or (index >= range.stop - 1):
return True
return False
|
98c980d06df047d0792f87b7f6ca3d6cb1c34b4a | NaoiseGaffney/PythonMTACourseCertification | /GaffTest/comprehensionInPython.py | 4,061 | 4.84375 | 5 | numbers = [1, 2, 3, 4, 5]
text = ["One", "Two", "Three", "Four", "Five"]
# List and Dictionary Comprehensions, For-, and If-statements first followed by List and Dictionary Comprehensions
# doing the same thing.
# --- 1. Simple example
print("\n--- Example 1, List Comprehension:")
# For-loop...
result = []
for x in numbers:
result.append(x)
print(result)
# ...as a List Comprehension...
result_list_comprehension = [x for x in numbers]
print(result_list_comprehension)
# --- 2. Simple example, multiplying x with itself 'x*x'
print("\n--- Example 2:")
# For-loop...
result = []
for x in numbers:
result.append(x*x)
print(result)
# ...as a List Comprehension...
result = [x*x for x in numbers]
print(result)
# --- 3. Multiplying even-numbered 'x'
print("\n--- Example 3:")
# For and If...
result = []
for x in numbers:
if x % 2 == 0:
result.append(x*x)
print(result)
# ...as a List Comprehension...
result = [x*x for x in numbers if x % 2 == 0]
print(result)
# --- 4. Using 'map()' and a lambda function instead.
print("\n--- Example 4, using 'map()' and a lambda function instead of a List Comprehension:")
print(list(map(lambda y: y*y, numbers)))
# --- 5. Nested For-loops.
print("\n--- Example 5 Nested For-loops:")
for num in numbers:
print(num)
for t in text:
print(text)
# ...as a List Comprehension, a List of Lists...
print("List of Tuples: ", [(num, t) for num in numbers for t in text])
print("List of Lists: ", [[num, t] for num in numbers for t in text])
print("List of Dictionaries: ", [{num, t} for num in numbers for t in text])
# --- 6. Simplifying diceRolls.py
print("\n--- Example 6:")
import random
numOfDiceRolled = 6
numSidesOfDice = 10
# For-loop and '.append()'
rollList = []
for roll in range(numOfDiceRolled):
rollList.append(random.randint(1, numSidesOfDice))
print(rollList)
# ...as a List Comprehension...
rollList = [random.randint(1, numSidesOfDice) for roll in range(numOfDiceRolled)]
print(rollList)
# --- 7. NOT a comprehension in Python. Use of '.get()' instead of 'for, if, dictRolls[rolls] += 1...'.
print("\n--- Example 7 (NOT a comprehension in Python. "
"Use of '.get()' instead of 'for, if, dictRolls[rolls] += 1...'):")
# For-loop and If-Else statement
dictRolls = {}
for rolls in rollList:
if rolls in dictRolls:
dictRolls[rolls] += 1
else:
dictRolls[rolls] = 1
print(dictRolls)
# NOT a comprehension in Python. Use of '.get()' instead of 'for, if, dictRolls[rolls] += 1...'.
dictRolls[rolls] = dictRolls.get(rolls, 0) + 1
print(dictRolls)
# --- 8. Flatten a List.
print("\n--- Example 8, Flatten a List:")
# Nested For-loops and '.append()'.
def flatten_long(nested_list):
flat_list = []
for sublist in nested_list:
for item in sublist:
flat_list.append(item)
return flat_list
# ...as a List Comprehension...
def flatten(nested_list):
flat_list = [item for sublist in nested_list for item in sublist]
return flat_list
print("Flatten Long: ", flatten_long([[1, 2], [3, 4], [5, 6]]))
print("Flatten with List Comprehension: ", flatten([[1, 2], [3, 4], [5, 6]]))
# --- 9. Dictionary Comprehension.
# Taken from 'https://github.com/programiz/python-best-practices/blob/main/02-comprehension.md'.
print("\n--- Example 9, Dictionary Comprehension:")
# For, If-Else Statements.
pint_price = {"Guinness Foreign Extra": 5, "Punk IPA": 4.5, "Milk": 0.8}
new_price = dict()
for key, value in pint_price.items():
if value > 2:
new_price[key] = value * 1.5
else:
new_price[key] = value
print(new_price)
# ...as a Dictionary Comprehension...
new_price = {key: value * 1.5 if value > 2 else value for (key, value) in pint_price.items()}
print(new_price)
# --- 10. Dictionary Comprehension.
# Taken from 'https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/'.
print("\nExample 10, Dictionary Comprehension:")
original = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}
flipped = {value: key for key, value in original.items()}
print(flipped)
|
af7c480c7a1e1e1f83755724ee1025e1bec7ad32 | AlexFue/Interview-Practice-Problems | /sorting_algorithm/color_sort.py | 3,054 | 4.15625 | 4 | Problem:
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Follow up:
Could you solve this problem without using the library's sort function?
Could you come up with a one-pass algorithm using only O(1) constant space?
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]
Example 3:
Input: nums = [0]
Output: [0]
Example 4:
Input: nums = [1]
Output: [1]
Solution1:
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if len(nums) > 1:
m = len(nums) // 2
left = nums[:m]
right = nums[m:]
self.sortColors(left)
self.sortColors(right)
self.helper(nums, left, right)
def helper(self, nums, left, right):
l = r = 0
i = 0
while l < len(left) and r < len(right):
if left[l] < right[r]:
nums[i] = left[l]
l += 1
else:
nums[i] = right[r]
r += 1
i += 1
while l < len(left):
nums[i] = left[l]
i += 1
l += 1
while r < len(right):
nums[i] = right[r]
r += 1
i += 1
Solution2:
def color_sort(nums):
moves_right = 0
for x in range(len(nums)):
if nums[x - moves_right] == 0:
nums.insert(0, nums[x - moves_right])
del nums[x - moves_right + 1]
elif nums[x - moves_right] == 2:
nums.append(nums[x - moves_right])
del nums[x - moves_right]
moves_right += 1
return nums
Process1:
The way we are going to solve this is by implementing the merge sort algorithm to sort our colors.
If you do not know how that works. basically you seperate the list to halves until they are in singles,
then you backtrack and start to join the lists back together but sorted.
Process2:
example
input = [1,2,0,2,1,0,2]
step = [1,0,2,1,0,2,2] moved 2 to the back
step = [0,1,2,1,0,2,2] moved 0 to the front
step = [0,1,1,0,2,2,2] moved 2 to the back
step = [0,0,1,1,2,2,2] moved 0 to the front
output = [0,0,1,1,2,2,2]
do this process n amount of times
if a number is 2, move to back and dont go on to the next element
if a number is 0, move to front and go on to the next elelment
if it is a 1, go on to next element
for loop through the array
if cur element is 0, move it at index 0
if cur element is 2, move it to the back
keep track of the amount of elements that are moved to the back, when accessing an element from the array, subtract the index by the amount of times you moved an element to the back so you wont accidentally skip an element
return sorted array
|
1dc11f3bc927c0b768f71de88fca6b0870dcd1e6 | neveSZ/fatecsp-ads | /IAL-002/Listas/2-Seleção/07.py | 680 | 3.84375 | 4 | '''
Fornecido os coeficientes de uma equação de segundo grau (com a≠0, ou seja,
não é necessário verificar a existência da equação), exibir suas raízes.
Obs. (2): Caso Δ seja negativo, imprimir suas raízes no formato x-yi e x+yi,
apos calcular x e y.
'''
a = float(input('a: '))
b = float(input('b: '))
c = float(input('c: '))
delta = b * b - 4 * a * c
if delta == 0:
print((-b + delta**(1 / 2)) / (2 * a))
else:
if delta > 0:
print((-b + delta**(1 / 2)) / (2 * a))
print((-b - delta**(1 / 2)) / (2 * a))
else:
x = -b / 2 * a
y = (-delta)**(a / 2)
print('%.2f+%.2fi' % (x, y))
print('%.2f-%.2fi' % (x, y))
|
9a10fedbf1aff6d2a77035b3b88c52ae8b3fdb29 | gavrie/pycourse | /examples/attr.py | 210 | 3.59375 | 4 | class Foo(object):
def __init__(self, a):
self._a = a
@property
def a(self):
return self._a
@a.setter
def a(self, value):
print "setter"
self._a = value
f = Foo(123)
print f.a
f.a = 5
print f.a
|
87643f43071ba086d24c97d510e88b5083d193cb | CristianoFernandes/LearningPython | /desafios/desafio_018.py | 348 | 3.953125 | 4 | print('#' * 43)
print('#' * 15, 'DESAFIO 018', '#' * 15)
import math
angulo = int(input('Digite a medida do ângulo: '))
print('O seno de um angulo de', angulo, 'º é: ', math.sin(angulo))
print('O cosseno de um angulo de', angulo, 'º é', math.cos(angulo))
print('A tangente de um angulo de', angulo, 'º é', math.tan(angulo))
print('#' * 43)
|
cc627b17eb30f10da4af33b7d1c9d9e391dfc348 | jaqamoah/CS210 | /Release/PythonCode.py | 1,333 | 4.09375 | 4 | import re
import string
import fileinput
contents = dict() # Dictionary to store items from the input file.
# Method to display the frequency of a specific item
def display_specific_items(value):
read_data() # Method to read the items from the input file and store them in a dictionary.
key = contents.get(value)
if(key) != None : # Checking if the item exists or not
return contents[value]; # Return the frequency of the item selected
else :
return -1; # Return -1 if the item does not exist
# Method to read the items from the input file and store them in a dictionary.
def read_data():
with open("CS210_Project_Three_Input_File.txt") as f:
for line in f :
line = line.strip()
if line in contents:
contents[line]+=1
else :
contents[line]=1
# Method to write the items to a frequency.dat file.
def write_data():
read_data()
out = open("frequency.dat", "w")
for key in contents.keys() :
items = key +" "+ str(contents[key])+"\n"
out.write(items)
out.close()
# Method to display all of the items from the input file with their frequency.
def display_all_items():
read_data()
for key in contents.keys() :
print(key, contents[key]) |
229953ea3a0ec15c980f9814f2c683601550f84f | celshee/areacalsi | /area.py | 156 | 4 | 4 | def area():
r=int(input("enter the radius of the circle"))
area1=3.14*(r**2)
print(area1)
area()
print("the area of the circle is ",)
|
a1ab9993a1f555a744c4699e6e9594e0c39c28f0 | Bonfim-luiz/Introducao_Ciencia_Computacao_Python_Parte_2_Coursera | /Semana 2/Conta_letras.py | 1,219 | 3.9375 | 4 | import re
def conta_letras(frase, contar="vogais"):
"""A função conta_letras(frase, contar="vogais"), que recebe como
primeiro parâmetro uma string contendo uma frase e como segundo
parâmetro uma outra string. Este segundo parâmetro deve ser opcional."""
consoantes = ''
vogais = ''
frase = re.sub('[!-.:-@]',' ', frase)
a = 0
for letra in frase:
if letra not in ("A","E","I","O","U","a","e","i","o","u") and contar == "consoantes":
consoantes = consoantes + letra
consoantes = re.sub('[!-.:-@]', ' ', consoantes)
consoantes = consoantes.strip()
a = len(consoantes)
elif letra in ("A","E","I","O","U","a","e","i","o","u") and contar == "vogais":
vogais = vogais + letra
vogais = re.sub('[!-.:-@]', ' ', vogais)
vogais = vogais.strip()
a = len(vogais)
else:
if letra in ("A","E","I","O","U","a","e","i","o","u") and contar != "consoantes":
vogais = vogais + letra
vogais = re.sub('[!-.:-@]', ' ', vogais)
vogais = vogais.strip()
a = len(vogais)
return a
|
07cc4dcf09903fa36ed2a047283debb1e74760ea | appinfin/RootCount | /RootCount.py | 1,487 | 3.796875 | 4 |
Af = True
Bf = True
Cf = True
def root_count(A, B, C):
""" Вычисляет число корней квадратного ур-ния
"""
if A!=0:
D = B**2 - 4*A*C
if D > 0:
print(f'D = {round(D, 2)} -> Два корня: ', end=' ')
print(f'X1 = {round((-B -D**0.5) / (2*A), 2)};', end=' ')
print(f'X2 = {round((-B +D**0.5) / (2*A), 2)}')
elif D == 0:
print(f'D = {round(D, 2)} -> Один корень', end=' ')
print(f'X = {round(-B / (2*A), 2)}')
else:
print(f'D = {round(D, 2)} -> Корней нет')
else:
print(f'Ур-ние с коэффициентом А = 0 не является квадратным')
for i in range(1,6): # кол-во уравнений от 1 до 6 (5 шт.)
while Af:
try:
A = float(input('Введите коэффициент А = '))
Af = False
except Exception:
pass
while Bf:
try:
B = float(input('Введите коэффициент B = '))
Bf = False
except Exception:
pass
while Cf:
try:
C = float(input('Введите коэффициент C = '))
Cf = False
except Exception:
pass
print(f'Уравнение № {i}')
root_count(A, B, C)
Af = True
Bf = True
Cf = True
|
3e0d79a1c85da1be5feb95ff688d9aa1614e9b6f | ritwiksingh21/WebTest | /qclass.py | 557 | 3.640625 | 4 | class Question():
def __init__(self):
self.text = ""
self.tags = []
class QuestionMC(Question):
def __init__(self):
super().__init__()
self.answers = []
self.correctAnswers = []
self.correctAnswerLabels = [] #should i use this?
class Answer():
def __init__(self, q, correct=False):
self.question = q
self.question.answers.append(self)
if correct:
self.question.correctAnswers.append(self)
class Tag():
def __init__(self, name):
self.name = name
|
c73ce129433199c507cecac9f2bce5dbcfe95ac5 | dtingg/Fall2018-PY210A | /students/KyleBarry/session04/trigrammify.py | 2,059 | 3.765625 | 4 | import random
import requests
from bs4 import BeautifulSoup
def get_text(url):
"""
Get text data from url of gutenberg project so as to not have it within
code
"""
page = requests.get(url)
soup = BeautifulSoup(page.content, "lxml")
text = soup.find_all("p")
texter = [i.text for i in text]
words = "".join(texter).split()
# Pass parsed words of book in list form to trigram dictionary maker
make_trigrams(words)
def make_trigrams(words):
"""
Build trigrams, keys as two words and values as possible next words
"""
tris = {}
for w1, w2, w3 in zip(words[:-2], words[1:-1], words[2:]):
if (w1, w2) not in tris:
tris[(w1, w2)] = [w3]
else:
tris[(w1, w2)].append(w3)
# Pass tris dictionary and words list to random text generator
random_text(tris, words)
def random_text(tris, words):
"""
Select tris dictionary key to start sequence if first letter is
capitalized.
Iterate for approximate length of text and create tuples of last two words.
Add values of tuples that are in tris dictionary, otherwise append random
word.
"""
while True:
new_text = list(random.choice(list(tris.keys())))
if new_text[0][0].isupper():
break
else:
continue
# Add random choice to the new text from list of tuple pair in dictionary
# If exact match doesn't exist in dictionary, take second word and add
# random choice from list of value with second tuple value
for i in range(len(words)-2):
last_two = tuple(new_text[-2:])
try:
new_text.append(random.choice(tris[last_two]))
except KeyError:
for i in tris:
if last_two[1] == i[1]:
new_text.append(random.choice(tris[i]))
else:
new_text.append(random.choice(new_text))
print(" ".join(new_text))
if __name__ == "__main__":
get_text("https://www.gutenberg.org/files/1497/1497-h/1497-h.htm")
|
86cb1f3b6ca9bc783cd5cc0cef07a4eb51711f7e | emmagordon/python-bee | /hard/roman_numerals.py | 635 | 3.875 | 4 | #!/usr/bin/env python
"""Write a function, f, which, given a positive integer, returns the
value as a roman numeral.
where, in roman numerals:
i = 1
v = 5
x = 10
l = 50
c = 100
d = 500
The value you return should use as few characters as possible, e.g. 4
should be 'iv' rather than 'iiii'.
You can assume the number you have to convert is < 1000.
>>> f(1) in ['i', 'I']
True
>>> f(4) in ['iv', 'IV']
True
>>> f(36) in ['xxxvi', 'XXXVI']
True
>>> f(140) in ['cxl', 'CXL']
True
>>> f(827) in ['dcccxxvii', 'DCCCXXVII']
True
"""
import doctest
# TODO: REPLACE ME WITH YOUR SOLUTION
if __name__ == "__main__":
doctest.testmod()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.