blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
742e0b135c8c19f4a604b24d1225fc5bf3f3c699 | Alevtina2283/cd101 | /age_count.py | 226 | 3.953125 | 4 | furst_name = input("ur furst name")
second_name = input("ur second_name")
birth_year = input("please, enter ur Bday")
curent_year = 2021
age = curent_year - int(birth_year)
print(F"name:{furst_name} {second_name} age: {age}") |
7168ee2a01b6dc489696bd2f1a8c5d37c9dd0b7f | baloooo/coding_practice | /reverse_integer.py | 978 | 4.15625 | 4 | """
Reverse digits of an integer.
Example1:
x = 123,
return 321
Example2:
x = -123,
return -321
Return 0 if the result overflows and does not fit in a 32 bit signed integer
"""
def my_reverse(self, x):
ans = 0
if x >= 0:
while x:
# ans*10, since one unit place was added with this iteration.
# x%10 to get the current tail of x
ans = ans * 10 + x % 10
x /= 10
return ans if ans <= 2147483647 else 0 # Handle overflow.
else:
return -self.my_reverse(-x)
def reverse_integer(num):
sign = False
if num<0:
sign = True
num = abs(num)
reversed_num = 0
num_len = len(str(num)) - 1
index = 0
while(index<=num_len):
rem = num%10
reversed_num += (10**(num_len-index))*rem
num /= 10
index += 1
return -reversed_num if sign else reversed_num
if __name__ == '__main__':
num = -123
print reverse_integer(num)
|
81a2d55c8de43273bc6a4a5f915b7431f4556add | AmithSahadevan/No_repetition | /NOrep.py | 540 | 4.125 | 4 | Input = input("Enter a phrase: ") #Taking in input.
lizt = list(Input) #Convering Input into a list and storing it in a variable called lizt.
dictionary = dict.fromkeys(lizt) #Converting the above list into a dictionary.
back_to_list = list(dictionary) #Converting the above dictionary back to list.
for letters in back_to_list: # looping thru the letters in the list.
print(letters, end = "") #Printing out the letters one by one from the list, but in a single line.
print("") #Just for adding a bit of final touch..Yeah, that's it. |
67f7d37b82e337c1c94ffc26c02464236cf14e21 | yiming1012/MyLeetCode | /LeetCode/回溯法/5635. 构建字典序最大的可行序列.py | 2,763 | 4.125 | 4 | """
5635. 构建字典序最大的可行序列
给你一个整数 n ,请你找到满足下面条件的一个序列:
整数 1 在序列中只出现一次。
2 到 n 之间每个整数都恰好出现两次。
对于每个 2 到 n 之间的整数 i ,两个 i 之间出现的距离恰好为 i 。
序列里面两个数 a[i] 和 a[j] 之间的 距离 ,我们定义为它们下标绝对值之差 |j - i| 。
请你返回满足上述条件中 字典序最大 的序列。题目保证在给定限制条件下,一定存在解。
一个序列 a 被认为比序列 b (两者长度相同)字典序更大的条件是: a 和 b 中第一个不一样的数字处,a 序列的数字比 b 序列的数字大。比方说,[0,1,9,0] 比 [0,1,5,6] 字典序更大,因为第一个不同的位置是第三个数字,且 9 比 5 大。
示例 1:
输入:n = 3
输出:[3,1,2,3,2]
解释:[2,3,2,1,3] 也是一个可行的序列,但是 [3,1,2,3,2] 是字典序最大的序列。
示例 2:
输入:n = 5
输出:[5,3,1,4,3,5,2,4,2]
提示:
1 <= n <= 20
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-the-lexicographically-largest-valid-sequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from typing import List
class Solution:
def constructDistancedSequence(self, n: int) -> List[int]:
"""
思路:回溯法
类似数独
@param n:
@return:
"""
m = 2 * n - 1
self.arr = [0] * m
visited = set()
# 找到了就返回True
def backtrack(cur):
if len(visited) == n:
return True
if self.arr[cur] != 0:
if backtrack(cur + 1): return True
for i in range(n, 0, -1):
if i == 1 and i not in visited and self.arr[cur] == 0:
self.arr[cur] = i
visited.add(i)
if backtrack(cur + 1):
return True
visited.remove(i)
self.arr[cur] = 0
elif i not in visited and self.arr[cur] == 0 and cur + i < m and self.arr[cur + i] == 0:
self.arr[cur] = i
self.arr[cur + i] = i
visited.add(i)
if backtrack(cur + 1):
return True
visited.remove(i)
self.arr[cur] = 0
self.arr[cur + i] = 0
return False
backtrack(0)
return self.arr
if __name__ == '__main__':
n = 3
print(Solution().constructDistancedSequence(n))
|
149cffd532d7683795d3c4d8d8fb33156f575898 | Vagacoder/Codesignal | /python/Arcade/Core/C152CountElements.py | 3,188 | 4.09375 | 4 | #
# * Core 152. Count Elements
#
# * You've been invited to a job interview at a famous company that tests programming
# challenges. To evaluate your coding skills, they have asked you to parse a given
# problem's input given as an inputString string, and count the number of primitive
# type elements within it.
# The inputString can be either a primitive type variable or an array (possibly
# multidimensional) that contains elements of the primitive types.
# A primitive type variable can be:
# an integer number;
# a string, which is surrounded by " characters (note that it may contain any
# character except ");
# a boolean, which is either true or false.
# Return the total number of primitive type elements inside inputString.
# Example
# For inputString = "[[0, 20], [33, 99]]", the output should be
# countElements(inputString) = 4;
# For inputString = "[ "one", 2, "three" ]", the output should be
# countElements(inputString) = 3;
# For inputString = "true", the output should be
# countElements(inputString) = 1;
# For inputString = "[[1, 2, [3]], 4]", the output should be
# countElements(inputString) = 4.
# Input/Output
# [execution time limit] 4 seconds (py3)
# [input] string inputString
# Correct input of a given problem.
# Guaranteed constraints:
# 2 ≤ inputString.length ≤ 60.
# [output] integer
# The total number of primitive type elements within the input.
#%%
import re
# * Solution 1
# ! using exec() to execute a STATEMENT
def countElements1(inputString: str) -> int:
updatedInput = inputString.replace('[', '')
updatedInput = updatedInput.replace(']', '')
updatedInput = updatedInput.replace('true', 'True')
updatedInput = updatedInput.replace('false', 'False')
print(updatedInput)
# a = []
# print(a)
newArray = 'a=[' + updatedInput + ']'
# print(newArray)
lcls = locals()
exec(newArray, globals(), lcls)
a = lcls['a']
# print(a)
# * try eval()
# a = eval('[' + updatedInput + ']')
return len(a)
# * Solution 2
# ! using eval() to execute a EXPRESSION
def countElements2(S:str) -> int:
S = S.replace('true','True')
S = S.replace('false','False')
T = eval(S)
print(T)
def count(A):
ans = 0
if type(A) in [int,str,bool]:
return 1
for x in A:
if type(x) in [int,str,bool]:
ans += 1
else:
ans += count(x)
return ans
return count(T)
# * Solution 3
def countElements(inputString: str) -> int:
# ! NOTE: .*? is non-greedy for *
X = re.findall(r'\".*?\"|\d+|true|false', inputString)
# ! another regex
# X = re.findall(r'(\"[^\"]*\"|\d+|true|false)', inputString)
print(X)
return len(X)
i1 = '[]'
r1 = countElements(i1)
print(r1)
i1 = '[[0, 20], [33, 99]]'
r1 = countElements(i1)
print(r1)
i1 = '[ "one", 2, "three" ]'
r1 = countElements(i1)
print(r1)
i1 = "true"
r1 = countElements(i1)
print(r1)
i1 = '[[1, 2, [3]], 4]'
r1 = countElements(i1)
print(r1)
i1 = '[[1, "two, three", [4]], "true", true]'
r1 = countElements(i1)
print(r1)
|
19985800277a9f5dce7288e9e65003f60a8726f5 | cogito0823/learningPython | /从入门到实践/2-4.py | 601 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#########################################################################
# File Name: 2-4.py
# Created on : 2019-11-21 17:04:14
# Author: cogito0823
# Last Modified: 2019-11-21 17:04:14
# Description: 调整名字的大小写: 将一个人名存储到一个变量中,再以小写、大写和首字母大写的方式显示这个人名。
#########################################################################
name = input('Username: ')
def printname(name):
print(name)
printname(name.lower())
printname(name.upper())
printname(name.title())
|
c551dcf8141b0b465e99be80637980c7bab450b5 | d4rkr00t/leet-code | /python/leet/5-longest-palindromic-substr.py | 681 | 3.859375 | 4 | # Longest palindromic substr
# #url: https://leetcode.com/problems/longest-palindromic-substring/
# #medium
def longestPalindrome(s): # cbbd
ans = (0, 0)
def expand(str, start, end): # 1 2
while start >= 0 and end < len(s) and str[start] == str[end]:
start -= 1
end += 1
return s[start+1:end]
for i in range(len(s)): # 3
range1 = expand(s, i, i)
range2 = expand(s, i, i+1)
tmp = range1 if len(range1) > len(range2) else range2
ans = ans if len(ans) > len(tmp) else tmp # (0, 3)
return ans
print(longestPalindrome("babad"), "bab")
print(longestPalindrome("cbbd"), "bb")
# babad
#
|
684b548367b90150a6d61bb7273e356d6192f8c4 | S-ghanbary98/python_Exception_Handling | /files_and_exception_handling.py | 719 | 3.8125 | 4 | # print(1/0) # ZeroDivisionError
# We will create a file with required Permissions and see what errors/exception are possible
# First iterations
#file = open("order.txt") # open() takes string argument of file name.
#print(file) # Produces an FileNotFoundError
# Second Iteration
try:
file = open("app/order.txt")
print("file found")
except FileNotFoundError as errmsg:
print(f"File not Found {errmsg}") # prints the error message.
finally: ## finally will execute regardless of try/except block
print("Thanks for trying, See you again")
# Let's Create a file called order.txt - naming is essential
# Let's apply DRY - OOP - Python Packaging
# 1 2 3
|
5f7cba7bdf299c915d0d01cc23b183f17267e3b0 | gibum1228/Python_Study | /lab1.py | 989 | 3.84375 | 4 | number = "Hi" #number의 타입이 문자열
print(number) #문자열 출력
number = 10 #number에 정수를 저장했으므로, number의 타입이 정수형이 되었음
print(number) #정수형 number를 출력
# 변수 a, b에 값을 저장한 후, 합을 c변수에 저장 후, c를 출력
a = 4
b = 5
c = a+b
#4 + 5 = 9와 같이 출력하라.
msg = "%d + %d = %d" #출력하려는 문자열을 변수로 정의할 수 있다.
print(msg %(a, b, c)) #변수를 여러 개 출력하고 싶을 때, %( , , )를 이용해 순서대로 출력한다.
#문자열 출력
money = 10000
print("나는 현재 %d원을 가지고 있습니다." %money) #서식문자를 이용할 수 있다. ,를 대신해 변수이름 앞에 %를 쓴다.
#입력
money = input("얼마를 가지고 계세요?") #input의 결과값은 문자열
print("입력하신 값은 %s입니다." %money) #input의 결과값이 문자열이기 때문에 money의 타입이 문자열이다. 따라서 %s를 사용한다. |
a6dbea4a2b36d99d2a32bb1369893c6dd436b2a2 | Elliot-L/comp551-a3 | /tut_ex.py | 2,568 | 3.90625 | 4 | # not mine, source is the class PyTorch tutorial
from __future__ import print_function
import os, pickle
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import transforms
from torch.autograd import Variable
class TwoLayerNet(torch.nn.Module):
def __init__(self, D_in, H, D_out):
"""
In the constructor we instantiate two nn.Linear modules and assign them as
member variables.
Args:
- D_in : input dimension of the data
- H : size of the first hidden layer
- D_out : size of the output/ second layer
"""
super(TwoLayerNet, self).__init__() # intialize recursively
self.linear1 = torch.nn.Linear(D_in, H) # create a linear layer
self.linear2 = torch.nn.Linear(H, D_out)
def forward(self, x):
"""
In the forward function we accept a Tensor of input data and
return a tensor of output data. We can use
Modules defined in the constructor as well as arbitrary
operators on Variables.
"""
h_relu = self.linear1(x)
y_pred = self.linear2(h_relu)
return y_pred
def toy_ex( batch_size=64, input_dim=1000, hidden_layer_size=100, output_dim=10, epochs=100 ):
"""
Launches toy example of a two-layer-deep FC FF Neural Net
for the purpose of 10-label classification.
Arguments:
batch_size: int representing the batch size (number of instances).
input_dim: int representing the number of features per instance.
hidden_layer_size: int representing the number of neurons in each hidden layer.
output_dim: int representing the number of neurons in the output layer
(and hence the number of labels).
epochs: int representing the number of learning epochs.
Returns:
Nothing.
"""
x = torch.randn( batch_size, input_dim )
y = torch.randn( batch_size, output_dim, requires_grad=False )
model = TwoLayerNet( input_dim, hidden_layer_size, output_dim )
criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=1e-4)
losses = []
for epoch in range( epochs ):
preds = model( x )
loss = criterion( preds, y )
losses.append( loss )
print( f"Epoch\t{epoch};\t\t\tLoss:{loss}" )
optimizer.zero_grad()
loss.backward()
optimizer.step()
if __name__ == '__main__':
toy_ex() |
ebcedf23649e11f819e6faa6c13bff16a053a0b0 | waelnaseeb/TicTacToe-1 | /main.py | 4,062 | 3.984375 | 4 | import random
EMPTY_SLOT = "-"
X_PLAYER = "X"
O_PLAYER = "0"
TIE = "tie"
WIN_COMBINATION_INDICES = [
# Complete row
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
# Complete column
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
# Complete diagonal
[0, 4, 8],
[2, 4, 6]
]
def initialize_board():
board = [EMPTY_SLOT, EMPTY_SLOT, EMPTY_SLOT,
EMPTY_SLOT, EMPTY_SLOT, EMPTY_SLOT,
EMPTY_SLOT, EMPTY_SLOT, EMPTY_SLOT]
return board
def display_board(board):
print("\n")
print(board[0] + " | " + board[1] + " | " + board[2] + " 1 | 2 | 3")
print(board[3] + " | " + board[4] + " | " + board[5] + " 4 | 5 | 6")
print(board[6] + " | " + board[7] + " | " + board[8] + " 7 | 8 | 9")
print("\n")
def handle_turn(player, board):
print(f"{player}, it's your turn.")
handle_the_turn = False
while handle_the_turn ==False:
position = input("Please choose an available number on the board from 1-9: ") # TODO Ask player to input a position (1-9). Ask while the position is not valid (check using valid_position)
if position not in ["1","2","3","4","5","6","7","8","9"]:
print("Invalid input! Please choose an available number in the board from 1-9: ")
else:
position = int(position) - 1
if board[position]!= EMPTY_SLOT:
print("The selected number is not available!")
else:
handle_the_turn = True
board[position] = player # TODO Write player's sign in
return board
def switch_player(player):
if player == X_PLAYER:# TODO Switch the player: X --> 0 or 0 --> X
player = O_PLAYER
else: #player == O_PLAYER:
player = X_PLAYER
return player
def check_for_winner(board):
winner = None
filled_slots = 0
WIN_COMBINATION_INDICES[0][0]=WIN_COMBINATION_INDICES[3][0]=WIN_COMBINATION_INDICES[6][0]= board[0]
WIN_COMBINATION_INDICES[0][1]=WIN_COMBINATION_INDICES[4][0]=board[1]
WIN_COMBINATION_INDICES[0][2]=WIN_COMBINATION_INDICES[5][0]=WIN_COMBINATION_INDICES[7][0]=board[2]
WIN_COMBINATION_INDICES[1][0]=WIN_COMBINATION_INDICES[3][1]=board[3]
WIN_COMBINATION_INDICES[1][1]=WIN_COMBINATION_INDICES[4][1]=WIN_COMBINATION_INDICES[6][1]=WIN_COMBINATION_INDICES[7][1]=board[4]
WIN_COMBINATION_INDICES[1][2]=WIN_COMBINATION_INDICES[5][1]=board[5]
WIN_COMBINATION_INDICES[2][0]=WIN_COMBINATION_INDICES[3][2]=WIN_COMBINATION_INDICES[7][2]=board[6]
WIN_COMBINATION_INDICES[2][1]=WIN_COMBINATION_INDICES[4][2]=board[7]
WIN_COMBINATION_INDICES[2][2]=WIN_COMBINATION_INDICES[5][2]=WIN_COMBINATION_INDICES[6][2]=board[8]
# TODO Check if any of the players got a win combination
for i in WIN_COMBINATION_INDICES:# Hint: loop over WIN_COMBINATION_INDICES to check if one of the combination is X-X-X or O-O-O
if i[0]==i[1]==i[2]==X_PLAYER:
winner=X_PLAYER
elif i[0]==i[1]==i[2]==O_PLAYER:
winner=O_PLAYER
elif EMPTY_SLOT not in board and not winner:# TODO If there is no winner, check if all spots are filled already. This would mean tie (winner = TIE)
winner = TIE
# Hint: count number of filled slots
return winner
def player_random(): # TODO (optional): select who starts randomly --> do this in a separate function
player = random.choice([X_PLAYER,O_PLAYER])
return player
def tic_tac_toe():
winner = None
game_still_going = True
player = player_random()
# Initialize board
board = initialize_board()
while game_still_going:# TODO run this while the game is still going
# Display board
display_board(board)
# Ask the player for a valid position and write it on the board
player = switch_player(player)
board = handle_turn(player, board)
# Check if there is a winner already
winner = check_for_winner(board)
if winner:# TODO stop the game if there is a winner, otherwise switch the player
game_still_going = False
print("THE END")
if winner == TIE:
print("Tie")
else:
print(f"Congratulations {winner}!!")
display_board(board)
# Start game
tic_tac_toe()
|
b86fe90e473350799cccb707072eb40b2314b557 | gatecrasher83/stepik-python | /tests/3.6.py | 214 | 3.890625 | 4 | str1 = "one"
str2 = "two"
str3 = "three"
print(f"Let's count {str1}, then goes {str2}, and then {str3}")
actual_result = "abracadabra"
print(f"Wrong text, got {actual_result}, something wrong")
print(f"{2 + 3}")
|
3589234dc4866f58175ac0997900612b26810e0c | gsy/leetcode | /greedy/splitIntoFibonacci.py | 1,131 | 3.75 | 4 | class Solution:
def isValid(self, sub, result):
if sub[0] == '0':
if sub != '0':
return False
number = int(sub)
if number < 0 or number > 2**31 - 1:
return False
length = len(result)
if length >= 2:
if int(result[-2]) + int(result[-1]) == number:
return True
else:
return False
return True
def backtrack(self, text, path, result):
# 只要找到1个就可以返回了
length = len(text)
if length == 0 and len(path) >= 3:
result.append(path)
return True
# candidates
for i in range(1, length+1):
sub = text[:i]
if self.isValid(sub, path):
done = self.backtrack(text[i:], path + [sub], result)
if done:
return True
return False
def splitIntoFibonacci(self, S):
path, result = [], []
self.backtrack(S, path, result)
if result:
return [int(item) for item in result[0]]
return []
|
dde5a4fc7a08dacd55f806f2f38873654629ed37 | ZL4746/Basic-Python-Programming-Skill | /First_Part/05_Goldbach.py | 2,111 | 4.03125 | 4 | def is_prime(num):
is_prime = True
divisor = 2
limit = int(num**0.5) + 1
while (divisor < limit) and is_prime:
if (num%divisor == 0):
is_prime = False
divisor += 1
return is_prime
def main():
#prompt the user to input lower limit and upper limit
lo = eval(input("Enter the lower limit: "))
up = eval(input("Enter the upper limit: "))
#prompt the user to re-enter if not satisfied the condition
while ( (lo < 4) or (up <= lo) or (lo % 2 != 0) or (up % 2 != 0) ):
print ("Something wrong with the input, please re-enter")
lo = eval(input("Enter the lower limit: "))
up = eval(input("Enter the upper limit: "))
#to print all the even number at the beginning
for num in range (lo, up+1, 2):
#use a string for final output after one line
sum_string = str(num)
#use a loop to test the first prime number
for i in range (2, int(num/2 + 1) ):
if is_prime(i):
#if the first number is prime, use a loop to test the second prime number
for j in range (int(num/2), num):
#initialize the sum before each successful testing
summing = 0
if is_prime(j):
summing = i + j
#add the sum to the sum_string to eventually get output for each line
if (num == summing):
sum_string += (" = "+ str(i) + " + " + str(j) )
#print the final sum_string after all the loop and test
print (sum_string)
main()
|
f5562b1a9330e2bb3b767377e81df25217642930 | Pradhapmaja/Pradhap | /string is numeric.py | 166 | 3.828125 | 4 | num=['1','2','3','4','5','6','7','8','9','0']
s=input()
flag=True
for i in s:
if i not in num:
flag=False
if flag:
print("yes")
else:
print("no")
|
7cfd8346d6846014568ae18c8b8ef23e62cd8cab | qkreltms/problem-solvings | /Programmers/전화번호 목록/1회차.py | 1,331 | 3.578125 | 4 | # 통과 되면 안되는 문제인데 통과가 되어버렸다...
import re
phone_book = ['123', '12', '145', '567', '88']
def solution(phone_book):
phone_book.sort()
if (len(phone_book) == 1):
return True
jubdooau = phone_book[0]
phone_book = phone_book[1:]
for i in phone_book:
if jubdooau == i[0:len(jubdooau)]:
return False
return solution(phone_book)
print(solution(phone_book))
# 다른 사람이 푼 방식
# 정규식 사용문제 (젤 괜찮은듯)
def solution(phoneBook):
for b in phoneBook:
# 정규식 생성
p = re.compile("^"+b)
for b2 in phoneBook:
if b != b2 and p.match(b2):
return False
return True
# 조합을 사용한다
# 예를 들어 [12, 123,145]을 조합하면 ((12,123),(12,145),(123,145))
# 가 나오는데 여기서 비교한다.
# 단 정렬 필수임 왜냐면 [123,12,145]입력시 (123,12)가 나오기 때문에 아래의 로직이 틀릴수 있다.
# 정렬을 안쓰려면 40번째줄 if문을 왼쪽, 오른쪽 두 번비교하면 될듯?
from itertools import combinations as c
def solution(phoneBook):
answer = True
sortedPB = sorted(phoneBook, key=len)
for (a, b) in c(sortedPB, 2):
if a == b[:len(a)]:
answer = False
return answer
|
5f621b601d87c7462eaec42d36afec137feef98c | zqfan/taurus | /code-interview/baidu/baidu.py | 1,528 | 3.875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shitwidth=4 softtabstop=4
def matrix_has_element(matrix, k):
"""return true if k in matrix. else false. O(m*n)"""
return k in [j for i in matrix for j in i]
def ordered_matrix_has_element(matrix, k):
"""return true if k in matrix, else false. O(logm+logn)
matrix should in increasing order in each row and col
"""
if not matrix:
return False
if not matrix[0]: # [[]] is true but [] is false
return False
def find_pos(r, start, end, k):
if start == end:
# if k == r[start], then we find it
# if k > r[start], since the k < r[start+1], we should
# return start
# if k < r[start], then return start-1
return start if k >= r[start] else start - 1
m = (start + end)/2
if k == r[m]:
return m
# it can be just in the m col, if currently is just find the
# col index, but we still search the bigger, because if it
# is less than the bigger, it will return m+1-1=m
elif k > r[m]:
return find_pos(r, m + 1, end, k)
# k < r[m], search the lower bound
else:
return find_pos(r, start, m - 1, k)
col = find_pos(matrix[0], 0, len(matrix[0]) - 1, k)
if col < 0:
return false
col_list = [row[col] for row in matrix]
row = find_pos(col_list, 0, len(matrix) - 1, k)
return matrix[row][col] == k
if __name__ == '__main__':
test()
|
79e13caee28e5e309d63a501bd182b160f971feb | wangyendt/LeetCode | /Biweekly Contests/0-50/biweek 29/1491. Average Salary Excluding the Minimum and Maximum Salary/Average Salary Excluding the Minimum and Maximum Salary.py | 553 | 3.875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: Wayne
@contact: wangye.hope@gmail.com
@software: PyCharm
@file: Average Salary Excluding the Minimum and Maximum Salary
@time: 2020/06/27 22:30
"""
class Solution:
def average(self, salary: list) -> float:
return sum(sorted(salary)[1:-1]) / (len(salary) - 2)
so = Solution()
print(so.average(salary=[4000, 3000, 1000, 2000]))
print(so.average(salary=[1000, 2000, 3000]))
print(so.average(salary=[6000, 5000, 4000, 3000, 2000, 1000]))
print(so.average(salary=[8000, 9000, 2000, 3000, 6000, 1000]))
|
f8bccb8a062b9ca904af7e620a7214faf3766edf | Neckmus/itea_python_basics_3 | /shevchenko_mike/04/4.1.py | 2,326 | 4.1875 | 4 | from collections import Counter
tesla_story = 'Now in it is fourth model year, the Tesla Model three manages to be efficient, luxurious and fun to ' \
'drive. For those reasons and more, the Tesla Model three is Edmunds\' top-rated Luxury ' \
'Electric Vehicle for 2020. ' \
'You can configure a Model three to maximize what you want, whether it be a low price, ' \
'long range or high performance. And in every iteration, the Model three gives you ' \
'access to Tesla\'s proprietary Supercharger charging network and some ' \
'of the best semi-automated driving assistance features around. Of course, the brand cachet ' \
'the Tesla name carries in many parts of the country is probably worth something too. ' \
'The Model three has it is foibles. The lack of hard buttons forces drivers to use ' \
'the touchscreen to operate almost all vehicle functions. ' \
'The Model three should warrant consideration not just from electric-vehicle shoppers ' \
'but anyone looking for a break from the norm.'
# This program will not analyze words such as:
incorrect_words_tesla_story = 'as, a, an, to, be, is, are, was, were, will, would, could, ' \
'and, or, if, he, she, it, this, my, for, the, you'
#print(incorrect_words_tesla_story_two)
"""
comment about this program
"""
words_list = []
tesla_story_correctly =[]
# This is the main object - tesla_story_correctly
print('approach_2')
# .split() - разбиваеть строку
for word in tesla_story.split():
clear_word = ''
for letter in word:
# check whether is there a letter a word symbol if yes-?
if letter.isalpha():
# add only letters and lowercase
clear_word += letter.lower()
words_list.append(clear_word)
print(Counter(words_list))
words_list_two = []
for i in words_list:
if i in incorrect_words_tesla_story:
continue
else:
tesla_story_correctly.append(i)
print(tesla_story_correctly)
"""
tesla_story_edit = len(tesla_story)
print(tesla_story_edit)
print(tesla_story)
"""
"""
print('approach_1')
# approach_1
tesla_story_counter = Counter(tesla_story.lower().split())
print(tesla_story_counter)
"""
|
a1919257ac6b518cd92952c3ac5e5ec1098007c9 | andreLubawski/pyB-sico | /coleções/collections-ordered dict.py | 224 | 3.875 | 4 | from collections import OrderedDict
# garante que a exibição será feita conforme minha inserção
d1 = OrderedDict({'a': 1, 'b': 2, 'd': 4, 'c': 3})
for key, value in d1.items():
print(f'chave:{key} valor:{value}')
|
61d81ed77ba18d430721daba3808ab5cb1f6ef67 | dexman/AdventOfCode | /2016/aoc05.py | 2,262 | 3.90625 | 4 | # --- Day 5: How About a Nice Game of Chess? ---
# You are faced with a security door designed by Easter Bunny engineers that
# seem to have acquired most of their security knowledge by watching hacking
# movies.
# The eight-character password for the door is generated one character at a
# time by finding the MD5 hash of some Door ID (your puzzle input) and an
# increasing integer index (starting with 0).
# A hash indicates the next character in the password if its hexadecimal
# representation starts with five zeroes. If it does, the sixth character in
# the hash is the next character of the password.
# For example, if the Door ID is abc:
# The first index which produces a hash that starts with five zeroes is
# 3231929, which we find by hashing abc3231929; the sixth character of the
# hash, and thus the first character of the password, is 1.
# 5017308 produces the next interesting hash, which starts with 000008f82...,
# so the second character of the password is 8.
# The third time a hash starts with five zeroes is for abc5278568, discovering
# the character f.
# In this example, after continuing this search a total of eight times, the
# password is 18f47a30.
# Given the actual Door ID, what is the password?
################################################################################
import hashlib
import multiprocessing
def door_code_part1(door_id):
code = ''
index = 0
while len(code) < 8:
value = f'{door_id}{index}'.encode()
digest = hashlib.md5(value).hexdigest()
if digest.startswith('00000'):
code += digest[5]
index += 1
return code
def door_code_part2(door_id):
code = [None] * 8
index = 0
while None in code:
value = f'{door_id}{index}'.encode()
digest = hashlib.md5(value).hexdigest()
if digest.startswith('00000'):
try:
code_index = int(digest[5])
except ValueError:
pass
if code_index < len(code) and code[code_index] is None:
code[code_index] = digest[6]
index += 1
return ''.join(code)
print(f'The first door code is {door_code_part1("uqwqemis")}')
print(f'The second door code is {door_code_part2("uqwqemis")}')
|
eeb0fae215fa9341695899a0b8d25b66ba01218a | kielejocain/AM_2015_06_15 | /StudentWork/arielkaplan/PE/pe003.py | 1,050 | 3.671875 | 4 | # Largest prime factor
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
f = open('primes.txt')
# Save primes in a list (of strings)
primes = f.read().split("\n")[:-1]
f.close()
number = 600851475143
print "Let's factor the number " + str(number) + "."
factors = []
remainder = number
i = 0
while remainder > 1 :
prime = int(primes[i])
if remainder % prime == 0 :
factors.append(prime)
remainder /= prime
print "remainder = " + str(remainder)
else:
i += 1
print "Here are the factors of " + str(number) + ": "
print factors
print factors[-1]
###################
number = 600851475143
print ("Let's factor the number " + str(number) +
" without using a list of primes.")
factors = []
remainder = number
divisor = 2
while remainder > 1 :
if remainder % divisor == 0 :
factors.append(divisor)
remainder /= divisor
print "remainder = " + str(remainder)
else:
divisor += 1
print "Here are the factors of " + str(number) + ": "
print factors
print factors[-1]
|
4ff600f35f226903d5bc0af7bb96bfa5cf043d01 | bibash28/python_projects | /function/recursion.py | 122 | 3.6875 | 4 | def factorial(x):
if x==1:
return 1;
else:
return x*factorial(x-1);
def main():
print(factorial(5));
main();
|
d499bcfa92216c181d25990a890cae2065c49de6 | TynanWilke/boost_python_presentation | /example_3_game_entity/main.py | 1,179 | 3.609375 | 4 | import game
from random import randint
class Wizard(game.Entity):
""" Low HP, high power. """
def __init__(self):
super(Wizard, self).__init__("Wizard", 20)
self.min_power = 0
self.max_power = 40
def power(self):
return int(randint(self.min_power, self.max_power))
class Dragon(game.Entity):
""" High HP, lower power which decreases with lower HP. """
def __init__(self):
super(Dragon, self).__init__("Dragon", 200)
self.min_power = 0
self.max_power = 20
def power(self):
return int(randint(self.min_power, self.max_power)*(float(self.hp)/self.max_hp))
class Peasant(game.Entity):
""" Medium HP, pitiful power. """
def __init__(self):
super(Peasant, self).__init__("Peasant", 100)
def power(self):
return 1
if __name__ == "__main__":
# Fair fight
e1 = Wizard()
e2 = Dragon()
# Terrible fight
#e1 = Wizard()
#e2 = Peasant()
# Reasonable fight
#e1 = Peasant()
#e2 = Peasant()
game.fight(e1, e2)
print e1
print e2
"""
# Heal the entities
e1 += 100
e2 += 20
print e1
print e2
"""
|
c56df31765ab8c2b2adc74a0f7793eb90b7112e9 | SeanBackstrom/DS-Unit-3-Sprint-2-SQL-and-Databases | /module1-introduction-to-sql/rpg_queries.py | 3,736 | 3.609375 | 4 | import sqlite3
conn = sqlite3.connect('rpg_db.sqlite3')
curs = conn.cursor()
print("\nPart 1\n")
#how many characters
print("Objective 1:")
count_characters = 'SELECT COUNT(*) FROM charactercreator_character;'
print("Total characters:", curs.execute(count_characters).fetchall())
#How many each subclass
print("\nObjective 2:")
count_mages = 'SELECT COUNT(*) FROM charactercreator_mage;'
print("Total mages:", curs.execute(count_mages).fetchall())
count_clerics = 'SELECT COUNT(*) FROM charactercreator_cleric;'
print("Total clerics:", curs.execute(count_clerics).fetchall())
count_fighters = 'SELECT COUNT(*) FROM charactercreator_fighter;'
print("Total fighters:", curs.execute(count_fighters).fetchall())
count_necromancers = 'SELECT COUNT(*) FROM charactercreator_necromancer;'
print("Total necromancers:", curs.execute(count_necromancers).fetchall())
count_thiefs = 'SELECT COUNT(*) FROM charactercreator_thief;'
print("Total thiefs:", curs.execute(count_thiefs).fetchall())
#How many total items?
print("\nObjective 3:")
count_items = 'SELECT COUNT(*) FROM armory_item;'
print("Total items:", curs.execute(count_items).fetchall())
#How many of the Items are weapons? How many are not?
print("\nObjective 4:")
count_weapons = 'SELECT COUNT() FROM armory_item JOIN armory_weapon ON armory_item.item_id = armory_weapon.item_ptr_id;'
print("Total weapons that are items:", curs.execute(count_weapons).fetchall())
#How many Items does each character have? (Return first 20 rows)
print("\nObjective 4:")
count_weapons = (f"SELECT charactercreator_character.character_id, COUNT(item_id) AS num_items "
f"FROM charactercreator_character "
f"JOIN charactercreator_character_inventory "
f"ON charactercreator_character_inventory.character_id = charactercreator_character.character_id "
f"GROUP BY charactercreator_character.character_id "
f"LIMIT 20")
print("- Left number is character ID, right number is amount of items. -")
print("How many items first 20 characters have: ", curs.execute(count_weapons).fetchall())
#On average, how many Items does each Character have?
print("\nObjective 5:")
average_items = (f"SELECT avg(count) "
f"FROM "
f"( "
f"SELECT charactercreator_character.character_id, COUNT(item_id) AS count "
f"FROM charactercreator_character "
f"JOIN charactercreator_character_inventory "
f"ON charactercreator_character_inventory.character_id = charactercreator_character.character_id "
f"GROUP BY charactercreator_character.character_id "
f")")
print("Average items characters have: ", curs.execute(average_items).fetchall())
#On average, how many Items does each Character have?
print("\nObjective 6:")
average_weapons = (f"SELECT avg(count) "
f"FROM "
f"( "
f"SELECT charactercreator_character.character_id, COUNT(item_id) AS count "
f"FROM charactercreator_character "
f"JOIN charactercreator_character_inventory "
f"ON charactercreator_character_inventory.character_id = charactercreator_character.character_id "
f"WHERE item_id BETWEEN 138 AND 174 "
f"GROUP BY charactercreator_character.character_id "
f")")
print("Average weapons characters have: ", curs.execute(average_weapons).fetchall())
|
cf3f0515a95030a26395eabad2e586a17d098a68 | waterspout11/hyperskill-Smart-Calculator | /calculator.py | 10,220 | 3.5 | 4 | from collections import deque
class SmartCalculator():
OPERATOR = '+-*/^()'
map_priotity = {
'-': 3,
'+': 3,
'*': 4,
'/': 4,
'^': 5,
}
def __init__(self):
self.var_dict = {}
self.postfix_out = deque() # for postfix notation
self.stack_oper = deque() # stack for operand
# self.result_oper = deque() # for calculate postfix notation
self.oper_plus = None # flag of operators, for func callculate
self.flag_sucsess_check = True # flag of sucsess chech input line
self.inv_expres = 'Invalid expression'
self.line = []
while True:
self.line_input = input()
if self.line_input.startswith('/'): # block for command, begin with '/'
if self.line_input[1:] == 'exit':
self.exit_calc()
elif self.line_input[1:] == 'help':
self.help_calc()
else:
print('Unknown command')
elif '=' in self.line_input:
self.variable()
elif self.line_input == '':
continue
else:
self.evaluate_line()
def evaluate_line(self):
'''
Code errors on flag_sucsess_check:
0 - no errors
1 - Invalid expression ()
2 - Unkown variable
'''
self.flag_sucsess_check = 0
self.check_line()
if self.flag_sucsess_check == 0:
self.postfix_quere()
if self.flag_sucsess_check == 0:
self.callculate()
elif self.flag_sucsess_check == 1:
print('Invalid expression')
else:
print('Invalid expression')
def postfix_quere(self): # transform line in reverse polish notation
self.postfix_out.clear()
self.stack_oper.clear()
self.count = 0
while True:
try:
self.value = self.line[self.count]
except IndexError:
while True:
try:
self.postfix_out.append(self.stack_oper.pop())
except IndexError:
break
self.finish_to_postfix = True
break
else:
if self.is_digit(self.value):
self.postfix_out.append(int(self.value))
elif self.value in self.var_dict.keys():
self.postfix_out.append(self.var_dict[self.value])
elif self.value in self.OPERATOR:
if self.value == '(':
self.stack_oper.append(self.value)
elif self.value == ')':
while True:
if self.stack_oper[-1] != '(':
self.postfix_out.append(self.stack_oper.pop())
elif self.stack_oper[-1] == '(':
self.stack_oper.pop()
break
elif len(self.stack_oper) == 0:
self.stack_oper.append(self.value)
else:
if self.stack_oper[-1] == '(':
self.stack_oper.append(self.value)
else:
if self.map_priotity[self.value] > self.map_priotity[self.stack_oper[-1]]:
self.stack_oper.append(self.value)
elif self.map_priotity[self.value] <= self.map_priotity[self.stack_oper[-1]]:
while True:
try:
self.stack_oper[-1]
except IndexError:
break
else:
if self.stack_oper[-1] == '(':
break
elif self.map_priotity[self.value] <= self.map_priotity[self.stack_oper[-1]]:
self.postfix_out.append(self.stack_oper.pop())
else:
break
self.stack_oper.append(self.value)
else:
print('Unknown variable')
self.flag_sucsess_check = 2
break
self.count += 1
def callculate(self):
self.stack_oper.clear()
while True:
try:
self.postfix_out[0]
except IndexError:
break
else:
if self.is_digit(self.postfix_out[0]):
self.stack_oper.append(self.postfix_out.popleft())
elif self.postfix_out[0] in self.OPERATOR:
try:
self.second = self.stack_oper.pop()
self.first = self.stack_oper.pop()
except IndexError:
print('Invalid expression')
break
else:
if self.postfix_out[0] == '-':
self.stack_oper.append(self.first - self.second)
elif self.postfix_out[0] == '+':
self.stack_oper.append(self.first + self.second)
elif self.postfix_out[0] == '*':
self.stack_oper.append(self.first * self.second)
elif self.postfix_out[0] == '/':
self.stack_oper.append(self.first / self.second)
elif self.postfix_out[0] == '^':
self.stack_oper.append(self.first ** self.second)
self.postfix_out.popleft()
print(self.if_int(self.stack_oper[0]))
def check_line(self):
self.line.clear()
self.count = 0
self.number = '' # stack for number
self.variable_name = '' # stack for name variable
self.operator_name = ''
while True:
try:
self.line_input[self.count]
except IndexError:
if len(self.number) != 0:
self.line.append(self.number)
self.number = ''
elif len(self.variable_name) != 0:
self.line.append(self.variable_name)
self.variable_name = ''
break
else:
if self.line_input[self.count] in '0123456789.':
self.number += self.line_input[self.count]
elif self.line_input[self.count].isalpha():
self.variable_name += self.line_input[self.count]
elif self.line_input[self.count] in '-+*/^() ':
if self.line_input[self.count] in '-+*/^':
self.operator_name += self.line_input[self.count]
if len(self.number) != 0:
self.line.append(self.number)
self.number = ''
elif len(self.variable_name) != 0:
self.line.append(self.variable_name)
self.variable_name = ''
if self.line_input[self.count] != ' ':
self.line.append(self.line_input[self.count])
elif self.line_input[self.count] == ' ':
if len(self.operator_name) > 1:
self.flag_sucsess_check = 1
break
else:
self.operator_name = ''
self.count += 1
self.stack_oper.clear()
for elem in self.line:
if elem == '(':
self.stack_oper.append(elem)
elif elem == ')':
try:
self.stack_oper.pop()
except IndexError:
self.flag_sucsess_check = 1
break
if len(self.stack_oper) != 0:
self.flag_sucsess_check = 1
def is_digit(self, str):
try:
float(str)
return True
except ValueError:
return False
def if_int(self, digit):
if int(digit) == digit:
return int(digit)
else:
return digit
def variable(self): # check, set, update variable in var_dict
if self.line_input.count('=') > 1:
print('Invalid assignment')
else:
self.line_input = self.line_input.replace(' ', '')
self.line_input = self.line_input.split('=')
self.sym_var = self.line_input[0].strip()
self.dig_var = self.line_input[1].strip()
# test if slice witn name variable is symbol without number
if not self.sym_var.isalpha():
print('Invalid identifier')
else:
# check if value is symbol and variable
if self.dig_var in self.var_dict.keys():
self.var_dict[self.sym_var] = self.var_dict[self.dig_var]
# test if value variable is digit
elif not self.dig_var.isdigit():
print('Invalid assignment')
# if tests Ok< create variable
else:
if self.dig_var.count('.') != 0:
self.var_dict[self.sym_var] = float(self.dig_var)
else:
self.var_dict[self.sym_var] = int(self.dig_var)
def exit_calc(self):
print('Bye!')
quit()
def help_calc(self):
print('''
The program calculates the sum of numbers
and get substraction of number
like then:
1 + 1 + 2 - 1
125 - 60
must be space beetwine numbers and math operators
Program can use variables in operions
''')
if __name__ == '__main__':
calc = SmartCalculator()
|
49c9680f845cbae1551e32881a8af3bb27f37ba6 | rtroshynski/one-python-project-a-day | /2019-06-13-Python_Playing_Cards.py | 1,438 | 3.75 | 4 |
# https://stackoverflow.com/questions/50769728/how-to-randomly-shuffle-a-deck-of-cards-among-players
import random
class Card:
def __init__(self, kind, rank, deck):
self._kind = kind
self._rank = rank
self.deck = deck
self.where = None
def __repr__(self):
return 'Card(kind={}, rank={}'.format(self.kind, self.rank)
@property
def kind(self):
return self._kind
@property
def rank(self):
return self._rank
class Deck:
def __init__(self):
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
kinds = ['H', 'C', 'D', 'S']
self.cards = [Card(kind, rank, self) for kind in kinds for rank in ranks]
def deal(self, players, n=None):
if any(p.deck is not self for p in players):
raise RuntimeError('Player {} is not playing the deck'.format(p.id))
n = n if n is not None else len(self.cards)
random.shuffle(self.cards)
for i, card in enumerate(self.cards[:n * len(players)]):
card.where = players[i % len(players)]
class Player:
def __init__(self, id, deck):
self.id = id
self.deck = deck
@property
def hand(self):
return [card for card in deck.cards if card.where is self]
deck = Deck()
players = [Player(id, deck) for id in range(3)]
deck.deal(players, n=4)
for p in players:
print(p.hand)
|
d3b6868ba04186532d3973eff67971c52098f1db | umbs/practice | /IK/DP/HW/CountWaysToClimb.py | 347 | 3.796875 | 4 | def countWaysToClimb(steps, n):
res = [0] * (n+1)
for i in range(0, n+1):
for s in steps:
if i == s:
res[i] += 1
elif i > s:
res[i] += res[i-s]
return res[n]
if __name__ == "__main__":
steps = [2, 3]
n = 7
res = countWaysToClimb(steps, n)
print(res)
|
dd2f7415a21602c8c4ff4dad93d259ec7fea3846 | romwil22/python-textbook-exercises | /chapter6/exercise3.py | 365 | 4.25 | 4 | """Encapsulate this code in a function named count, and
generalize it so that it accepts the string and the letter as arguments."""
fruit = 'banana'
# Count how many letter "a" in a strings
def count(f):
count = 0
for letter in f:
if letter == 'a':
count += 1
return count
# Print output
a_count = count(fruit)
print(a_count)
|
2a50ba09aa5804116a13bcde6936cf0034a7eeea | steve3p0/LING576 | /corpus_project/single2bitext.py | 4,302 | 3.78125 | 4 | import nltk
# Reference:
# This code comes from here:
# https://github.com/flycrane01/nltk-passive-voice-detector-for-English
def isPassive(sentence):
# all forms of "be"
beforms = ['am', 'is', 'are', 'been', 'was', 'were', 'be', 'being']
# NLTK tags "do" and "have" as verbs, which can be misleading in the following section.
aux = ['do', 'did', 'does', 'have', 'has', 'had']
words = nltk.word_tokenize(sentence)
tokens = nltk.pos_tag(words)
tags = [i[1] for i in tokens]
# no PP, no passive voice.
if tags.count('VBN') == 0:
return False
# one PP "been", still no passive voice.
elif tags.count('VBN') == 1 and 'been' in words:
return False
else:
# gather all the PPs that are not "been".
pos = [i for i in range(len(tags)) if tags[i] == 'VBN' and words[i] != 'been']
for end in pos:
chunk = tags[:end]
start = 0
for i in range(len(chunk), 0, -1):
last = chunk.pop()
# get the chunk between PP and the previous NN or PRP (which in most cases are subjects)
if last == 'NN' or last == 'PRP':
start = i
break
sentchunk = words[start:end]
tagschunk = tags[start:end]
# get all the verbs in between
verbspos = [i for i in range(len(tagschunk)) if tagschunk[i].startswith('V')]
# if there are no verbs in between, it's not passive
if verbspos != []:
for i in verbspos:
# check if they are all forms of "be" or auxiliaries such as "do" or "have".
if sentchunk[i].lower() not in beforms and sentchunk[i].lower() not in aux:
break
else:
return True
return False
def single2bitext(src, tgt, merge_p, merge_np):
with open(merge_p, 'w', encoding="utf8") as passive, \
open(merge_np, 'w', encoding="utf8") as not_passive, \
open(src, encoding="utf8") as f1, \
open(tgt, encoding="utf8") as f2:
for line1, line2 in zip(f1, f2):
if isPassive(line2):
passive.write("{0}\t{1}\n".format(line1.rstrip(), line2.rstrip()))
else:
not_passive.write("{0}\t{1}\n".format(line1.rstrip(), line2.rstrip()))
if __name__ == '__main__':
# source = 'enhr/prep/paracrawl.test10k.hr'
# target = 'enhr/prep/paracrawl.test10k.en'
# merge = "enhr/prep/paracrawl.test10k.hr-en.txt"
# source = 'enhr/prep/paracrawl.tune10k.hr'
# target = 'enhr/prep/paracrawl.tune10k.en'
# merge = "enhr/prep/paracrawl.tune10k.hr-en.txt"
# source = 'enhr/prep/paracrawl.train.hr'
# target = 'enhr/prep/paracrawl.train.en'
# merge = "enhr/prep/paracrawl.train.hr-en.txt"
# source = 'enhr/prep/ted2013.tune.hr'
# target = 'enhr/prep/ted2013.tune.en'
# merge = "enhr/prep/ted2013.tune.hr-en.txt"
###################################################333
# source = 'enhr/prep/paracrawl.test10k.hr'
# target = 'enhr/prep/paracrawl.test10k.en'
# merge_passive = "enhr/prep/paracrawl.test10k.passive.hr-en.txt"
# merge_not_passive = "enhr/prep/paracrawl.test10k.not-passive.hr-en.txt"
# source = 'enhr/prep/paracrawl.tune10k.hr'
# target = 'enhr/prep/paracrawl.tune10k.en'
# merge_passive = "enhr/prep/paracrawl.tune10k.passive.hr-en.txt"
# merge_not_passive = "enhr/prep/paracrawl.tune10k.not-passive.hr-en.txt"
# source = 'enhr/prep/ted2013.test.hr'
# target = 'enhr/prep/ted2013.test.en'
# merge_passive = "enhr/prep/ted2013.test.passive.hr-en.txt"
# merge_not_passive = "enhr/prep/ted2013.test.not-passive.hr-en.txt"
# source = 'enhr/prep/ted2013.tune.hr'
# target = 'enhr/prep/ted2013.tune.en'
# merge_passive = "enhr/prep/ted2013.tune.passive.hr-en.txt"
# merge_not_passive = "enhr/prep/ted2013.tune.not-passive.hr-en.txt"
source = 'enhr/prep/paracrawl.train.hr'
target = 'enhr/prep/paracrawl.train.en'
merge_passive = "enhr/prep/paracrawl.train.passive.hr-en.txt"
merge_not_passive = "enhr/prep/paracrawl.train.not-passive.hr-en.txt"
single2bitext(source, target, merge_passive, merge_not_passive)
|
e1825d563d3ffd8e2290d2c347671eb48ff9ff6f | malikxomer/static | /10.Excersices/8.Usain Bolt races me and a guy.py | 844 | 4.03125 | 4 | # give choice to get back a name
def number_to_choice(choice):
if choice==1:
return 'Usain'
elif choice==2:
return 'Me'
elif choice==3:
return 'Qazi'
else:
return 'Not a member of race'
# give name to get back a position
def choice_to_number(choice):
if choice=='Usain':
return 1
elif choice=='Me':
return 2
elif choice=='Qazi':
return 3
else:
return 'Not a member of race'
print(number_to_choice(2))
print(choice_to_number('Qazi'))
##########################
#Using dictionary to solve the same problem
def num_to_choice(number):
return {1:'Usain',2:'Me',3:'Qazi'}[number]
def choice_to_num(name):
return {'Usain':1,'Me':2,'Qazi':3}[name]
print(num_to_choice(3))
print(choice_to_num('Usain'))
|
5f04bd96a9c97e39e62a63d3564d67825f27c733 | ArrayZoneYour/LeetCode | /337/House Robber III.py | 987 | 3.984375 | 4 | # /usr/bin/python
# coding: utf-8
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rob_node(self, node):
if not node.left:
rob_node_left, not_rob_node_left = 0, 0
else:
rob_node_left, not_rob_node_left = self.rob_node(node.left)
if not node.right:
rob_node_right, not_rob_node_right = 0, 0
else:
rob_node_right, not_rob_node_right = self.rob_node(node.right)
return node.val + not_rob_node_left + not_rob_node_right, \
max(rob_node_left, not_rob_node_left) + max(rob_node_right, not_rob_node_right)
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return root.val
rob_root, not_rob_root = self.rob_node(root)
return max(rob_root, not_rob_root)
|
a2fb9ceb92954f5163f0a072b73240a0c6d0516b | RaquelFonseca/P1 | /Unidade6a10/Agenda-telefonica.py | 883 | 3.734375 | 4 | # coding: utf-8
# Agenda Telefonica
agend_nom = []
agend_num = []
def insertion_sort(lista1):
for j in range(1, len(lista1)):
chave = lista1[j]
i = j - 1
while lista1[i] > chave and i >= 0:
lista1[i + 1] = lista1[i]
i -= 1
lista1[i + 1] = chave
return lista1
while True:
comando = raw_input()
if comando == "finalizar":
break
elif comando == "inserir":
quant = int(raw_input())
for i in range(quant):
agend_nom.append(raw_input())
agend_num.append(raw_input())
elif comando == "buscar":
nome = raw_input()
indice = "X"
for i in range(len(agend_nom)):
if agend_nom[i] == nome:
print "Nomé: %s\nFone: %s" % (agend_nom[i], agend_num[i])
print "----------"
if indice == "X":
print "Nome inexistente"
print "----------"
else:
for i in range(len(agend_nom)):
print "Nome: %s\nFone: %s" % (agend_nom[i], agend_num[i])
|
223d35bf87ccd66e251bc87f00dc0b142a679d73 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/89f705c829cb4995bfb0daacbbfaafdd.py | 623 | 4.0625 | 4 | #
# Skeleton file for the Python "Bob" exercise.
def hey(answer):
# Get rid of all the leading and trailing white space in a string
answer = answer.strip()
# Answer if string is in all UPPERCASE letters
if answer.isupper():
return "Whoa, chill out!"
# Answer if string ends with a question mark
if answer.endswith("?"):
return "Sure."
# Answer if the string does not contain text
if answer.isspace() or len(answer)==0:
return "Fine. Be that way!"
# Answer for anything else in the string that is not covered above
return "Whatever."
|
2f4df165a03378fef88f51970fcd5a494af5738b | ericsporto/Python | /Variaveis_1.py | 3,798 | 4.21875 | 4 | # fazer um programa onde o computador vai pensar em um número inteiro de 0 a 5
# peça para o usuário tentar descobrir este numero
# mostre se o usuario acertou ou não
import random
print("Vamos jogar? Estou pensando em um número de 0 a 5. Quer tentar adivinhar?")
n = int(input("Digite um número de 0 a 5: "))
lista = [0, 1, 2, 3, 4, 5]
comp = (random.choice(lista))
if n == comp:
print("Parabéns! Você acertou! Eu escolhi {} e você digitou {}!.".format(comp, n))
elif n > 5:
print("Opa! O número precisa ser de 0 a 5!")
else:
print("Não foi desta vez! Eu escolhi {} e você digitou {}! Tente outra vez!".format(comp, n))
# fazer um programa que vai ler a velocidade de um carro.
# se ele ultrapassar 80Km/h mostre uma mensagem dizendo que ele foi multado
# a multa vai custa R$ 7.00 por Km acima do limite
v = float(input("Velocidade: "))
v_limite = 80
multa = (v - v_limite) * 7
if v > v_limite:
print("Sua velocidade foi de {}Km/h e você passou do limite de {}Km/h permitido".format(v, v_limite))
print("Sua multa foi de R${:.2f}.".format(multa))
else:
print("Você está dentro do limite de {}Km/h permitido e não foi multado!".format(v_limite))
# criar um programa que lê um número inteiro e mostre se ele é par ou impar
numero = int(input("Digite um número: "))
divisao = numero % 2
if divisao == 0:
print("O número digitado {} é par".format(numero))
else:
print("O número digitado {} não é par".format(numero))
# criar um prgrama que pergunte a ditância da uma viagem em Km.
# calcular o preço da passagem cobrando R$0.50 por Km até 200Km e
# R$0.45 por Km para viagens mais longas.
km = float(input("Qual a kilometragem da sua viagem em Km? "))
curta = km * 0.50
longa = km * 0.45
if km <= 200:
print("O valor da passagem é R${:.2f}".format(curta))
else:
print("O valor da passagem é R${:.2f}".format(longa))
# fazer um programa que leia um ano qulquer e diga se ele é Bissexto
ano = int(input("Digite um ano: "))
dezena_por_4 = ano % 4
if dezena_por_4 == 0:
print("O ano de {} é BISSEXTO".format(ano))
else:
print("O ano de {} NÃO é BISSEXTO".format(ano))
# fazer um programa que leia três número e diga qual é o maior e qual é o menor
n1 = int(input("Escreva o primeiro número: "))
n2 = int(input("Escreva o segundo número: "))
n3 = int(input("Escreva o terceiro número: "))
maior = n1
if n2 > n1 and n2 > n3:
maior = n2
if n3 > n1 and n3 > n2:
maior = n3
print("O maior valor digitado foi {}".format(maior))
menor = n1
if n2 < n1 and n2 < n3:
menor = n2
if n3 < n1 and n3 < n2:
menor = n3
print("O menor valor digitado foi {}".format(menor))
# fazer um programa que pergunte o salário e calcule o seu aumento:
# quem recebe mais de R$1250,00 receberá um aumento de 10%
# para inferiores ou iguais, aumento de 15%
salario = float(input("Digite o seu salário:R$ "))
s_maior = (salario * (10/100)) + salario
s_menor = (salario * (15/100)) + salario
if s_maior > 1250.00:
print("Seu novo salário com aumento de 10% será de R${:.2f}".format(s_maior))
if s_menor <= 1250.00:
print("Seu novo salário com aumento de 15% será de R${:.2f}".format(s_menor))
# criar um programa que leia três retas e diga se podem ou não formar um triângulo
reta1 = float(input("Digite o tamanho em metros da primeira reta:"))
reta2 = float(input("Digite o tamanho em metros da segunda reta:"))
reta3 = float(input("Digite o tamanho em metros da terceira reta:"))
condicao = reta1 + reta2 > reta3 and reta2 + reta3 > reta1 and reta3 + reta1 > reta2
if condicao == True:
print("Essas medidas: {}, {} e {} podem formar um triângulo".format(reta1, reta2, reta3))
else:
print("Essas medidas: {}, {} e {} NÃO podem formar um triângulo".format(reta1, reta2, reta3))
|
ee27ec7c417492b45250419fd8ad7e20674d4406 | jayakrishna35/Coding | /tuple.py | 76 | 3.515625 | 4 | tuple=(4,6,8)
print(tuple[2])
list=[(3,5),(9,0),(7,4)]
print(list[0]
)
|
f3f599dc9010e9ef3a9abaae85502376f000f117 | Arfameher/challenge-card-game-becode | /utils/card.py | 1,107 | 4.125 | 4 | import typing
# Parent Class
class Symbol:
"""
Class defining the color and icon of the card.
Using the icon, the variable color is set to respective color.
♦ ♥ --> Red
♣ ♠ --> Black
"""
def __init__(self, icon: str):
# icon = "♥, ♦, ♣, ♠"
self.icon = icon
if self.icon == '♥' or self.icon == '♦':
color = "Red"
else:
color = "Black"
self.color = color
def __str__(self):
return f"{self.color} {self.icon} "
# Child Class
class Card(Symbol):
"""
Class defining the value of the card.
The values can range in A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K
"""
# value = "A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K"
def __init__(self, value: str, icon: str):
super().__init__(icon)
self.value = value
def __str__(self):
if self.color == "Red":
return f" {self.value} \033[1;31m{self.icon}\033[0m " # To print the symbol in colour Red.
else:
return f" {self.value} {self.icon} " |
ac0a032d1c05762e48be1f1b2f77b06c0ba071b6 | zranguai/python-learning | /day34/04 数据共享.py | 1,181 | 3.640625 | 4 | # 可以通过Manager进行数据共享
from multiprocessing import Process, Manager, Lock
def change_dic(dic, lock):
with lock:
dic['count'] -= 1
if __name__ == '__main__':
# 用法1:
# m = Manager()
# lock = Lock()
# dic = m.dict({'count': 100})
# # dic = {'count': 100}
# p_l = []
# for i in range(100):
# p = Process(target=change_dic, args=(dic, lock))
# p.start()
# p_l.append(p)
# for i in p_l:
# i.join()
# # print(dic) # {'count': 100} 没有Manager不会改变,因为进程的数据之间相互独立
# print(dic) # {'count': 0} 有Manager 数据之间会共享
# 用法2:
with Manager() as m:
lock = Lock()
dic = m.dict({'count': 100})
# dic = {'count': 100}
p_l = []
for i in range(100):
p = Process(target=change_dic, args=(dic, lock))
p.start()
p_l.append(p)
for i in p_l:
i.join()
# print(dic) # {'count': 100} 没有Manager不会改变,因为进程的数据之间相互独立
print(dic) # {'count': 0} 有Manager 数据之间会共享
|
ee4cbce12ffb2be4e8642edc79d4d9cd04ea42e3 | TingGingLiao/Computer-Thinking | /廖挺均Week15.py | 611 | 3.5 | 4 | import turtle
shelly = turtle.Turtle()
shelly.shape("turtle")
shelly.position()
shelly.color("green", "red")
shelly.pencolor("black")
shelly.turtlesize(10,10,2)
shelly.resizemode("auto")
shelly.turtlesize(5,5,3)
shelly.forward(100)
shelly.left(90)
shelly.circle(250)
shelly.circle(250, 180, 30)
shelly.end_fill()
shelly.write("Turtle Rock")
import turtle
shelly = turtle.Turtle()
for i in range(4):
shelly.forward(250)
shelly.left(90)
print (i)
import turtle
shelly = turtle.Turtle()
shelly.color("red")
for i in range(4):
shelly.forward(250)
shelly.left(90)
|
825b0375e44a6db539bedfc9d014da2f72a56792 | gstvmoura/ppzombies | /ppzombies/LISTA 1 PYTHON PARA ZOMBIES/Total em segundos.py | 248 | 3.71875 | 4 | d = int(input("Escreva a quantidade de dias: "))
h = int(input("Escreva a quantidade de horas: "))
m = int(input("Escreva a quantidade de minutos: "))
s = int(input("Escreva a quantidade de segundos: "))
tt = d*24*60*60 + h*60*60 + s*60
print(tt)
|
42a6b9f7043f94aba1707135a07dd0dd7ba3558c | dhruvbaldawa/challenges | /dailyprogrammer/rail_fence_cipher.py | 4,355 | 3.875 | 4 | """ (Intermediate): Rail Fence Cipher Before the days of computerised
encryption, cryptography was done manually by hand. This means the methods of
encryption were usually much simpler as they had to be done reliably by a
person, possibly in wartime scenarios. One such method was the rail-fence
cipher[1] . This involved choosing a number (we'll choose 3) and writing our
message as a zig-zag with that height (in this case, 3 lines high.) Let's say
our message is REDDITCOMRDAILYPROGRAMMER. We would write our message like this:
R I M I R A R
E D T O R A L P O R M E
D C D Y G M
See how it goes up and down? Now, to get the ciphertext, instead of reading with
the zigzag, just read along the lines instead. The top line has RIMIRAR, the
second line has EDTORALPORME and the last line has DCDYGM. Putting those
together gives you RIMIRAREDTORALPORMEDCDYGM, which is the ciphertext. You can
also decrypt (it would be pretty useless if you couldn't!). This involves
putting the zig-zag shape in beforehand and filling it in along the lines. So,
start with the zig-zag shape:
? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ?
The first line has 7 spaces, so take the first 7 characters (RIMIRAR)
and fill them in.
R I M I R A R
? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ?
The next line has 12 spaces, so take 12 more characters (EDTORALPORME)
and fill them in.
R I M I R A R
E D T O R A L P O R M E
? ? ? ? ? ?
Lastly the final line has 6 spaces so take the remaining 6 characters
(DCDYGM) and fill them in.
R I M I R A R
E D T O R A L P O R M E
D C D Y G M
Then, read along the fence-line (zig-zag) and you're done!
Input Description
You will accept lines in the format:
enc # PLAINTEXT
or
dec # CIPHERTEXT
where enc # encodes PLAINTEXT with a rail-fence cipher using # lines,
and dec # decodes CIPHERTEXT using # lines.
For example:
enc 3 REDDITCOMRDAILYPROGRAMMER
Output Description
Encrypt or decrypt depending on the command given. So the example above gives:
RIMIRAREDTORALPORMEDCDYGM
Sample Inputs and Outputs
enc 2 LOLOLOLOLOLOLOLOLO
Result: LLLLLLLLLOOOOOOOOO
enc 4 THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG
Result: TCNMRZHIKWFUPETAYEUBOOJSVHLDGQRXOEO
dec 4 TCNMRZHIKWFUPETAYEUBOOJSVHLDGQRXOEO
Result: THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG
dec 7 3934546187438171450245968893099481332327954266552620198731963475632908289907
Result: 3141592653589793238462643383279502884197169399375105820974944592307816406286 (pi)
"""
import itertools
# magic transformation for n=3, the sequence is [0, 1, 2, 1]
# for n=4, the sequence will be [0, 1, 2, 3, 2, 1]
# pass output of range() function to the sequence lambda
sequence = lambda x: x + x[::-1][1:-1]
def encrypt(text, nlines):
r_nlines = range(nlines)
lines = ['' for _ in r_nlines]
seq = sequence(r_nlines)
iter_cycle = itertools.cycle(seq)
for x in text:
lines[iter_cycle.next()] += str(x)
return ''.join(lines)
def decrypt(text, nlines):
r_nlines = range(nlines)
seq = sequence(r_nlines)
# starts = sequence
# get the cycle
iter_cycle = itertools.cycle(seq)
# get an encrypted sequence
list_cycle = [iter_cycle.next() for _ in range(len(text))]
enc_list_cycle = encrypt(list_cycle, nlines)
# zip the sequence and the encrypted sequence to get the line
# correspondence
zenc_list = zip(text, enc_list_cycle)
# group the sequence by line numbers
lines = {i: list(items) for i, items in itertools.groupby(zenc_list,
lambda x: x[1])}
# reinitialize the cycle
iter_cycle = itertools.cycle(seq)
decrypted = ''
for _ in range(len(text)):
current = str(iter_cycle.next())
# get the current line and remove the first element from it
decrypted += str(lines[current].pop(0)[0])
return decrypted
if __name__ == '__main__':
testcases = [
(3, 'REDDITCOMRDAILYPROGRAMMER'),
(2, 'LOLOLOLOLOLOLOLOLO'),
(4, 'THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG'),
(7, '3934546187438171450245968893099481332327954266552620198731963475632908289907')
]
for n, testcase in testcases:
assert testcase == decrypt(encrypt(testcase, n), n)
print 'All tests pass!'
|
eb2f4676f8e4140d778d4e1da05425c8c693d4c2 | Ashudeshwal/DFA-Function-Solution | /dfaCode.py | 2,551 | 4 | 4 | '''
Write a function solution that, given a string S consisting of N letters 'a' and/or 'b' returns Accepted
when all occurrences of letter 'a' are before all occurrences of letter 'b' and return Not Accepted otherwise.
Examples
1. Given S = "aabbb", the function should return Accepted.
2. Given S = "ba", the function should return Not Accepted.
3. Given S = "aaa", the function should return Accepted. Note that 'b' does not need to occur in S
4. Given S = "b", the function should return Accepted. Note that 'a' does not need to occur in S
5. Given S = "abba", the function should return Not Accepted
'''
# Function for state zero Q0
def startStateQ0(s):
if (s == 'a'):
state = 1
elif (s == 'b'):
state = 3
else:
state = -1
return state
# Function for first state Q1
def firstStateQ1(s):
if (s == 'a'):
state = 2
elif (s == 'b'):
state = 4
else:
state = -1
return state
# Function for second state Q2
def secondStateQ2(s):
if (s == 'b'):
state = 3
elif (s == 'a'):
state = 1
else:
state = -1
return state
# Function for third state Q3
def thirdStateQ3(s):
if (s == 'b'):
state = 3
elif (s == 'a'):
state = 4
else:
state = -1
return state
# Function for fourth state Q4
def fourthStateQ4(s):
if(s == 'a'):
state = 2
elif(s == 'b'):
state = 3
else:
state = -1
return state
def isAcceptedString(String):
l = len(String)
# dfa tells the number associated
# with the present dfa = state
state = 0
for i in range(l):
if (state == 0):
state = startStateQ0(String[i])
elif (state == 1):
state = firstStateQ1(String[i])
elif (state == 2) :
state = secondStateQ2(String[i])
elif (state == 3) :
state = thirdStateQ3(String[i])
elif (state == 4) :
state = fourthStateQ4(String[i])
else:
return 0
if(state == 3 or state == 1) :
return 1
else:
return 0
# Driver code
if __name__ == "__main__" :
String = input("Enter the string: ")
if (isAcceptedString(String)) :
print("ACCEPTED")
else:
print("NOT ACCEPTED")
|
ce0cc3e4fd3a9a5e207df05abffaed2e5b4b734f | PigsGoMoo/LeetCode | /unique-word-abbreviation/unique-word-abbreviation.py | 712 | 3.59375 | 4 | class ValidWordAbbr:
def __init__(self, dictionary: List[str]):
self.table = collections.defaultdict(list)
for word in dictionary:
abbrev = word[0] + str(len(word) - 2) + word[-1]
if word not in self.table[abbrev]:
self.table[abbrev].append(word)
def isUnique(self, word: str) -> bool:
abbrev = word[0] + str(len(word) - 2) + word[-1]
if abbrev not in self.table or (len(self.table[abbrev]) == 1 and self.table[abbrev][0] == word):
return True
return False
# Your ValidWordAbbr object will be instantiated and called as such:
# obj = ValidWordAbbr(dictionary)
# param_1 = obj.isUnique(word) |
bef69bd7fe3f8f8be03e1093d926ef23337ebb2a | ygberg/labbar | /code alongs and misc/second_lowest_garde.py | 323 | 3.53125 | 4 |
names = []
scores = []
for _ in range(int(input())):
name = input()
score = float(input())
scores.append(score)
names.append(name)
st = dict(zip(names,scores))
sv = sorted(st.values())
sk= sorted(st, key=str.lower)
ab= list(dict.fromkeys(sv))
s_l = ab[2]
for s_l in sk:
print(st.items(s_l))
|
13c5b12164bf6a2510356b36bdb0c7020e63038c | vrrohan/Python100DaysOfCode | /Day25-ClassesAndObjects/Py2ClassInit.py | 4,225 | 4.78125 | 5 | #How to initialize a class
#The instantiation of the class happened at the line - per = Person().
#You may have noticed that the property stored_name does not exist in the object until we assign a value to it.
#This can give very serious headaches if someone calls the method get_name before actually having a name stored (you can give it a try to see what happens!)
#Therefore it is very useful to run a default method when the class is first called. This method is called __init__ [which is similar to constructor in Java, self is equivalent to this operator in java]
class Person :
"""Creating a person class"""
def __init__(self, name, age) :
"""Initialize name and age attributes"""
self.name = name
self.age = age
def displayPersonInfo(self) :
"""method that display person's information"""
print('person name is', self.name, ',person age is', self.age)
def getPersonAccess(self) :
"""method that displays whether person can access documents or not"""
if self.age > 40 :
print(self.name, 'can access documents.')
else :
print('person cannot access documents')
per = Person('elon', 48)
per2 = Person('bill', 35)
per.displayPersonInfo()
per2.displayPersonInfo()
per.getPersonAccess()
per2.getPersonAccess()
#triple quotes at starting of class and all methods acts like a docstring, which describes what this class is doing or method does.
#A function that’s part of a class is a method. Everything you learned about functions applies to methods as well; the only practical difference for now is the way we’ll call methods.
#The __init__() method at is a special method Python runs automatically whenever we create a new instance based on the Person class. This method has two leading underscores and two trailing underscores, a convention that helps prevent Python’s default method names from conflicting with your method names.
#We define the __init__() method to have three parameters: self, name and age. The self parameter is required in the method definition, and it must come first before the other parameters.
#It must be included in the definition because when Python calls this __init__() method later (to create an instance of Person), the method call will automatically pass the self argument.
#Every method call associated with a Person class automatically passes self, which is a reference to the instance itself; it gives the individual instance access to the attributes and methods in the class.
#When we make an instance of Person, Python will call the __init__() method from the Person class. We passed Person() a name and an age as arguments; self is passed automatically, so we don’t need to pass it.
#Any variable prefixed with self is available to every method in the class, and we’ll also be able to access these variables through any instance created from the class. self.name = name takes the value stored in the parameter name and stores it in the variable name, which is then attached to the instance being created.
#The same process happens with self.age = age. Variables that are accessible through instances like this are called attributes.
#The Person class has two other methods defined: displayPersonInfo() and getPersonAccess().
#Because these methods don’t need additional information like a name or age, we just define them to have one parameter, self. The instances we create later will have access to these methods. In other words, they’ll be able to sit and roll over.
per = Person('Mark', 27)
#When Python reads this line, it calls the __init__() method in Dog with the arguments 'Mark' and 27.
#The __init__() method creates an instance representing this particular person and sets the name and age attributes using the values we provided.
#The __init__() method has no explicit return statement, but Python automatically returns an instance representing this person. We store that instance in the variable per.
#To access the attributes of an instance, you use dot notation. we access the value of per attribute name by writing:
print(per.name) #Mark
per.name = 'NewName'
print(per.name) #NewName
|
d321d41c9ba560fe4148b481737962481f7d62c3 | frances-zhao/ICS207 | /homework/lesson 8/lesson8_3.py | 627 | 4.25 | 4 | #*****************************************************
#
#Program Author: Frances Zhao
#Completion Date: May 10 2021
#Program Name: Lesson8_3
#Description: Ask the user for a positive integer.
#Print the ten times table for that number all on one line.
#
#*****************************************************
#variable declaration
num = int(0)
step = int(1)
#input: prompting the user for a positive integer
while num <= 0:
num = int(input("Please enter a positive integer: "))
#process: outputting the timestable to ten based on the step/counter
while step <= 10:
print(f"{step*num}", end = " ")
step += 1
|
ed2ef09c332c147deb16090ad069b03acd0c2a0c | dineshbalachandran/mypython | /src/daily/daily4.py | 1,325 | 3.765625 | 4 | """ Given an array of integers, find the first missing positive integer in linear time and constant space.
In other words, find the lowest positive integer that does not exist in the array.
The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. """
import sys
def missing_On(a):
s = set()
v = sys.maxsize
for e in a:
s.add(e)
for e in a:
lv = e - 1
hv = e + 1
if hv > 0 and hv < v and hv not in s:
v = hv
if lv > 0 and lv < v and lv not in s :
v = lv
return v
def missing_O1(a):
def segregate(a):
j = 0
for i in range(0, len(a)):
if a[i] <= 0:
t = a[i]
a[i] = a[j]
a[j] = t
j += 1
return j
def missing(a):
size = len(a)
for i in range(0, size):
if a[i] <= size and a[i] > 0 and a[a[i]-1] > 0:
a[a[i]-1] = -a[a[i]-1]
for i in range(0, size):
if a[i] > 0:
return i+1
return len(a)+1
return missing(a[segregate(a):])
if __name__ == '__main__':
print(missing_O1([0, -1, 2, 3, 99,100])) |
637df499f8e005776dc26ab263a6468f6ea8d56b | apriantoa917/Python-Latihan-DTS-2019 | /string in action/string comparasion.py | 420 | 3.65625 | 4 | # 5.1.10.1 String in action, 5.1.10.2 String in action
# operator yang bisa digunakan ==,!=,>,>=,<,<=
print('alpha' == 'alpha')
print('alpha' == 'Alpha') #case sensitive
print('alpha' != 'Alpha')
print('alpha' > 'alpha')
print('alpha' >= 'alpha')
print('alpha' < 'alphabet')
print('alphabet' < 'alpha')
'10' == 10
'10' != 10
'10' == 1
'10' != 1
# '10' > 10 eror karena >,>=,<,<= tidak mendukung komparasi int dan str |
f87959c25858522913c2e6d00e6857f6133810c5 | thebigshaikh/PythonPractice | /randomGuess.py | 424 | 3.84375 | 4 | import random
number=random.randint(0,10)
print(number)
while True:
uinput=input("Enter a number? \n")
print(uinput)
if uinput.isdigit():
if int(uinput)==number:
print("Woah You should be gambling!")
break
elif int(uinput)>number:
print("AH too high")
elif int(uinput)<number:
print("Too low")
elif uinput == "exit":
break
|
4b238ca8ddb8721a47e2dda80b49ee0b93da0aea | dwilhelm/projecteuler | /problem_31.py | 1,354 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
In England the currency is made up of pound, £, and pence, p, and there
are eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
It is possible to make £2 in the following way:
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
How many different ways can £2 be made using any number of coins?
"""
import sys
def maxcoincount(amount, coinvalue):
return map(lambda x: amount / x, coinvalue)
def numwaystomake(amount, coinvalue, coincount):
total = 0
if len(coincount) < 2:
return len(coincount)
idx = len(coincount) - 1
for num in xrange(coincount[idx], -1, -1):
remaining = amount - num * coinvalue[idx]
newcoincount = maxcoincount(remaining, coinvalue[:idx])
if newcoincount[1:]:
total += numwaystomake(remaining, coinvalue[:idx],
newcoincount[:idx])
else:
total += 1
return total
def main(N):
coinvalue = [1, 2, 5, 10, 20, 50, 100, 200]
maxcoincounts = maxcoincount(N, coinvalue)
ans = numwaystomake(N, coinvalue, maxcoincounts)
print '%d ways to make %d from %s' % (ans, N, maxcoincounts)
if __name__ == '__main__':
if len(sys.argv) > 1:
main(int(sys.argv[1]))
else:
main(200)
|
5ab3ddae2c03f3a6e29670a72943cf117d4a4087 | mossytreesandferns/CFPDXDataStorageObj | /ShouldIGoHiking.py | 1,341 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 23 23:00:47 2018
@author: meganporter
"""
"""This is a boolean look at whether I should go hiking or not and whether I will draw in my
nature journal or keep a photographic record. I won't go if it's below 45F or above 80F. I
also won't go if I don't have a ride or haven't reserved a rental car in time.
I like to keep records of hikes. Either I take photos on my phone to print out at a drugstore
or I bring my dedicated nature journal and draw with an archival pen. I'll rely on my phone
if it is downpouring or windy. Wind causes too much disturbance and if the rain is too heavy
my phone will be in danger. However, it's works okay to protect my phone from drizzle with
my sleeve and dry pockets stuffed with knitted gloves."""
#Is it below 45 degrees F?
below_45 = False
#Is it above 80 degrees F?
above_80 = False
#Is it sunny?
sunny = False
#Is it drizzling?
drizzling = True
#Is it downpouring?
downpour = False
#Is it windy?
windy = False
#Do I have a ride?
ride = False
#Have I reserved a rental car in time?
rental = True
yes_go = not(below_45 or above_80) and (ride or rental)
journal = sunny and not (windy or downpour) and yes_go
phone_photos = (sunny or drizzling) and not (downpour or journal) and yes_go
print(yes_go, journal, phone_photos)
|
da4c114a7f21d6cf027c12b7c30aeaf01c919bb8 | dvncan/python_fun | /listcomprehension/evennumbers.py | 99 | 3.59375 | 4 | #lst = [x for x in range(2,21,2)]
#print(lst)
lst = [x for x in range(1,21) if x%2==0]
print(lst) |
32cf5bb3ec295b8f8807a9e03ac51ee44dadde5e | yveso/ProjectEuler | /0001-0100/0001-0020/0004/0004.py | 264 | 3.765625 | 4 | def is_palindrome(number):
return str(number) == str(number)[::-1]
answer = 0
for x in range(100, 1000):
for y in range(x, 1000):
current = x * y
if is_palindrome(current) and current > answer:
answer = current
print(answer)
|
0ef4196ddf73b4da3eb64c1f5ce3ff02ccbdbd0f | sahilguptaBackup/learn-python | /dic.py | 278 | 3.875 | 4 | # customer = {
# "name" : "sahil",
# "age" : 25,
# "is_verified" : True
# }
#
# print(customer.get('name'))
numbers = {
'0' : 'Zero',
'1' : 'One',
}
input = input('Enter a number ')
output = ""
for i in input:
output += numbers.get(i, "")
print(output) |
67896feb38b6621bba529295a95735ac07bdab0b | lizawood/Apple-Health-Fitness-Tracker | /Package/myfitness/summary/maxmin.py | 1,708 | 3.78125 | 4 |
# coding: utf-8
# In[ ]:
def getMax(data):
""" Find the maximum number of steps in the data and the date it was achieved.
Parameters:
data: Pandas DataFrame containing Apple Health data imported from a
.csv file.
Return:
The row of values for when the maximum number of steps were achieved:
Start date, Finish date, Distance(mi), Steps (count)"""
# ensure pandas has been imported
import pandas as pd
# Verify datatype in Steps is correct datatype, then find the
# row containing the maximum steps and return that row.
try:
maximum = data.loc[data['Steps (count)'].idxmax()]
return maximum
except:
data['Steps (count)'] = data['Steps (count)'].astype(int)
maximum = data.loc[data['Steps (count)'].idxmax()]
return maximum
def getMin(data):
""" Find the maximum number of steps in the data and the date it was achieved.
Parameters:
data: Pandas DataFrame containing Apple Health data imported from a
.csv file.
Return:
The row of values for when the maximum number of steps were achieved:
Start date, Finish date, Distance(mi), Steps (count)"""
#ensure pandas has been imported
import pandas as pd
# Verify datatype in Steps is correct datatype, then find the
# row containing the minimum steps and return that row.
try:
minimum = data.loc[data['Steps (count)'].idxmin()]
return minimum
except:
data['Steps (count)'] = data['Steps (count)'].astype(int)
minimum = data.loc[data['Steps (count)'].idxmin()]
return minimum
|
e795bea0ba602aeecac5be55eadb7ecdfe156847 | arsamigullin/problem_solving_python | /leet/amazon/trees_and_graphs/1334_Find_the_City_With_the_Smallest_Number_of_Neighbors_at_a_Threshold_Distance.py | 3,641 | 3.609375 | 4 | import collections
import heapq
from typing import List
class SolutionWrong:
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
# a deque is faster at removing elements from the front
graph = collections.defaultdict(dict)
for u, v, dist in edges:
if dist < distanceThreshold:
graph[u][v] = dist
graph[v][u] = dist
# print(graph)
def find_dist(start):
distances = {vertex: float('inf') for vertex in graph}
pq = []
pq_update = {}
distances[start] = 0
for vertex, value in distances.items():
entry = [vertex, value]
heapq.heappush(pq, entry)
pq_update[vertex] = entry
while pq:
getmin = heapq.heappop(pq)[0]
for neighbour, distance_neigh in graph[getmin].items():
dist = distances[getmin] + distance_neigh
if dist < distances[neighbour]:
distances[neighbour] = dist
pq_update[neighbour][1] = dist # THIS LINE !!!
# print(distances)
return distances
# def find_dist(start):
# destinations = {start:0}
# queue = collections.deque([start])
# while queue:
# u = queue.popleft()
# dist = destinations[u]
# for v, vdist in graph[u].items():
# vdist+=dist
# if vdist > distanceThreshold:
# continue
# if v not in destinations:
# queue.append(v)
# destinations[v] = vdist
# elif vdist < destinations[v]:
# destinations[v] = vdist
# destinations.pop(start)
# return destinations
reachable_cities = float('inf')
curr_node = -1
# print(find_dist(1))
for key in range(n):
dists = find_dist(key)
if len(dists) < reachable_cities:
curr_node = key
reachable_cities = len(dists)
elif len(dists) == reachable_cities and curr_node < key:
curr_node = key
return curr_node
from heapq import heappush, heappop
class Solution:
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
# this for fast taking weight of the edge
cost = [[float('inf')] * n for _ in range(n)]
graph = collections.defaultdict(list)
for a, b, c in edges:
cost[a][b] = cost[b][a] = c
graph[a].append(b)
graph[b].append(a)
def dijkstra(i):
dis = [float('inf')] * n
dis[i], pq = 0, [(0, i)]
heapq.heapify(pq)
while pq:
d, i = heapq.heappop(pq)
if d > dis[i]: continue
for j in graph[i]:
this_cost = d + cost[i][j]
if this_cost < dis[j]:
dis[j] = this_cost
heapq.heappush(pq, (this_cost, j))
return sum(d <= distanceThreshold for d in dis) - 1
res = {dijkstra(i): i for i in range(n)}
return res[min(res)]
if __name__ == '__main__':
s = Solution()
s.findTheCity(4, [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], 4)
|
47d983b56b8db5afe7802a4ee8c87e39bb4030cd | jorgedelavg04/Algorithms-Analysis- | /Algorithms.py | 5,255 | 3.703125 | 4 | import matplotlib.pyplot as plt
import numpy as np
import time
import random
import sys
sys.setrecursionlimit(1500)
__Nombre__ = "Jorge C De la Vega C"
### Algoritmos ###
# Insertion Sort(Ciclico)
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
# Merge Sort(Recursivo)
def mergeSort(arr):
if len(arr)>1:
mid = len(arr)//2
lefthalf = arr[:mid]
righthalf = arr[mid:]
#recursion
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
arr[k]=lefthalf[i]
i=i+1
else:
arr[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
arr[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
arr[k]=righthalf[j]
j=j+1
k=k+1
return arr
# Quicksort(Divide y Venceras)
def partition(arr, begin, end):
pivot = begin
for i in range(begin+1, end+1):
if arr[i] <= arr[begin]:
pivot += 1
arr[i], arr[pivot] = arr[pivot], arr[i]
arr[pivot], arr[begin] = arr[begin], arr[pivot]
return pivot
def quicksort(arr, begin=0, end=None):
if end is None:
end = len(arr) - 1
def _quicksort(arr, begin, end):
if begin >= end:
return
pivot = partition(arr, begin, end)
_quicksort(arr, begin, pivot-1)
_quicksort(arr, pivot+1, end)
return _quicksort(arr, begin, end)
### Tiempo de los Algoritmos ####
def timeInsertionSort(arr):
start = time.clock()
insertionSort(arr)
final = time.clock()
resultTime = final - start
return resultTime
def timeMergeSort(arr):
start = time.clock()
mergeSort(arr)
final = time.clock()
resultTime = final - start
return resultTime
def timeQuickSort(arr):
start = time.clock()
quicksort(arr)
final = time.clock()
resultTime = final - start
return resultTime
### Peor de los Casos ###
def worstInsertionSort(n):
arr = []
for x in range(0, n+1):
arr.append(x)
return arr
def worstQuickSort(n):
arr = []
for x in range(0, n+1):
arr.append(x)
return arr
def worstMergeSort(n):
arr = []
for x in range(0, n+1):
arr.append(x)
return arr
def plotWorstCase(x, y1,y2,y3):
plt.plot(x, y1, label='Insertion Sort')
plt.plot(x, y2, label='Quick Sort')
plt.plot(x, y3, label='Merge Sort')
plt.title("Worst Case")
plt.legend()
### Caso Intermedio ###
def intermedio(n):
arr = []
for x in range (0,n):
arr.append(random.randint(0, 500))
return arr
def plotCasoIntermedio(x, y1,y2,y3):
plt.plot(x, y1, label='Insertion Sort')
plt.plot(x, y2, label='Quick Sort')
plt.plot(x, y3, label='Merge Sort')
plt.title("Caso Intermedio")
plt.legend()
### Mejor Caso ###
def bestInsertionSort(n):
arr = []
for x in range(0, n):
arr.append(x)
return arr
def bestQuickSort(n):
arr = []
for x in range(0, n):
arr.append(x)
return arr
def bestMergeSort(n):
arr = []
for x in range(0, n):
arr.append(x)
return arr
def plotBestCase(x, y1,y2,y3):
plt.plot(x, y1, label='Insertion Sort')
plt.plot(x, y2, label='Quick Sort')
plt.plot(x, y3, label='Merge Sort')
plt.title("Mejor Caso")
plt.legend()
def findPointsOfIntersection(a, b):
intersect = [val for val in a if val in b]
return intersect
def numberOfArrays(m,n):
y =m*n
return y
def main():
arrayNumber = 500
m1 = [0]
x = list(range(0, arrayNumber))
y1 = numberOfArrays(m1,arrayNumber)
y2 = numberOfArrays(m1,arrayNumber)
y3 = numberOfArrays(m1,arrayNumber)
print("Se debe cerrar cada ventana para abrir la siguiente, OJO, puede llegar a tardar en abrir")
### Plot Peor Caso
for i in x:
arr2 = worstInsertionSort(i)
arr3 = worstQuickSort(i)
arr4 = worstMergeSort(i)
intersection1 = findPointsOfIntersection(arr2, arr3)
intersection2 = findPointsOfIntersection(arr2, arr4)
intersection3 = findPointsOfIntersection(arr3, arr4)
y1[i] = timeInsertionSort(arr2)
y2[i] = timeQuickSort(arr3)
y3[i] = timeMergeSort(arr4)
plotWorstCase(x,y1,y2,y3)
plt.show()
### Plot Caso Intermedio
for i in x:
arr2 = intermedio(i)
arr3 = intermedio(i)
arr4 = intermedio(i)
intersection1 = findPointsOfIntersection(arr2, arr3)
intersection2 = findPointsOfIntersection(arr2, arr4)
intersection3 = findPointsOfIntersection(arr3, arr4)
y1[i] = timeInsertionSort(arr2)
y2[i] = timeQuickSort(arr3)
y3[i] = timeMergeSort(arr4)
plotCasoIntermedio(x,y1,y2,y3)
plt.show()
### Plot Mejor Caso
for i in x:
arr2 = bestInsertionSort(i)
arr3 = bestQuickSort(i)
arr4 = bestMergeSort(i)
intersection1 = findPointsOfIntersection(arr2, arr3)
intersection2 = findPointsOfIntersection(arr2, arr4)
intersection3 = findPointsOfIntersection(arr3, arr4)
y1[i] = timeInsertionSort(arr2)
y2[i] = timeQuickSort(arr3)
y3[i] = timeMergeSort(arr4)
plotBestCase(x,y1,y2,y3)
plt.show()
if __name__ == '__main__':
main()
|
c7b61c0a0684712788b9311295911d5db9536fe7 | CB150/Exercice-Python | /Exercice 16.py | 669 | 3.953125 | 4 | #création de la fonction avec 2 paramètres
def distance_hamming(str1,str2):
cpt=0
#si la taille d premier mot n'est pas égale à celle du deuxième
if (len(str1)!=len(str2)):
#Renvoie la phrase ci-dessous et met fin au programme.
return("Les mots ne sont pas de la même longueur")
else:
for i in range(len(str1)):
#si l'itérateur de la boucle du premier paramètre est différent de l'itérateur du second paramètre
if str1[i]!=str2[i]:
#incrémentation du compteur
cpt+=1
#on nous retourne la valeur du compteur.
return(cpt)
mm1=input("entrer le premier mot")
mm2=input("entrer le deuxieme mot")
print(distance_hamming(mm1,mm2))
|
c5199c9198aa609a5c61c93f9d280ad37e6a49a4 | gbucar/Sudoku | /new_possible.py | 1,095 | 3.734375 | 4 | def row_to_column(row):
column = [[] for i in range(3)]
for r in row:
for ii, char in enumerate(r):
column[ii].append(char)
return column
def create_base_three():
line = [i for i in range(3)]
base = []
for a in range(3):
base.append(create_order_row(line))
line = reorder(line)
return base
def create_order_row(line):
return [line for i in range(3)]
def reorder(lis):
return [lis[-1]]+lis[:-1]
def create_options_from_base(base):
options = []
for i in range(3):
current = list(base)
for ii in range(2):
current[i] = reorder(current[i])
options.append(list(current))
return options + [base]
def create_rows():
base_three = create_base_three()
all = []
for base in base_three:
all += create_options_from_base(base)
return all
def create_columns():
return [row_to_column(i) for i in create_rows()]
options = open("options.txt", "w")
options.write(str(create_rows()))
options.write("\n")
options.write(str(create_columns()))
options.close() |
2b2cc7d99e3ec57dbbd9268b2488767b179bbe9a | meetmemathanram/python_programs | /professional_tax.py | 326 | 3.859375 | 4 | from __builtin__ import str
salary = int(input('Enter the salary. '))
employer_type = str(raw_input('Enter the type of employer. '))
def showpt(salary , employer_type):
if(employer_type == "government"):
print(salary)
else:
tax = 0.25*salary
print(tax+salary)
showpt(salary, employer_type) |
9c86a3bc79a5611d9d7217dfaf538ce60c7fbdbb | Mr-Wolfram/MiniSQL | /test/mk.py | 1,075 | 3.625 | 4 | name = ['alice', 'bob', 'charlie', 'dave', 'eve', 'issac', 'ivan', 'justin', 'mallory', 'matilda', 'oscar', 'pat']
import random
import string
def generate_random_str( randomlength=1):
"""
生成一个指定长度的随机字符串,其中
string.digits=0123456789
string.ascii_letters=abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
"""
str_list = [random.choice(string.digits + string.ascii_letters) for i in range(randomlength)]
random_str = ''.join(str_list)
return random_str
test_name = 'test100000'
test_num=100000
with open("{}.txt".format(test_name), "w") as f:
f.write("create database cxz;\nuse database cxz;\ncreate table table1 (\ncolumn1 int unique,\ncolumn2 float not null,\ncolumn3 char(30) ,\nprimary key (column1)\n);")
# f.write("create index i1 on table1(column1);\n")
# f.write("create index i2 on table1(column2);\n")
for i in range(test_num):
s = "insert into table1 values ({}, {:.2f}, '{}');\n".format(i, i, generate_random_str(30))
f.write(s)
|
4ad1afb3d4de1d3eb451a5e5d79accc6f3ccc4f8 | sherlockwu/programming_study | /python_practice/learn_2.py | 496 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import string
def _greet_1(name):
print("hello, %s" %name)
def _greet_2(name):
print("hi, %s" %name)
def greeting(name_1):
temp_len = len(name_1)
if temp_len<=5:
_greet_1(name_1)
else:
_greet_2(name_1)
def test():
temp = sys.argv
temp_l = len(temp)
if temp_l == 1:
print("hello world")
elif temp_l == 2 :
print("hello %s" %temp[1])
else :
print("too much input")
if __name__ == '__main__' :
test()
|
8dbba7602b7988e28784dad99f0083e610d10919 | catalinc/aoc2020 | /src/day3.py | 1,219 | 3.65625 | 4 | import unittest
from typing import List
import sys
def count_trees(grid: List[List[str]], right: int, down: int) -> int:
w, h, r, c, cnt = len(grid[0]), len(grid), 0, 0, 0
while r < h:
if grid[r][c] == '#':
cnt += 1
c = (c + right) % w
r = r + down
return cnt
def parse_grid(s: str) -> List[List[str]]:
return [list(r) for r in s.split('\n') if r]
def part1(grid):
print(count_trees(grid, 3, 1))
def part2(grid):
p = 1
for right, down in [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]:
p *= count_trees(grid, right, down)
print(p)
class Test(unittest.TestCase):
def test_count_trees(self):
grid = parse_grid("""..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#""")
data = [(1, 1, 2), (3, 1, 7), (5, 1, 3), (7, 1, 4), (1, 2, 2)]
for r, d, t in data:
self.assertEqual(t, count_trees(grid, r, d))
if __name__ == '__main__':
if len(sys.argv) == 2:
with open(sys.argv[1], 'r') as infile:
g = parse_grid(infile.read())
part1(g)
part2(g)
else:
unittest.main()
|
1480e4f71cc8b0bc2b27f113937ba4b1cafe8cfb | saif93/simulatedAnnealingPython | /LocalSearch.py | 2,948 | 4.125 | 4 | """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
implementation of Simulated Annealing in Python
Date: Oct 22, 2016 7:31:55 PM
Programmed By: Muhammad Saif ul islam
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
import math
import random
from copy import deepcopy
from Tour import Tour
from City import city
class LocalSearch:
temp = 10000
coolingRate = 0.003
def __init__(self):
self.cities = deepcopy(city.cities)
def acceptanceProbability(self,energy, newEnergy, temperature):
# If the new solution is better, accept it
if (newEnergy < energy):
return 1.0
# // If the new solution is worse, calculate an acceptance probability
return math.exp((energy - newEnergy) / temperature)
def simulatedAnnealing(self):
currentSolution = Tour()
currentSolution.generateIndividual()
print("Initial solution distance: " , currentSolution.getDistance())
print("Initil path:",currentSolution.getTour())
# // Set as current best
best = deepcopy(Tour(currentSolution.getTour()))
# // Loop until system has cooled
while (self.temp > 1) :
# // Create new neighbour tour
newSolution = deepcopy(Tour(currentSolution.getTour()))
# // Get a random positions in the tour random.randrange(0,19,1)
tourPos1 = random.randrange(0,newSolution.tourSize(),1)
tourPos2 = random.randrange(0,newSolution.tourSize(),1)
# // Get the cities at selected positions in the tour
citySwap1 = newSolution.getCity(tourPos1)
citySwap2 = newSolution.getCity(tourPos2)
# // Swap them
newSolution.setCity(tourPos2, citySwap1);
newSolution.setCity(tourPos1, citySwap2);
# // Get energy of solutions
currentEnergy = currentSolution.getDistance()
neighbourEnergy = newSolution.getDistance()
# // Decide if we should accept the neighbour
if (self.acceptanceProbability(currentEnergy, neighbourEnergy, self.temp) >= random.randint(1,19)) :
currentSolution = deepcopy(Tour(newSolution.getTour()))
# // Keep track of the best solution found
if (currentSolution.getDistance() < best.getDistance()) :
best = deepcopy(Tour(currentSolution.getTour()))
# // Cool system
self.temp *= 1- self.coolingRate
print("\n\nFinal solution distance: " , best.getDistance())
print("Final path: " , best.getTour())
"""
Testing
"""
initializeCities = city()
localSearch = LocalSearch()
localSearch.simulatedAnnealing()
|
8a804aed82fafdaed8e26856906f352fcc35ab0e | Shalom91/Password-Checker | /tests/test_password_is_valid.py | 927 | 3.515625 | 4 | from password_checker.password_checker import password_is_valid
import pytest
# Testing for each condition of password_is_valid
def test_password_is_valid():
with pytest.raises(Exception) as e:
assert password_is_valid("")
assert str(e.value) == "password should exist"
with pytest.raises(Exception):
assert password_is_valid("molash") == Exception("password must be longer than 8 characters")
assert password_is_valid("MOLASH") == Exception("password must have at least one lowercase letter")
assert password_is_valid("molash") == Exception("password must have at least one uppercase letter")
assert password_is_valid("Molashxyz!") == Exception("password must have at least one digit")
assert password_is_valid("Molashxyz4") == Exception("password must have at least one special character")
assert password_is_valid("Molash@91") == True
|
c0a3397f75247a87d9c55314f3e42e985ad1b5fc | Priyangshu-Mandal/JARVIS | /jarvis.py | 4,881 | 3.65625 | 4 | import time
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os
import random
import pygame
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
"""
:param audio: any text
'speaks' the given text
"""
engine.say(audio)
engine.runAndWait()
def wishMe():
"""
Wishes the user according to the current time
"""
hour = int(datetime.datetime.now().hour)
if 0 <= hour < 12:
speak("Good Morning")
elif 12 <= hour < 18:
speak("Good Afternoon")
else:
speak("Good Evening")
speak("I am Jarvis. Please tell me how may I help you.")
def takeCommand():
"""
:return: the string form of the audio user input
"""
r = sr.Recognizer()
with sr.Microphone() as source: # input from microphone is stored in source
print("Listening...")
r.pause_threshold = 1 # seconds of non-speaking
r.energy_threshold = 400 # you will have to shout!
audio = r.listen(source) # 'listens' to source and stores the string in audio
try:
print("Recognizing...")
userInput = r.recognize_google(audio, language='en-in') # recognize audio in Indian English using google engine
print(f"User said: {userInput}\n")
except Exception:
print("Say that again please...\n")
speak("Say that again please...\n")
return "None"
return userInput
if __name__ == '__main__':
wishMe()
while True:
query = takeCommand().lower()
# LOGIC FOR EXECUTING TASKS BASED ON QUERY
# wikipedia search
if "wikipedia" in query:
speak("Searching wikipedia...")
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences=5)
print("According to Wikipedia, " + results + "\n")
speak("According to Wikipedia, " + results)
# opening YouTube
elif "open youtube" in query:
speak("Opening Youtube...")
webbrowser.open('youtube.com')
# opening Google
elif "open google" in query:
speak("Opening Google...")
webbrowser.open('google.com')
# opening CodeWithHarry.com
elif "open codewithharry.com" in query:
speak("Opening CodeWithHarry.com...")
webbrowser.open('codewithharry.com')
# opening Java docs
elif "open java docs" in query:
speak("Opening Java Documentation...")
webbrowser.open('docs.oracle.com//en//java//javase//14//docs//api//')
# asking, "who are you?"
elif "who are you" in query:
speak("I am Jarvis")
# playing music
elif "play music" in query:
speak("Playing music...")
music_dir = 'C:\\Users\\Mrinmoy\\Music\\Music'
songs = os.listdir(music_dir)
for i, song in enumerate(songs):
print(str(i) + ") " + song + "\n")
os.startfile(os.path.join(music_dir, songs[random.randint(0, len(songs) - 1)]))
# asking the time
elif "the time" in query:
strTime = datetime.datetime.now().strftime("%H:%M:%S")
print(f"Time: {strTime}")
speak(f"The time is {strTime}")
# opening Visual Studio Code
elif "open code" in query:
speak("Opening Visual Studio Code...")
codePath = "F:\\Microsoft VS Code\\Code.exe"
os.startfile(codePath)
# opening IntelliJ IDEA
elif "open idea" in query:
speak("Opening IntelliJ IDEA...")
codePath = "F:\\IntelliJ IDEA 2020.3.1\\IntelliJ IDEA Community Edition 2020.3.1\\bin\\idea64.exe"
os.startfile(codePath)
# opening PyCharm
elif "open pycharm" in query:
speak("Opening PyCharm...")
codePath = "F:\\Pycharm 2020.3.2\\PyCharm Community Edition 2020.3.2\\bin\\pycharm64.exe"
os.startfile(codePath)
# opening Google Chrome
elif "open chrome" in query:
speak("Opening Google Chrome...")
codePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
os.startfile(codePath)
# opening the flappy bird game
elif "open flappy bird game" in query:
codePath = "F:\\Flappy Bird Game\\Try\\Try.exe"
os.startfile(codePath)
# opening powershell
elif "open powershell" in query:
codePath = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
os.startfile(codePath)
# switching Jarvis off
elif "jarvis quit" in query:
speak("Quitting. Hope I was of help.")
quit()
|
bfe1c225f11bca754da630d9bc38205732bfcb6a | sarthaksaini7/python | /learn33.py | 202 | 3.859375 | 4 | import random
for i in range(3):
number = random.randint(10, 20)
print(number)
for i in range(5):
members = ['John', 'Mary', 'Harry']
leader = random.choice(members)
print(leader)
|
0e3e33b0c280f36a86830a663507cc5923aa413a | sushengyang/yelp-review-sentiment-analysis | /src/util/reservoir_sampling.py | 572 | 3.703125 | 4 | import random
def generate_sample(n, population):
sample = [];
for i, item in enumerate(population):
if i < n:
sample.append(item)
elif i >= n and random.random() < n/float(i + 1):
replace = random.randint(0, len(sample) - 1)
sample[replace] = item
return sample
if __name__ == '__main__':
# Return random sample of 1000 elements from 0 - 1 000 000
sample_size = 1000
population_ids = range(0, 1000000)
sample_ids = generate_sample(sample_size, population_ids)
print(sample_ids)
|
224890a992080b8a76830031954bb0551b6cfed1 | szhmery/leetcode | /DFS-BFS/617-MergeTrees.py | 2,390 | 3.84375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# DFS
# 时间复杂度:O(min(m,n)),其中 m 和 n 分别是两个二叉树的节点个数。对两个二叉树同时进行深度优先搜索,
# 只有当两个二叉树中的对应节点都不为空时才会对该节点进行显性合并操作,因此被访问到的节点数不会超过较小的二叉树的节点数。
# 空间复杂度:O(min(m,n)),其中 m 和 n 分别是两个二叉树的节点个数。
# 空间复杂度取决于递归调用的层数,递归调用的层数不会超过较小的二叉树的最大高度,最坏情况下,二叉树的高度等于节点数。
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
if not root1:
return root2
if not root2:
return root1
root = TreeNode(root1.val + root2.val)
root.left = self.mergeTrees(root1.left, root2.left)
root.right = self.mergeTrees(root1.right, root2.right)
return root
# BFS
# 时间复杂度:O(min(m,n)),其中 m 和 n 分别是两个二叉树的节点个数。对两个二叉树同时进行深度优先搜索,
# 只有当两个二叉树中的对应节点都不为空时才会对该节点进行显性合并操作,因此被访问到的节点数不会超过较小的二叉树的节点数。
# 空间复杂度:O(N),对于满二叉树时,要保存所有的叶子节点,即 N/2 个节点。
def mergeTrees2(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
if not root1:
return root2
if not root2:
return root1
queue = [(root1, root2)]
while queue:
r1, r2 = queue.pop()
r1.val += r2.val
# 如果r1和r2的左子树都不为空,就放到队列中
# 如果r1的左子树为空,就把r2的左子树挂到r1的左子树上
if r1.left and r2.left:
queue.append((r1.left, r2.left))
elif not r1.left:
r1.left = r2.left
if r1.right and r2.right:
queue.append((r1.right, r2.right))
elif not r1.right:
r1.right = r2.right
return root1
|
37ece193102f1b3308efdf0ba4f98e15561f3b75 | Andersonabc/practice_Python | /week7-1.py | 3,648 | 3.921875 | 4 | """
#分數四則計算
(若為 C 語言此題不使用陣列,必須使用指標)
此題自訂 add function,計算兩個分數相加。
function input
--------------------
n1: 第一個數的分子
d1: 第一個數的分母
n2: 第二個數的分子
d2: 第二個數的分母
function output
------------------------------
numerator: 相加結果的分子
deniminator: 相加結果的分母
此題自訂multiply function 定義,計算兩個分數相乘。
function input
--------------------
n1: 第一個數的分子
d1: 第一個數的分母
n2: 第二個數的分子
d2: 第二個數的分母
function output
------------------------------
numerator: 相乘結果的分子
deniminator: 相乘結果的分母
--------------------
輸入說明:
----------------------------
輸入二行,每一行代表一個分數
----------------
輸出說明:
---------------------------
輸出分數相加結果
輸出分數相減結果
輸出分數相乘結果
輸出分數相除結果
若有輸入分數的分母或分子為0,則輸出ERROR。
若分數大於1,則分數部分要加括號,如一又六分之一輸出為1(1/6)
若為負數,負號在最前面。
若輸出為0,則顯示0
輸出的結果必須化簡為最簡分數
----------------
Sample input:
----------------
1/2
2/3
----------------
Sample output:
----------------
1(1/6)
-1/6
1/3
3/4
----------------
Sample input:
----------------
0/2
2/3
----------------
Sample output:
----------------
ERROR
ERROR
ERROR
ERROR
"""
def a(m,n):
while (m!=0 and n!=0):
if m>n:
m=m%n
else:
n=n%m
if m==0:
return n
elif n==0:
return m
else:
return 0
def output(son,mom,stt):
if son > mom :
ans=son//mom
son=son%mom
if son!=0:
print('%s%d(%d/%d)' %(stt,ans,son,mom))
else:
print('%s%d' %(stt,ans))
elif son==mom:
print('%s%d' %(stt,son//mom))
elif son<mom:
if son!=0:
print('%s%d/%d' %(stt,son,mom))
else:
print('0')
def min(x,y):
stt=''
if (int(x[0])/int(x[1])-int(y[0])/int(y[1]))<0:
stt='-'
mom=abs(int(x[1])*int(y[1]))
son=abs(int(x[0])*int(y[1])-int(y[0])*int(x[1]))
qq=a(son,mom)
if qq !=0 :
son/=qq
mom/=qq
output(son,mom,stt)
def ad (x,y):
stt=''
if (int(x[0])/int(x[1])+int(y[0])/int(y[1]))<0:
stt='-'
mom=abs(int(x[1])*int(y[1]))
son=abs(int(x[0])*int(y[1])+int(y[0])*int(x[1]))
qq=a(abs(son),mom)
if qq !=0 :
son/=qq
mom/=qq
output(son,mom,stt)
def mult (x,y):
stt=''
if (int(x[0])/int(x[1])*int(y[0])/int(y[1]))<0:
stt='-'
son=abs(int(x[0])*int(y[0]))
mom=abs(int(x[1])*int(y[1]))
qq=a(abs(son),mom)
if qq !=0 :
son/=qq
mom/=qq
output(son,mom,stt)
def divi (x,y):
stt=''
if (int(x[0])/int(x[1])*int(y[0])/int(y[1]))<0:
stt='-'
son=abs(int(x[0])*int(y[1]))
mom=abs(int(x[1])*int(y[0]))
qq=a(abs(son),mom)
if qq !=0 :
son/=qq
mom/=qq
output(son,mom,stt)
def main():
a=input()
a1=a.split('/')
b=input()
b1=b.split('/')
if a1[0]=='0' or a1[1]=='0' or b1[0]=='0' or b1[1]=='0':
for i in range (4):
print('ERROR')
else:
ad(a1,b1)
min(a1,b1)
mult(a1,b1)
divi(a1,b1)
main()
|
55c180463bb42b0b6d5c679dd076ab481aa3596e | chenxu0602/LeetCode | /660.remove-9.py | 966 | 3.609375 | 4 | #
# @lc app=leetcode id=660 lang=python3
#
# [660] Remove 9
#
# https://leetcode.com/problems/remove-9/description/
#
# algorithms
# Hard (51.70%)
# Likes: 75
# Dislikes: 116
# Total Accepted: 5.4K
# Total Submissions: 10.5K
# Testcase Example: '10'
#
# Start from integer 1, remove any integer that contains 9 such as 9, 19,
# 29...
#
# So now, you will have a new integer sequence: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11,
# ...
#
# Given a positive integer n, you need to return the n-th integer after
# removing. Note that 1 will be the first integer.
#
# Example 1:
#
# Input: 9
# Output: 10
#
#
#
#
# Hint: n will not exceed 9 x 10^8.
#
#
class Solution:
def newInteger(self, n: int) -> int:
# The answer is therefore just the n-th base-9 number.
# Time complexity: O(1)
# Space complexity: O(1)
ans = ""
while n:
ans = str(n % 9) + ans
n //= 9
return int(ans)
|
d19f25a122306d614c3ca76a08892dd590d5260f | fl-ada/Toy_programs | /Python_programming/sort_maxnum.py | 1,069 | 4.03125 | 4 | # get maximum possible number by listing integers in array 'numbers'
# 1 <= len(numbers) <= 100,000
# 1 <= elements in numbers <= 1,000
import numpy as np
def fill_digits(numbers):
# make all elements into 3 digit numbers
new_numbers = []
for i in range(len(numbers)):
if numbers[i] < 10:
# 1-digit num
new_numbers.append(numbers[i] * 1111)
elif numbers[i] < 100:
# 2-digit num
new_numbers.append(numbers[i] * 100 + numbers[i])
elif numbers[i] < 1000:
# 3-digit num
new_numbers.append(numbers[i] * 10 + int(numbers[i] / 100))
else:
# 1000
new_numbers.append(numbers[i])
return new_numbers
def get_index(new_numbers):
return np.argsort(new_numbers)[::-1]
def sort_by_index(numbers, index):
return [numbers[i] for i in index]
def solution(numbers):
answer = ''
numbers = sort_by_index(numbers, get_index(fill_digits(numbers)))
answer = "".join([str(int) for int in numbers])
return str(int(answer)) |
13249c6c042ea783f89cbcbd81705e1773f98036 | alemas/k-means-python | /iris_plant.py | 1,153 | 3.75 | 4 | import math
class IrisPlant:
sepal_length = 0
sepal_width = 0
petal_length = 0
petal_width = 0
name = ""
def __init__(self, sl, sw, pl, pw, name):
self.sepal_length = sl
self.sepal_width = sw
self.petal_length = pl
self.petal_width = pw
self.name = name
# Distância euclidiana entre uma planta e outra
def distanceToPlant(self, plant):
return math.sqrt(pow(self.sepal_length - plant.sepal_length, 2) +
pow(self.sepal_width - plant.sepal_width, 2) +
pow(self.petal_length - plant.petal_length, 2) +
pow(self.petal_width - plant.petal_width, 2))
def equals(self, plant):
return (abs(self.sepal_length - plant.sepal_length) < 0.001 and
abs(self.sepal_width - plant.sepal_width) < 0.001 and
abs(self.petal_length - plant.petal_length) < 0.001 and
abs(self.petal_width - plant.petal_width) < 0.001)
def copy(self):
return IrisPlant(self.sepal_length, self.sepal_width, self.petal_length, self.petal_width, self.name) |
2144c62172922791836baaa57b3d0eb1e29e36be | crampete/full_stack_course | /python/01_basic_python/03_control_statements/02_for/05.py | 157 | 3.984375 | 4 | desired_sum = 0
for number_iter in range(501):
if number_iter % 3 == 0 and number_iter % 5 != 0:
desired_sum += number_iter
print(desired_sum)
|
24fdfbab8aff055f9fa550589e1d6048b652ec75 | Gurendar/Python-Basic-Codes | /rock_paper_scissors.py | 1,977 | 4.03125 | 4 |
# First Working Code for Rock-Paper-Scissors
from random import randint
# print(ord('p'),ord('P'))
for i in range(1):
class RPS():
def __init__(self):
self.player1_name = input("Please enter your name: ")
self.player1 = (input('Select any one of the options \nRock(r), Paper(p) and Scissors(s): '))
self.player1 = self.player1.lower()
print(self.player1)
self.sys_opt()
def sys_opt(self):
self.comp_selected = randint(1, 3)
print(self.comp_selected)
if self.comp_selected == 1:
self.comp_player2 = 'r'
print(self.comp_player2)
self.check_win()
elif self.comp_selected == 2:
self.comp_player2 ='p'
print(self.comp_player2)
self.check_win()
elif self.comp_selected == 3:
self.comp_player2 = 's'
print(self.comp_player2)
self.check_win()
def check_win(self):
if self.player1 == self.comp_player2:
print("Its a TIE !!")
# break:
elif self.player1 == 'r' and self.comp_player2 == 'p':
print("Computer wins !!")
# break
elif self.player1 == 'p' and self.comp_player2 == 'r':
print(self.player1_name," wins")
elif self.player1 == 'p' and self.comp_player2 == 's':
print("Computer wins !!")
elif self.player1 == 's' and self.comp_player2 == 'p':
print(self.player1_name," wins")
elif self.player1 == 's' and self.comp_player2 == 'r':
print("Computer wins !!")
elif self.player1 == 'r' and self.comp_player2 == 's':
print(self.player1_name," wins")
mycode = RPS()
# mycode.sys_opt()
# mycode.check_win()
|
015d98f55c0664e8bd0d8b9d37f0f915f2ee3b1e | xujianhai/backtest | /backtest/backtest/Util/SetUtil.py | 718 | 3.734375 | 4 | #集合的操作
#交集
def intersection(a,b):
return list(set(a).intersection(set(b)))
#获取两个list 的并集
def union(a,b):
return list(set(a).union(set(b)))
#获取两个 list 的差集
def difference(a,b):
return list(set(a).difference(set(b))) # a中有而b中没有的
def dict_to_string(dict):
result = ''
for key, value in dict.items():
result += "\"%s\":\"%s\"" % (key, value)
return result
"""
#用merge对df取交集的方法
if currSourceData == None | lastSourceData == None:
return None
if len(currSourceData) == 0 | len(currSourceData) == 0:
return None
pd.merge(currSourceData, lastSourceData, on=['AAA', 'BBB'], how='inner')
"""
|
26d4fa2db35a791ee5016cd01490892c688007f2 | mohithvegi/GFG | /Strings/multiplyStrings.py | 448 | 4.03125 | 4 | # https://practice.geeksforgeeks.org/problems/multiply-two-strings/1
#User function Template for python3
def multiplyStrings(s1,s2):
# code here
# return the product string
return str(int(s1)*int(s2))
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == "__main__":
t=int(input())
for i in range(t):
a,b=input().split()
print(multiplyStrings( a.strip() , b.strip() ))
# } Driver Code Ends
|
b5f5c1ced9b8a4263a213e436d2654be4d93bf4e | serhansezgin/introtoprogramming | /serhansezgin_third_exercise_at_class_exercises.py | 7,848 | 4.1875 | 4 | '''
def addtwo(a,b):
print(a+b)
return(a+b)
print (addtwo(1,2) + 3)
'''
'''
def season(month):
if month == 1 or month == 2 or month == 12:
print("winter")
elif month == 3 or month == 4 or month == 5:
print("spring")
elif month > 5 and month < 9:
print("summer")
else:
print("autumn")
season(9)
'''
'''
def multiply(a,b):
return a - b
print(multiply(5, 6))
print(multiply(1, 1))
print(multiply(10, 0))
'''
'''
print(max("Introdction") + max("to") + max("progamming"))
'''
'''
def shoe_size(length):
size = 1.5 * (length + 1.5)
return size
name = input("Enter your name: ")
foot = float(input("Enter your foot length (cm): "))
shoe = shoe_size(foot)
print("Dear " + name + ", your suitable shoe size is " +str(round(shoe)))
print("Shrek's shoe size is", round(shoe_size(foot)))
'''
'''
def maximum(a,b):
if a < b:
return b
else:
return a
try:
x1 = int(input("Enter the first number: "))
y1 = int(input("Enter the second number: "))
m1 = maximum(x1,y1)
print("The input numbers are", str(x1), "and", str(y1) + ". The greatest number is", str(m1) + ".")
x2 = int(input("Enter the third number: "))
y2 = int(input("Enter the fourth number: "))
m2 = maximum(x2, y2)
print("The input numbers are", str(x2), "and", str(y2) + ". The greatest number is", str(m2) + ".")
if m2 > m1:
print("The first greatest number is smaller.")
else:
print("The second greatest number is smaller.")
except:
print("Please enter a number.")
#print("The input numbers are 2 and 5. The greatest number is", str(maximum(2,5)) + ".")
#print("The input numbers are 4 and 1. The greatest number is", str(maximum(4,1)) + ".")
'''
#Exercise 1
# Number of days in month with function
'''
try:
x = int(input('Enter the number of the month: '))
def number_of_days(x):
if x==1 or x==3 or x==5 or x==7 or x==8 or x==10 or x==12:
return('That month has 31 days in it')
elif x==2:
year = int(input("Enter a year:"))
if year%4 != 0:
return("hat month has 28 days in it (a common year).")
elif year%4 == 0 and year%100 !=0:
return("That month has 29 days in it (a leap year).")
elif year%100 == 0 and year%4 == 0:
if year%400 == 0:
return("That month has 29 days in it (a leap year).")
else:
return("That month has 28 days in it (a common year).")
elif x==4 or x==6 or x==9 or x==11:
return("That month has 30 days in it")
else:
if x<1 or x>12:
return("The number of a month must be in the range [1-12]")
print(number_of_days(x))
except:
print('Please enter a number')
'''
'''
#sample
a = input("Please and the number of the month: ")
def number_of_days(a):
if a == 1:
return "January 30 days"
else:
return "February 28 days"
print (number_of_days(a))
'''
#Exercise 2
#Price Difference
'''
def price_difference(a,b,c):
return (b*c)-a
a = int (input("What is the price of the product? "))
b = int (input("What is the monthly payment on the first installment plan? "))
c = int (input("How many months does the first installment plan last? "))
x = price_difference(a,b,c)
b = int (input("What is the monthly payment on the second installment plan? "))
c = int (input("How many months does the second installment plan last? "))
y = price_difference(a,b,c)
def analyzer(x,y):
if x<y:
return "The first installment plan is better!, Because the price difference is", x, "But in another case", y
else:
return "The second installment plan is better!, Because the price difference is", y, "But in another case", x
print (analyzer(x,y))
'''
#During Session 3
'''
#Ex1 Money Change
def money_change(a):
return float(a*1.14)
gbp = float(input("Please enter the GBP amount: "))
gbp2 = float(input("Please enter the second GBP amount: "))
print ("The first pound's conversion is",round(money_change(gbp)), "Euro")
print ("The second pound's conversion is",round(money_change(gbp2)), "Euro")
'''
'''
#Ex2 What is the name of the month?
try:
month = int(input("Please enter the number of the month? "))
def month_as_name(month):
if month == 1:
return("January")
elif month == 2:
return("February")
elif month == 3:
return("March")
elif month == 4:
return("April")
elif month == 5:
return("May")
elif month == 6:
return("June")
elif month == 7:
return("July")
elif month == 8:
return("August")
elif month == 9:
return("September")
elif month == 10:
return("October")
elif month == 11:
return("November")
elif month == 12:
return("December")
elif month == 0:
return("The number of a month must be in the range [1-12]")
else:
return("There are only 12 months in a year.")
print(month_as_name(month))
except:
print("Please enter a valid number between [1-12]")
'''
#Ex3 Date as String
'''
try:
day = int (input("Please enter the day: "))
month = int(input("Please enter the number of the month? "))
year = int(input("Please enter the year? "))
def month_as_name(month):
if month == 1:
return("January")
elif month == 2:
return("February")
elif month == 3:
return("March")
elif month == 4:
return("April")
elif month == 5:
return("May")
elif month == 6:
return("June")
elif month == 7:
return("July")
elif month == 8:
return("August")
elif month == 9:
return("September")
elif month == 10:
return("October")
elif month == 11:
return("November")
elif month == 12:
return("December")
elif month == 0:
return("The number of a month must be in the range [1-12]")
else:
return("There are only 12 months in a year.")
man = (month_as_name(month))
def whole_date(day,man,year):
return (man,day,year)
print (whole_date(day,man,year))
except:
print("Please enter a valid number between [1-12]")
'''
'''
# 4 Budget
def budget(a):
return ((10*a)+55)
inv_people = int(input("Please enter the number of invited people: "))
att_people = int(input("Please enter the number of people attending: "))
min_budget = budget(att_people)
max_budget = budget(inv_people)
print ("Min Budget",min_budget,"Euro")
print ("Max Budget",max_budget,"Euro")
'''
#5 Money
'''
def enough_money(price, amount, savings):
total_price = price * amount
if total_price < savings:
return True
else:
return False
if enough_money(2, 4.5, 10):
print('Buy')
else:
print('Save more money')
'''
'''
def enough_money_trial(price,amount,savings):
return (price*amount<savings)
if enough_money_trial(2, 4.5, 10):
print('Buy')
else:
print('Save more money')
'''
|
bd2dd960e601bd594f913e0c448078e412d09bb4 | sudiptapadhi/fibonacci-series | /datastr1.py | 581 | 4.375 | 4 | ASSIGNING ELEMENTS TO DIFFERENT LIST
test_list = [9, 3, 6, 5]
print("The original list : " + str(list))
list.extend(range(5))
print("The list after adding range elements : " + str(test_list))
ACCESSING DATA USING TUPLE
tup1 = ('red', 'green', 9, 10);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
DELETING DICTIONARY ELEMENT
dict = {"zayn" : 22, "harry" : 21, "jazz" : 21, "arya" : 21}
print ("The dictionary before performing remove is : " + str(dict))
del dict['jazz']
print ("The dictionary after remove is : " + str(dict))
|
7b3812aefa02b1bf93d4cbfd1b7f00b4bbcaec93 | espmihacker/study_python | /class1_2_08/02-private.py | 285 | 3.71875 | 4 | class Dog:
# 私有方法
def __test1(self):
print("------Messing")
# 公有方法
def test2(self, money):
if money > 1:
self.__test1()
else:
print("余额不足!")
print("------2")
dog = Dog()
dog.test2(-1) |
6075a9f1544c77b0940a41ae7a489caceb4b53a4 | karthikh07/Python-core | /Functions/No_Arg_No_Rtn.py | 128 | 3.84375 | 4 | def add():
a=int(input('Enter a value'))
b=int(input('Enter b value'))
c=a+b
print(a,'+',b,'=',c)
add()
|
e994a356226e3715799a012aaf61e44cb2d2ba98 | beau-tie/Python-Library | /hatsAndGames/perfectNum.py | 490 | 4.21875 | 4 | # This program will determine if a number inputed is a perfect number or not
def is_plus_perfect(n):
digitsN = len(str(n))
number = str(n)
digitPowerSum = 0
for i in number:
x = int(i)
digitPowerSum += x**digitsN
return digitPowerSum
n = input("Enter a number: ")
print is_plus_perfect(n)
if is_plus_perfect(n) == n:
print "Number ", n , " is a perfect number."
else:
print "Number ", n , " is not a perfect number."
|
8630cbac70723290cc6294d0f8a9550efecc58cc | hfsvv/python-basics | /testing/new.py | 171 | 3.640625 | 4 | lst=[1,2,3,4,5,6]
s=0
#eveb or not
for n in lst:
if n%2==0:
print(n)
for i in range(0,len(lst)):
print(lst[i])
# total sum
for n in lst:
s=s+n
print(s) |
6edc4c6b337133eded281ab3bda444f59a426b8f | CallumGray/Countdown | /TrieList.py | 3,184 | 4.0625 | 4 | from typing import List
class TrieNode:
def __init__(self, letter: str, complete_word: bool):
# Letter of current node
self.letter: str = letter
# Children of this node
self.children: List[TrieNode] = []
# If current node is a complete_word node
self.complete_word: bool = complete_word
class TrieList:
def __init__(self):
self.root_node: TrieNode = TrieNode('', False)
#
#
# ADD WORD TO TREE
#
#
def add_word(self, word: str):
# Start at the root node
node: TrieNode = self.root_node
# Traversal will be the length of the word at most
for letter in word:
letter_found: bool = False
# Check all children of node for the letter
for child in node.children:
# Letter is in children so traverse 1 deeper and go to next letter
if child.letter == letter:
node = child
letter_found = True
break
# Letter is not in children
if not letter_found:
# Make a new child node and assign it the letter
child_node: TrieNode = TrieNode(letter, False)
node.children.append(child_node)
# Move to the child node
node = child_node
# Node after fully iterating loop has the last letter, so set complete_word to True
node.complete_word = True
#
#
# FIND LONGEST WORDS (AND PROVIDE DEFINITIONS)
#
#
# Collects all words that can be made from the letters
def find_words(self, letters: [str], node: TrieNode, prefix: str = '') -> List[str]:
valid_words: List[str] = []
if node.complete_word:
valid_words.append(prefix)
# Check every node for matching letters
for child in node.children:
# Set to avoid traversing multiple times for the same letter
for letter in set(letters):
if letter == child.letter:
# Remove 1st element of the letter from letters
letters_copy = letters.copy()
letters_copy.remove(letter)
valid_words += self.find_words(letters_copy, child, prefix + child.letter)
return valid_words
#
#
# PRINT TREE (to n rows)
#
#
def print_trie(self, n: int, node: TrieNode, prefix: str = ''):
if n == 0:
return
prefix += node.letter
midpoint: int = len(node.children) // 2
for index, child in enumerate(node.children):
if index <= midpoint:
# print above a level to the right
self.print_trie(n - 1, child, prefix)
# print current node at level
if node.complete_word:
print(" " * 3 * n, '[', prefix, ']')
else:
print(" " * 3 * n, prefix)
for index, child in enumerate(node.children):
if index > midpoint:
# print the rest below a level to the right
self.print_trie(n - 1, child, prefix)
|
821bf0185688ef84f9ed2f703c36e16987aa2975 | AnjoliPodder/Anjoli-Project | /podder_hw04_simple.py | 1,900 | 4.09375 | 4 | ''''''
'''
Create a sorted list from the following list of 2-tuples by the second element of each tuple.
The original list should be left intact.
Hint: you could use list comprehension and lambda function
Hint:
'''
indata = [
('a', 0),
('b', 2),
('c', 1),
]
def sort_tuples(input):
reversed = [(b, a) for a, b in input]
reversed.sort()
return [(b, a) for a, b in reversed]
print(sort_tuples(indata))
'''
Count the number of unique values in a list
'''
import random
indata = [random.randrange(100) for it in range(20)]
def count_unique(num_list):
unique_ints = []
for i in num_list:
if not(i in unique_ints):
unique_ints.append(i)
return len(unique_ints)
print(indata)
print(count_unique(indata))
'''
Check if there is a key called city in stuff dictionary
If it does not exit, add new key/value pair to the dictionary
Add another key/value pair using key 'weight' and some float value
Delete key/value pair where key is 'weight'
'''
stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}
print('city' in stuff.keys())
stuff['weight'] = 181.5
print(stuff)
del stuff['weight']
print(stuff)
'''
print the type of the value under key 'silly' in a_dict dictionary
create a copy of the object stored under the key 'silly' and store it
in a_dict under key 'goose'
'''
a_dict = {4: "hi", True: 24, "silly": ["very", "very", "very"]}
print(type(a_dict['silly']))
a_dict['goose'] = a_dict['silly'][:]
'''
Iterate through python_words dictionary keys and values from the python_words dictionary
'''
python_words = {'list': 'A collection of values that are not connected, but have an order.',
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of actions in Python.',
}
for key in python_words.keys():
print(key, python_words.get(key)) |
6ac836866f52a303b80078b593ad98920856cbe7 | jinurajk/PythonProject | /TwitterPgm5.py | 1,364 | 3.859375 | 4 | #This programs is for retrieving tweets from a particular hashtag
import json
import TwitterLogin
import os
import codecs
twitter_api = TwitterLogin.login_twitter1()
iterator = twitter_api.statuses.sample()
iterator1 = twitter_api.statuses.filter(track="Travel", result_type='recent', language="en")
# Print each tweet in the stream to the screen
# Here we set it to stop after getting 1000 tweets.
# You don't have to set it to stop, but can continue running
# the Twitter API to collect data for days or even longer.
tweet_count = 5
tweet_count1 = 5
for tweet in iterator:
tweet_count -= 1
# Twitter Python Tool wraps the data returned by Twitter
# as a TwitterDictResponse object.
# We convert it back to the JSON format to print/score
print("First Loop ",json.dumps(tweet))
# The command below will do pretty printing for JSON data, try it out
# print json.dumps(tweet, indent=4)
if tweet_count <= 0:
break
for tweet in iterator1:
tweet_count1 -= 1
# Twitter Python Tool wraps the data returned by Twitter
# as a TwitterDictResponse object.
# We convert it back to the JSON format to print/score
print("Second Loop ", json.dumps(tweet))
# The command below will do pretty printing for JSON data, try it out
# print json.dumps(tweet, indent=4)
if tweet_count1 <= 0:
break |
e17b08273d7e4ef969ec3f1045a1b0428b8ac92d | siddu1998/PythonCP | /TurboSort.py | 101 | 3.515625 | 4 | t = int(input())
a = []
for i in range(t):
a.append(int(input()))
a.sort()
print(*a, sep='\n') |
1658511ddf06d9124b17445af3164864cdd45c39 | nilearn/nilearn | /examples/05_glm_second_level/plot_second_level_design_matrix.py | 1,994 | 4.34375 | 4 | """
Example of second level design matrix
=====================================
This example shows how a second-level design matrix is specified: assuming that
the data refer to a group of individuals, with one image per subject, the
design matrix typically holds the characteristics of each individual.
This is used in a second-level analysis to assess the impact of these
characteristics on brain signals.
This example requires matplotlib.
"""
try:
import matplotlib.pyplot as plt
except ImportError:
raise RuntimeError("This script needs the matplotlib library")
#########################################################################
# Create a simple experimental paradigm
# -------------------------------------
# We want to get the group result of a contrast for 20 subjects.
n_subjects = 20
subjects_label = [f"sub-{int(i):02}" for i in range(1, n_subjects + 1)]
##############################################################################
# Next, we specify extra information about the subjects to create confounders.
# Without confounders the design matrix would correspond to a one sample test.
import pandas as pd
extra_info_subjects = pd.DataFrame(
{
"subject_label": subjects_label,
"age": range(15, 15 + n_subjects),
"sex": [0, 1] * (n_subjects // 2),
}
)
#########################################################################
# Create a second level design matrix
# -----------------------------------
# With that information we can create the second level design matrix.
from nilearn.glm.second_level import make_second_level_design_matrix
design_matrix = make_second_level_design_matrix(
subjects_label, extra_info_subjects
)
#########################################################################
# Let's plot it.
from nilearn.plotting import plot_design_matrix
ax = plot_design_matrix(design_matrix)
ax.set_title("Second level design matrix", fontsize=12)
ax.set_ylabel("maps")
plt.tight_layout()
plt.show()
|
fa9b779bc8e4f2c9d15ed623d75fc81feed61956 | texnofile1/Python | /triangulos.py | 843 | 4.15625 | 4 | #ESTE PROGRAMA IDENTIFICA SI EL TIRANGULO INGRESADO
#ES INVALIDO,ISOSELES,ESCALENO O EQUILATERO
def es_triangulo(a,b,c):
if int(a)> int(b) + int(c):
return False
elif int(b)> int(a) + int(c):
return False
elif int(c)> int(b) + int(a):
return False
else:
return True
def tipo_triangulo(a,b,c,triangulo):
if triangulo == True:
if a == b and b == c:
return 'El triangulo es equilatero'
elif (a == b and b!=c) or (b == c and a!=c) or (a == c and a!=b):
return 'El triangulo es isoseles'
else:
return 'El triangulo es escaleno'
else:
return 'No es un triangulo valido.'
a=raw_input("Ingrese a:\n")
b=raw_input("Ingrese b:\n")
c=raw_input("Ingrese c:\n")
print tipo_triangulo(a,b,c,es_triangulo(a,b,c))
raw_input()
|
2eb09e042b4434cdc4a212ec62783493b69959f1 | OneRaynyDay/MarkovChain | /FileReader.py | 1,888 | 3.703125 | 4 | import re, string, random
class FileReader:
fileName = ""
listOfWords = []
RADIUS = 2
adjacencyMatrix = {} # Example : { ("a","b","c") : {"a" : 0, "b" : 2, "c" : 3} }
def __init__(self, fileName):
self.fileName=fileName
with open(fileName,'r') as f:
for line in f:
for word in line.split():
exclude = set(string.punctuation)
self.listOfWords.append((''.join(ch for ch in word if ch not in exclude)).lower())
def constructAdjacency(self):
for index, obj in enumerate(self.listOfWords):
if index < self.RADIUS or index >= len(self.listOfWords) - self.RADIUS:
continue #We don't need it to be here
tupleKey = (self.listOfWords[index-1], self.listOfWords[index])
insertWord = self.listOfWords[index+1]
if tupleKey not in self.adjacencyMatrix:
self.adjacencyMatrix[tupleKey] = {}
if insertWord in self.adjacencyMatrix[tupleKey]:
self.adjacencyMatrix[tupleKey][insertWord] += 1
else:
self.adjacencyMatrix[tupleKey][insertWord] = 1
#print(self.adjacencyMatrix)
def markovChain(self, tup, ct):
s = tup[0] + " " + tup[1]
while(tup in self.adjacencyMatrix and ct >= 0):
ct-= 1
d = self.adjacencyMatrix[tup]
sum = 0
for i in d:
sum += d[i]
n = random.random() * sum
num = 0
chosenWord = ""
for i in d:
num += d[i]
if num > n:
s += " " + i
chosenWord = i
print(chosenWord)
break
#print(tup[-1])
tup = (tup[1], chosenWord)
print(tup)
print(s) |
f3988cc49ca7ec3ce3937379fa982530684d14e3 | ms-wanjira/python-class | /question16.py | 288 | 3.6875 | 4 | email=input("Enter email: ")
password =str(input("Enter password: "))
def my_login():
x = email
y = password
if (x == "admin@gmail.com") and (y =="Admin@123"):
print("Login Succesful!")
else:
print("Fail login!")
my_login()
|
47032eb825f5e65f4718f292f21d7d65b31a1bcf | sjhaluck/sea-level-predictor | /sea_level_predictor.py | 1,000 | 3.734375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import linregress
def draw_plot():
# Read data from file
df = pd.read_csv('epa-sea-level.csv')
# Create scatter plot
fig = plt.figure(figsize = (12,8))
plt.scatter(df['Year'],df['CSIRO Adjusted Sea Level'])
# Create first line of best fit
slope, intercept, r_value, p_value, std_err = linregress(df['Year'],df['CSIRO Adjusted Sea Level'])
x = range(1880,2050)
plt.plot(x,intercept + slope*x)
# Create second line of best fit
slope2, intercept2, r_value2, p_value2, std_err2 = linregress(df[df['Year']>=2000]['Year'],df[df['Year']>=2000]['CSIRO Adjusted Sea Level'])
x2 = range(2000,2050)
plt.plot(x2, intercept2 + slope2*x2)
# Add labels and title
plt.xlabel('Year')
plt.ylabel('Sea Level (inches)')
plt.title('Rise in Sea Level')
# Save plot and return data for testing (DO NOT MODIFY)
plt.savefig('sea_level_plot.png')
return plt.gca() |
35cde7dbda15f3ce90190ee55c1d5387b89cce60 | Vaironl/CarDatabase | /DBConnection.py | 3,553 | 3.71875 | 4 | import sqlite3
import os
_db = None
def initConnection(db):
global _db
_db = str(db)
conn = sqlite3.connect(_db)
cursor = conn.cursor()
#Create tables
cursor.execute('''CREATE TABLE IF NOT EXISTS carlist (ID integer primary key, make TEXT, model TEXT, year TEXT, horsepower TEXT, engine TEXT,transmission TEXT)''')
cursor.execute('''CREATE TABLE IF NOT EXISTS carparts (CARID INT, partname TEXT, notes TEXT)''')
# Save (commit) the changes
conn.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
def listCars():
conn = sqlite3.connect(_db)
cursor = conn.cursor()
#Create table
cursor.execute("SELECT * FROM carlist")
carlist = cursor.fetchall()
# Save (commit) the changes
conn.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
return carlist
def clearAllValues():
conn = sqlite3.connect(_db)
cursor = conn.cursor()
#Create table
cursor.execute("DELETE FROM carlist")
# Save (commit) the changes
conn.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
def addCar(_car):
conn = sqlite3.connect(_db)
cursor = conn.cursor()
#NONE for ID
cursor.execute("INSERT INTO carlist VALUES (?,?,?,?,?,?,?)", (None,_car[0],_car[1],_car[2],_car[3],_car[4],_car[5]) )
conn.commit()
conn.close()
def updateCar(ID, _car):
conn = sqlite3.connect(_db)
cursor = conn.cursor()
#NONE for ID
#cur.execute("UPDATE Cars SET Price=? WHERE Id=?", (uPrice, uId))
cursor.execute("UPDATE carlist SET MAKE = ?, MODEL = ?, YEAR = ?, HORSEPOWER = ?, ENGINE = ?, TRANSMISSION = ? WHERE ID = ?", (_car[0],_car[1],_car[2],_car[3],_car[4],_car[5], ID) )
conn.commit()
conn.close()
def selectCar(carID):
conn = sqlite3.connect(_db)
cursor = conn.cursor()
cursor.execute("SELECT * FROM carlist WHERE ID = " + str(carID))
car = cursor.fetchall()
conn.commit()
conn.close()
return car[0]
def fetchCarParts(carID):
conn = sqlite3.connect(_db)
cursor = conn.cursor()
cursor.execute("SELECT * FROM carparts WHERE CARID = " + carID)
parts = cursor.fetchall()
#print parts
conn.commit()
conn.close()
return parts
def addCarPart(carID, carPartName, carNotes):
conn = sqlite3.connect(_db)
cursor = conn.cursor()
cursor.execute("INSERT INTO carparts VALUES (?,?,?)",(carID, carPartName, carNotes))
conn.commit()
conn.close()
def removeCar(car):
conn = sqlite3.connect(_db)
cursor = conn.cursor()
#Create table
cursor.execute("DELETE FROM carlist WHERE ID = " + car)
cursor.execute("DELETE FROM carparts WHERE carid = " + car)
# Save (commit) the changes
conn.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
def removeCarParts(carID, partname):
conn = sqlite3.connect(_db)
cursor = conn.cursor()
#Create table
cursor.execute("DELETE FROM carparts WHERE carid = ? AND partname = ? ", (carID, partname))
conn.commit()
conn.close()
|
60440796a244ce64945c42c007c6258d5d67a19d | jin1101/Leetcode | /007Reverse Integer.py | 294 | 3.6875 | 4 | class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
reversed_int = int(str(abs(x))[::-1])
if reversed_int >= 2 ** 31 - 1 or x == 0:
return 0
return reversed_int * -1 if x < 0 else reversed_int |
b04f9423605f1e87a16056ea18a554dd91d8517c | DeepakSunwal/Daily-Interview-Pro | /solutions/roman_numerals.py | 1,146 | 3.890625 | 4 | def convert(string):
result = 0
string_to_val_dict = {"I": 1,
"IV": 4,
"V": 5,
"IX": 9,
"X": 10,
"XL": 40,
"L": 50,
"XC": 90,
"C": 100,
"CD": 400,
"D": 500,
"CM": 900,
"M": 1000
}
index = len(string)-1
while index > -1:
if index > 0:
if string[index - 1] + string[index] in string_to_val_dict:
result += string_to_val_dict[string[index - 1] + string[index]]
index -= 1
else:
result += string_to_val_dict[string[index]]
else:
result += string_to_val_dict[string[index]]
index -= 1
return result
def main():
assert convert("IX") == 9
assert convert("VII") == 7
assert convert("MCMIV") == 1904
assert convert("MCMX") == 1910
if __name__ == '__main__':
main()
|
aee989de3a8e3bff4b771a9387874d9745a6a89c | somewayin/MyComputerCollegeCourses | /leetcode/langqiao_419/括号匹配.py | 420 | 3.75 | 4 | s=[]
def permutations(arr, position, end):
if position == end:
print(arr)
s.append("".join(arr))
else:
for index in range(position, end):
arr[index], arr[position] = arr[position], arr[index]
permutations(arr, position+1, end)
arr[index], arr[position] = arr[position], arr[index]
arr = ["(","(","(","(",")",")",")",")"]
permutations(arr, 0, len(arr))
print(len(s))
s=list(set(list(s)))
print(len(s))
|
aaa5b13b59f4193477d16020cf8dabe987d3e598 | pandrey76/Python-Project-By-Lynda.com | /3. 3. Using Design Patterns/08. Creating the maze in Python using the Builder design pattern/CountingMazeBuilder.py | 1,200 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#-------------------------------------------------------------------------------
# Name: модуль1
# Purpose:
#
# Author: Prapor
#
# Created: 05.09.2017
# Copyright: (c) Prapor 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
from MazeBuilderPattern import *
# implementation
class CountingMazeBuilder(MazeBuilder):
def __init__(self):
self._rooms = 0
self._doors = 0
def BuildRoom(self, n):
self._rooms += 1
def BuildDoor(self, r1, r2):
self._doors += 1
def GetCounts(self):
return self._rooms, self._doors
# ==================================================================
# Self-testing section
# ==================================================================
if __name__ == '__main__':
print('\n' * 2)
print('*' * 21)
print('*** The Counting Maze Game ***')
print('*' * 21)
game = MazeGame()
builder = CountingMazeBuilder()
game.CreateMaze(builder)
rooms, doors = builder.GetCounts()
print('The maze has {} rooms and {} doors'.format(rooms, doors))
|
9be4acd802f7f7e9c1d5df6310b4bfbed7de16c9 | coolsnake/JupyterNotebook | /new_algs/Graph+algorithms/Hungarian+algorithm/templateMatching.py | 6,094 | 3.5625 | 4 | import cv2;
import numpy as np;
#https://docs.opencv.org/3.1.0/dc/d2e/tutorial_py_image_display.html
#
input = cv2.imread('templates/test.jpg', cv2.IMREAD_COLOR);
version = "Laplace";
if version == "Laplace":
mode = cv2.IMREAD_GRAYSCALE;
else:
mode = cv2.IMREAD_COLOR;
#Templates to match against
#In normal mode it will use the colored images
#In Laplace mode it will use the grayscale images that highlight the edges
if mode == cv2.IMREAD_COLOR:
template_5 = cv2.imread('templates/5_szamc.png', mode);
template_10 = cv2.imread('templates/10_szamc.png', mode);
template_20 = cv2.imread('templates/20_szamc.png', mode);
template_50 = cv2.imread('templates/50_szamc.png', mode);
template_100 = cv2.imread('templates/100_szamc.png', mode);
template_200 = cv2.imread('templates/200_szamc.png', mode);
if mode == cv2.IMREAD_GRAYSCALE:
template_5 = cv2.imread('templates/5_szam.png', mode);
template_10 = cv2.imread('templates/10_szam.png', mode);
template_20 = cv2.imread('templates/20_szam.png', mode);
template_50 = cv2.imread('templates/50_szam.png', mode);
template_100 = cv2.imread('templates/100_szam.png', mode);
template_200 = cv2.imread('templates/200_szam.png', mode);
#Coins in order of size
templates = [template_5, template_100, template_10, template_20, template_50, template_200];
#Coin values
template_values = [5, 100, 10, 20, 50, 200, 0];
#Coin radius multipliers
template_scaling = [1.13513, 1.03, 1.09524, 1.04348, 1.0496, 1.0981];
#Inverting and smoothing template images
if mode == cv2.IMREAD_GRAYSCALE:
for template in templates:
template = cv2.GaussianBlur(template, (3, 3), 0);
template = cv2.bitwise_not(template);
kernel = np.ones((5,5), np.uint8);
width = input.shape[1];
height = input.shape[0];
blur = cv2.GaussianBlur(input, (3,3), 0);
gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY);
_, filtered = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU);
filtered = cv2.morphologyEx(filtered, cv2.MORPH_CLOSE, kernel);
filterEdges = cv2.Canny(filtered, 10, 100);
#hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV);
edges = cv2.Laplacian(gray, cv2.CV_64F);
edges = cv2.convertScaleAbs(edges);
mask = np.zeros((gray.shape[0], gray.shape[1]), np.uint8);
#https://docs.opencv.org/3.1.0/da/d53/tutorial_py_houghcircles.html
circles = cv2.HoughCircles(filterEdges, cv2.HOUGH_GRADIENT, 1, 70, param1=60, param2=30, minRadius=20, maxRadius=160);
original = np.copy(input);
matches = [];
bestIndices = [];
#NORMAL TEMPLATE MATCHING
for index, i in enumerate(circles[0,:]):
cv2.circle(input,(i[0],i[1]),i[2],(0,128,255),2)
bestMatchIndex = -1;
bestMatch = 0.0;
matches.append([]);
for k, template in enumerate(templates):
resized = cv2.resize(template, None, fx=i[2]*2/template.shape[0], fy=i[2]*2/template.shape[0], interpolation = cv2.INTER_CUBIC);
if version == "Laplace":
resized = cv2.Laplacian(resized, cv2.CV_64F);
resized = cv2.convertScaleAbs(resized);
res = cv2.matchTemplate(edges,resized,cv2.TM_CCOEFF_NORMED);
else:
res = cv2.matchTemplate(original,resized,cv2.TM_CCOEFF_NORMED);
prob = res[int(i[1]-i[2])][int(i[0]-i[2])];
matches[index].append(prob);
cv2.putText(input, "{:.3f}".format(prob), (int(i[0]-0.7*i[2]), int(i[1]-i[2]*0.4+k*14)), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 1, cv2.LINE_AA);
if prob > bestMatch:
bestMatch = prob;
bestMatchIndex = k;
bestIndices.append(bestMatchIndex);
cv2.putText(input, "{:d}".format(template_values[bestMatchIndex]), (int(i[0]+i[2]*0.6), int(i[1]-i[2] * 0.5)), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 0, 0), 1, cv2.LINE_AA);
cv2.putText(input, "{:.1f}".format(i[2]), (int(i[0]+i[2]*0.9), int(i[1]-i[2] * 0.2)), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 1, cv2.LINE_AA);
#Confidence for each coin on the picture
confidence = [];
highestConfidenceIndex = 0;
for r in range(0, len(bestIndices)):
sqrdiff = 0.0;
for i, match in enumerate(matches[r]):
if r != i:
#The confidence level is based on the difference from the highest probability coin
diff = abs(matches[r][bestIndices[r]] - matches[r][i]);
sqrdiff += diff;
confidence.append(sqrdiff);
if sqrdiff > confidence[highestConfidenceIndex]:
highestConfidenceIndex = r;
#print the confidence on each coin
for k, c in enumerate(confidence):
circle = circles[0][k];
cv2.putText(input, "{:.2f}".format(c), (int(circle[0]), int(circle[1]-circle[2])), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 1, cv2.LINE_AA);
#Calculate the radius of each coin type based on the radius of the known coin.
meanRadius = [None] * len(templates);
#The known radius
meanRadius[bestIndices[highestConfidenceIndex]] = circles[0][highestConfidenceIndex][2];
if bestIndices[highestConfidenceIndex] > 0:
for k in range(bestIndices[highestConfidenceIndex]-1, -1, -1):
meanRadius[k] = meanRadius[k+1] / template_scaling[k];
if bestIndices[highestConfidenceIndex] < len(templates):
for k in range(bestIndices[highestConfidenceIndex]+1, len(templates)):
meanRadius[k] = meanRadius[k-1] * template_scaling[k];
#Print the coin type on each coin, based on the minimal difference in radius to each predicted coin radius
for k, circle in enumerate(circles[0,:]):
bestIndex = 0;
for i, mean in enumerate(meanRadius):
diff = abs(circle[2] - mean);
if diff < circle[2] - meanRadius[bestIndex]:
bestIndex = i;
cv2.putText(input, "{:d}".format(template_values[bestIndex]), (int(circle[0]+circle[2]), int(circle[1]-circle[2])), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 1, cv2.LINE_AA);
#display the resulting frame
cv2.imshow('gray', gray);
cv2.imshow('laplacian', edges);
cv2.imshow('coins', filterEdges);
cv2.imshow('detect', input);
cv2.waitKey(0);
cv2.destroyAllWindows()
|
90b3f24e17c215fa3f5bfa7680be1473d55a29d9 | abhishekjani123/CodeChef-Solved-Questions | /Beginner - ATM [HS08TEST].py | 150 | 3.5625 | 4 | x,y = input().split()
x = int(x)
y = float(y)
if(x%5 == 0 and x+0.50<=y):
x = x+0.50
t = y-x
print('%0.2f' %t)
else:
print('%0.2f' %y) |
07f31bfac40b12e353347b0bde03b2d0d436a4c1 | sethdeane16/projecteuler | /resources/pef.py | 4,135 | 4.46875 | 4 | import math
import sys
def is_pandigital(number):
"""
Determine if a number is pandigital.
https://en.wikipedia.org/wiki/Pandigital_number
Args:
number: Number to check for pandigitality.
Returns:
True if number is pandigital, False otherwise
"""
number = str(number)
len_number = len(number)
beg = number[0:len_number]
end = number[-len_number:]
for i in map(str, range(1, len_number + 1)):
if i not in beg or i not in end:
return False
return True
def is_prime(number):
"""
Determines if a number is prime.
Args:
number: Number to evaluate for prime.
Returns:
True if number is prime, False otherwise.
"""
# ensure that we are working with a positive int
number = abs(int(number))
# edge case for 2 since it is prime
if number == 2:
return True
# not totally sure, but it works
if number < 2 or not number & 1:
return False
# use modulous to check for prime
for i in range(3, int(number**.5) + 1, 2):
if number % i == 0:
return False
return True
def prime_sieve(maximum):
"""
Efficiently creates a set with all prime numbers below the input maximum.
Args:
maximum: Number to generate primes below.
Returns:
List containing all primes below the maximum number.
"""
limitn = maximum+1
not_prime = set()
primes = []
# check to make sure that we are within a usuable range
if maximum <= 99999999:
# calculate primes and add them to a list
for i in range(2, limitn):
if i in not_prime:
continue
for f in range(i*2, limitn, i):
not_prime.add(f)
primes.append(i)
else:
print("WARNING: The prime_sieve maximum you chose is dangerously high! (Primes not generated)")
return primes
def gen_fib(maximum):
"""
Generates the list of fibonacci numbers below the maximum input
Args:
maximum: Number to generate fibonacci sequence below.
Returns:
List of fibonacci numbers below the maximum.
"""
fibnums = [1]
prev = 0
curr = 1
while curr <= maximum:
temp = curr + prev
prev = curr
curr = temp
if curr >= maximum:
break
fibnums.append(curr)
return fibnums
def reverse_num(number):
"""
Reverse a number.
E.g. 12345 = 54321
Args:
number: Number of forward number.
Returns:
Number in reverse.
"""
reverse = 0
while number > 0:
reverse = (reverse * 10) + number % 10
number = number // 10
return reverse
def is_shape(number, shapeNumber):
"""
Test if a number is of a "certain shape".
Currently only setup for Triangular, Pentagonal, and Hexagonal.
Args:
number: number to test for a "certain shape".
shapeNumber: number representing the "certain shape" to test.
E.g. 3 for triangular, 6 for hexagonal
Returns:
True if number is of that shape, False otherwise.
"""
# Test for triangular number (https://en.wikipedia.org/wiki/Triangular_number)
if shapeNumber == 3:
potentialNumber = (math.sqrt(1 + 8 * number) - 1) / 2
# Test for pentagonal number
if shapeNumber == 5:
potentialNumber = (math.sqrt(1 + 24 * number) + 1) / 6
# Test for hexagonal number (https://en.wikipedia.org/wiki/Hexagonal_number)
if shapeNumber == 6:
potentialNumber = (math.sqrt(1 + 8 * number) + 1) / 4
return potentialNumber == int(potentialNumber)
def answer(answer, time_taken):
"""
Function that neatly formats the answer printing process.
Args:
answer: Answer to the question.
time_taken: Time taken to solve the question.
Returns:
None, just prints the answer nicely.
"""
current_file = sys.argv[0].split("/")[-1] # get the running file name
print(f"Answer to {current_file} is [{answer}] and completed in [{time_taken}]")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.