blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
3b959c8b140a34401ffb7b0ca80be2115b7d5d03
|
brianchiang-tw/CodingInterviews
|
/21_Sort by Parity/by_module_and_element swap.py
| 550 | 3.5625 | 4 |
from typing import List
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
i, j = 0, 0
while i < len(nums):
if nums[i] % 2 == 1:
nums[i], nums[j] = nums[j], nums[i]
j += 1
i += 1
return nums
# n : the length of input list
## Time Complexity: O( n )
#
# The overhead in time is the cost of while-loop iteration, which is of O( n )
## Space Complexity: O( 1 )
#
# The overhead in space is the storage for loop index, which is of O( 1 )
|
52760e84dbbe500efdc1f6ec9c844452010238d6
|
victorazzam/stash
|
/Challenges/ZeroDays 2018/Reversing/1 Cryptex/cryptex.py
| 452 | 3.609375 | 4 |
#!/usr/bin/env python
password_guess= raw_input("Enter Password: ")
if len(password_guess) != 14:
print "Wrong Length"
exit()
verify_code = [113, 220, 168, 206, 164, 220, 180, 236, 250, 73, 196, 228, 220, 244]
user_code = []
for char in password_guess:
user_code.append( (((ord(char) << 2) | (ord(char) >> 5)) ^ 123) & 255 )
if (user_code == verify_code):
print "Well Done the flag is ZD2018{"+password_guess+"}"
else:
print "Incorrect"
|
13de4f848523a86a86d24ac9c2b986c0b4f9cd7c
|
Desperaaado/ex4
|
/ex4/ex4a.py
| 739 | 3.9375 | 4 |
from sys import argv
from sys import exit
lenth = len(argv)
def print_sentense(who='I', do='eat', what='apple'):
print(f'Today {who} {do} {what}!!')
if '-h' in argv or '--help' in argv:
print("""
HELP:
This program can show you a sentense on the basis of
three word which you inputed.
""")
exit(0)
try:
if lenth == 4:
script, who, do, what = argv
print_sentense(who, do, what)
elif lenth == 3:
script, who, do = argv
print_sentense(who, do)
elif lenth ==2:
script, who = argv
print_sentense(who)
else:
print('Today I eat apple.')
exit(1)
except ValueError:
print('Today I eat apple!!')
exit(0)
|
5bd011bb00cf377fc1f763aa73356d09df1597bd
|
EmanuelYano/python3
|
/URI - Lista 3/1217.py
| 353 | 3.671875 | 4 |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
mKg = mBrl = 0
i = 1
n = int(input())
while i <= n:
val = float(input())
frutas = input()
nFru = 1
for crtr in frutas:
if crtr == ' ':
nFru += 1
print("day %d: %d kg"%(i,nFru))
mKg += nFru
mBrl += val
i += 1
mKg /= n
mBrl /= n
print("%.2f kg by day"%(mKg))
print("R$ %.2f by day"%(mBrl))
exit(0)
|
7dbe9a52e02ba87f59876b03a79404bfe7888c26
|
eryeer/pythonStudy
|
/card_system/cards_tool.py
| 2,857 | 4 | 4 |
# 记录所有的名片字典
card_list = []
def show_menu():
"""show menu"""
print("*" * 50)
print("欢迎使用名片管理系统 V 1.0")
print("")
print("1. 新增名片")
print("2. 显示全部")
print("3. 搜索名片")
print("")
print("0. 退出系统")
print("*" * 50)
def new_card():
"""new card"""
print("-" * 50)
print("新增名片")
name_str = input("請輸入姓名:")
phone_str = input("請輸入電話:")
qq_str = input("請輸入QQ")
email_str = input("請輸入郵箱:")
card_dic = {"name": name_str, "phone": phone_str, "qq": qq_str, "email": email_str}
card_list.append(card_dic)
print("名片 %s 添加成功" % name_str)
def show_all():
"""show all cards"""
print("-" * 50)
if len(card_list) != 0:
for name in ["姓名", "電話", "QQ", "email"]:
print(name, end="\t\t")
print("")
print("=" * 50)
else:
print("沒有卡片記錄")
return
for card in card_list:
print("%s\t\t%s\t\t%s\t\t%s" % (card["name"],
card["phone"],
card["qq"],
card["email"]))
def search_card():
""" search card"""
print("-" * 50)
print("搜索名片")
find_name = input("請輸入要搜索的姓名:")
for card_dic in card_list:
if find_name == card_dic["name"]:
for name in ["姓名", "電話", "QQ", "email"]:
print(name, end="\t\t")
print("")
print("=" * 50)
print("%s\t\t%s\t\t%s\t\t%s" % (card_dic["name"],
card_dic["phone"],
card_dic["qq"],
card_dic["email"]))
deal_card(card_dic)
break
else:
print("抱歉沒有找到 %s" % find_name)
def deal_card(find_dict):
"""
:param find_dict:
"""
print(find_dict)
action_str = input("请选择需要的操作 "
"[1] 修改 [2] 删除 [0] 返回上级菜单")
if action_str == "1":
find_dict["name"] = input_card_info(find_dict["name"], "name:")
find_dict["phone"] = input_card_info(find_dict["phone"], "phone:")
find_dict["qq"] = input_card_info(find_dict["qq"], "qq:")
find_dict["email"] = input_card_info(find_dict["email"], "email:")
elif action_str == "2":
card_list.remove(find_dict)
print("删除名片成功")
def input_card_info(dic_value, tip_message):
"""
:param dic_value:
:param tip_message:
:return:
"""
result_str = input(tip_message)
if len(result_str) > 0:
return result_str
else:
dic_value
|
c8e224c420bcd860291e7346ffcddc01d5a66cb2
|
RookieLinLucy666/Codewar
|
/Where my anagrams at?.py
| 325 | 4 | 4 |
def anagrams(word, words):
sort_word = "".join(sorted(word))
result = []
for sub_words in words:
if sort_word == "".join(sorted(sub_words)):
result.append(sub_words)
else:
continue
return result
print(anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']))
|
eb1a937c0651bf59052b16a59e43f78d5f6a578a
|
kyleburton/sandbox
|
/examples/python/exceptions/ex.py
| 401 | 3.765625 | 4 |
#!/usr/bin/env python
import sys
while True:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError as e:
#import pdb; pdb.set_trace()
print "Oops! invalid number, try again. %s" % (e.message)
print "Oops! invalid number, try again. %s" % (sys.exc_info()[0])
try:
raise Exception("an exception")
except Exception as e:
print "caught it '%s'" % (e)
|
acafa1621ed2e0bf893eff4dc69bc326b10997b0
|
linctothepast/The-Game
|
/a_scenario/approaching_an_acorn_pile/approaching_acorn_pile.py
| 5,368 | 4 | 4 |
import random
# Function for the actual thing.
def approaching_acorn_pile():
print("APROACHING AN ACORN PILE")
print("---------------------------")
loop = True
while loop:
choice = input("""You're walking through the Forest of Kloa,
and you come across a small pile of acorns (they seem to be twitching).
How should you approach this?:
A: Shout at the pile of acorns, 'Is anyone there?'
B: Say quietly to the pile of acorns, 'Is anyone there?'
C: Poke the pile of acorns with your finger
D: Poke the acorn pile with a stick
E: Ask the pile 'Are you an acorn sprite?'
F: Throw a rock at the acorns
G: Tickle the acorn pile with a stick
H: Chop an acorn in half
I: Step on an acorn
J: Ignore the acorn pile
""")
choice = choice.capitalize()
if choice == "A":
acorn_pile_choice_a()
loop = False
elif choice == "B":
acorn_pile_choice_b()
loop = False
elif choice == "C":
acorn_pile_choice_c()
loop = False
elif choice == "D":
acorn_pile_choice_d()
loop = False
elif choice == "E":
acorn_pile_choice_e()
loop = False
elif choice == "F":
acorn_pile_choice_f()
loop = False
elif choice == "G":
acorn_pile_choice_g()
loop = False
elif choice == "H":
acorn_pile_choice_h()
loop = False
elif choice == "I":
acorn_pile_choice_i()
loop = False
elif choice == "J":
acorn_pile_choice_j()
loop = False
print("")
print("SCENARIO ENDED")
# Function for choice A:
def acorn_pile_choice_a():
loop = False
print("""(You hear a shreik from the acorn pile as an angry acorn
monster rises from the pile, and you initiate combat)""")
if loop:
print("")
# Function for choice B:
def acorn_pile_choice_b():
loop = False
print("""(You hear a loud growl from the acorn pile as
an angry acorn monster rises from the pile, and you initiate combat)""")
if loop:
print("")
# Function for choice C:
def acorn_pile_choice_c():
rng = random.randint(1, 4)
loop = False
if rng == 1:
print("""(While walking over to poke the acorn with your finger,
you accidently step on an acorn, then you hear a loud shreik from the acorn
pile as an angry acorn monster rises from the pile,
and you initiate combat)""")
else:
print("""(You poke the acorn pile with your finger,
and you hear a loud squeak from the acorn pile, and a passive acorn rises
looking angry, then tranforms into a hostile acorn monster
and you initiate in combat)""")
if loop:
print("")
# Function for choice D:
def acorn_pile_choice_d():
rng = random.randint(1, 4)
loop = False
if rng == 1:
print("""(While walking over to poke the acorn with a stick,
you accidently step on an acorn, then you hear a loud shreik from the acorn
pile as an angry acorn monster rises from the pile,
and you initiate combat)""")
else:
print("""(You poke the acorn pile with a stick, and you hear a
quiet squeak from the acorn pile, and a passive acorn rises looking angry,
then tranforms into a hostile acorn monster and you initiate combat)""")
if loop:
print("")
# Function for choice E:
def acorn_pile_choice_e():
loop = False
print("""(You hear an angry sqeaky voice say 'yes',
and you initiate combat)""")
if loop:
print("")
# Function for choice F:
def acorn_pile_choice_f():
loop = False
print("""(You hear a loud growl from the acorn pile as an angry acorn
monster rises from the pile, and you initiate combat)""")
if loop:
print("")
# Function for choice G:
def acorn_pile_choice_g():
loop = False
print("""(You go over and tickle the acorn pile with a stick,
and you hear a little giggle from the acorn pile. An adorable passive acorn
rises from the pile and says, 'You must be an ally,
you figured out how to approach us carefully!)""")
rng = random.randint(1, 100)
if rng == 1:
print("""(The acorn offers you a pile of acorns, and in it,
you see a shiny blue acorn!) This is a blue acorn it shows that you are
trustorthy, show it to any member of my kind
and they will instantly trust you!""")
blueacorn = True
if not blueacorn:
print("")
else:
print("(The acorn offers you a small pile of acorns!)")
if loop:
print("")
# Function for choice H:
def acorn_pile_choice_h():
loop = False
print("""(You decide to chop an acorn in half, and before
you even shop the acorn,
you hear a shreik from the acorn pile as an angry acorn monster rises
from the pile, and you initiate combat)""")
if loop:
print("")
# Function for choice I:
def acorn_pile_choice_i():
loop = False
print("""You step on an acorn, and you hear a loud shreik from the
acorn pile as an angry acorn monster rises from the pile,
and you initiate combat)""")
if loop:
print("")
# Function for choice J:
def acorn_pile_choice_j():
loop = False
print("(You ignore the acorn pile and go on your way)")
if loop:
print("")
# Playing the actual thing
approaching_acorn_pile()
|
a7fbd15da45dac1e382f471ebe03acb6830ebd26
|
IrisLiQinyi/mis3690
|
/hello.py
| 237 | 3.96875 | 4 |
print('hello, world')
name = input()
name
print(name)
name = input('Enter your name: ')
print ('Hello, ', name)
message ='I did something cool today!'
print (message)
n=100
print (n)
a=123
print (a)
a = 'ABC'
b=a
a='XYZ'
print(b)
|
bed18ae9c1fa6f6e919367127ca2fffff37a199c
|
viciouspetal/knn-ml-cit
|
/common_utils.py
| 4,088 | 4.09375 | 4 |
import pandas as pd
import numpy as np
def load_data(path, columns):
"""
For a given path to file it loads a dataset with given headers.
:param path: paths to dataset
:param columns: columns specified for a given dataset
:return: dataset with headers loaded in a pandas dataframe
"""
df = pd.read_csv(path, names=columns, header=None)
return df
def calculate_distances(data_points, query_instance):
"""
Calculates a distance matrix for each of the records detailing how far each datapoint is from a given query instance.
Additionally computes a sorted array detailing indices of the smallest to largest distance from a given
query point, from smallest (or closest point to query instance) to largest.
:param data_points: data points of a given dataset
:param query_instance: instance of a dataset for which the distance matrix will be computed for
:return:
"""
# row wise sum with a negative lookahead
distance_matrix = euclideanDistance(data_points, query_instance)
#print('For query instance of {0} the distance matrix is {1}'.format(query_instance,distance_matrix))
# sorts the distance matrix and returns indices of elements from smallest distance value to largest
sorted_distance_matrix = np.argsort(distance_matrix)[np.in1d(np.argsort(distance_matrix),np.where(distance_matrix),1)]
return distance_matrix, sorted_distance_matrix
def euclideanDistance(data_points, query_instance):
"""
Calculate euclidean distance
:param data_points: data points of a given dataset
:param query_instance: instance of a dataset for which the distance matrix will be computed for
:return: distance value
"""
return np.sqrt(((data_points - query_instance) ** 2).sum(-1))
def manhattanDistance(data_points, query_instance):
"""
Calculate manhattan distance
:param data_points: data points of a given dataset
:param query_instance: instance of a dataset for which the distance matrix will be computed for
:return: distance value
"""
return np.abs(data_points - query_instance).sum(-1)
def minkowskiDistance(data_points, query_instance, p_value = 1):
"""
Calculate minkowski distance
:param data_points: data points of a given dataset
:param query_instance: instance of a dataset for which the distance matrix will be computed for
:param p_value:
:return: distance value
"""
return np.abs(((data_points - query_instance) / p_value) / (1 / p_value)).sum(-1)
def clean_cancer_dataset(df_training):
"""
Checks and cleans the dataset of any potential impossible values, e.g. bi-rads columns, the 1st only allows
values in the range of 1-5, ordinal
Age, 2nd column, cannot be negative, integer
Shape, 3rd column, only allows values between 1 and 4, nominal
Margin, only allows a range of 1 to 5, nominal
Density only allows values between 1-4,ordinal.
All deletions will be performed in place.
:return: cleaned up dataframe, count of removed points
"""
rows_pre_cleaning = df_training.shape[0]
df_training.drop(df_training.index[df_training['bi_rads'] > 5], inplace=True)
df_training.drop(df_training.index[df_training['shape'] > 4], inplace=True)
df_training.drop(df_training.index[df_training['margin'] > 5], inplace=True)
df_training.drop(df_training.index[df_training['density'] > 4], inplace=True)
rows_removed = rows_pre_cleaning - df_training.shape[0]
return df_training, rows_removed
def compute_classification_accuracy(correctly_classified, incorrectly_classified):
"""
Computes the accuracy of the model based on the number of correctly and incorrectly classified points.
Expresses accuracy as a percentage value.
:param correctly_classified: count of correctly classified data points
:param incorrectly_classified: count of incorrectly classified data points
:return: accuracy score
"""
accuracy = (correctly_classified / (correctly_classified + incorrectly_classified)) * 100
return accuracy
|
5ec9665ecf9a15fd38a1a45c23188ba68fe8fa25
|
Me-Pri/Python-programs
|
/multiple_inheritance.py
| 462 | 4.0625 | 4 |
class add:
def operate1(self):
self.sum=self.a+self.b
return self.sum;
class subtract:
def operate2(self):
self.diff=self.a-self.b
return self.diff;
class multiply(add,subtract):
def input(self):
self.a=int(input("Enter the first no: "))
self.b=int(input("Enter the second no: "))
def operate3(self):
self.mul=self.a*self.b
return self.mul;
m=multiply()
m.input()
print(m.operate1())
print(m.operate2())
print(m.operate3())
|
1ba008e2c977fd4fc1f521d26401bf3ce672ab2a
|
msullivancm/CursoEmVideoPython
|
/Mundo2-ExerciciosEstruturasDeRepeticao/ex057.py
| 204 | 3.75 | 4 |
c = 1
while c != 0:
sexo = str(input('Informe seu sexo: [M/F]:')).upper()
if sexo != 'M' and sexo != 'F':
c = 1
print('Digite M ou F somente.')
else:
c = 0
print('fim')
|
4392ca6533302eb1edf55d6fd0eac912e322dd12
|
hemangbehl/Data-Structures-Algorithms_practice
|
/leetcode_session2/queue_builtin.py
| 234 | 3.953125 | 4 |
from queue import Queue
a = Queue()
print (a)
print("size", a.qsize())
a.put(1)
a.put(2)
a.put(3)
print(a)
a.get() #removes and returns an item
print ("size", a.qsize())
#print queue
for i in range(a.qsize()):
print (a.get())
|
b7893d4fcfb8902ea43e42fcdf1195c9494ebf67
|
JoseJunior23/Iniciando-Python
|
/cursoemvideo/aula10.py
| 180 | 4.03125 | 4 |
nome = str(input('Qual o seu nome: '))
if nome == 'Junior':
print('É um belo nome!')
else:
print('seu nome não contem Junior que pena!')
print('Bom dia, {}'.format(nome))
|
a2f92a11505a09b14f14b79e4879da2c0ba2e406
|
akrizma12/pythonProjects
|
/H3/trace_me.py
| 2,080 | 3.953125 | 4 |
# The Python program trace_me.py is posted next to this handout on Canvas.
# Download it and add to your project for this assignment. Set breakpoints on the two print("set...") statements in this program.
# Run your program in the PyCharm debugger and enter 5 for the first input, then the values 1.0, -2.0, 3.0, -4.0, 5.0 for the five subsequent inputs.
# When your program stops at each breakpoint, write down the values of a, b, c, d, and e.
# Then resume until the next breakpoint is encountered. Finally, add comments (lines starting with #)
# at the end of the program which lists the five sets of such breakpoint values,
# followed by the values for the final breakpoint. Your program should thus end with a comment
# that lists six total sets of the values for a, b, c, d, and e. Submit your code with these comments as your delivery for this problem.
# Figure out what this program does, then rename the variables to better reflect its meaning.
# You are refactoring the program: changing its structure to improve readability, but not changing its behavior.
# Resubmit this version of the code to Canvas.
# Unfortunately, the given code doesn't always compute the correct values for all input data. Why? Discuss in class how to fix this.
#
# H3-5: run the following in the PyCharm debugger and print
# the following requested info...
num = int(input("enter number of floats: "))
maxBetweenTwoNumbers = 0.0
minBetweenTwoNumbers = 0.0
c = 0.0
for d in range(num):
e = float(input("enter next float: "))
maxBetweenTwoNumbers = max(maxBetweenTwoNumbers, e)
minBetweenTwoNumbers = min(minBetweenTwoNumbers, e)
c = c + e
print("set breakpoint here...")
# maxBetweenTwoNumbers= 1.0, minBetweenTwoNumbers = 0.0, c = 1.0, d = 0, e = 1.0
# list values of a, b, c, d, e at this point, each time through loop
print(maxBetweenTwoNumbers)
print(minBetweenTwoNumbers)
print(c / num)
print("set another breakpoint here...")
# maxBetweenTwoNumbers = 5.0, minBetweenTwoNumbers = -4.0, c = 3.0, d = 4, e = 5.0
# list final values of a, b, c, d, e
|
c2fdab62f985323ffbe6340f333ca6da1fa6b407
|
ninepillars/trunk
|
/example/pythonexample/bookexample/lession_1/lession_1_3.py
| 1,337 | 3.5625 | 4 |
# coding: utf-8
'''
Created on 2011-11-28
@author: Lv9
'''
a = 1;
b = 2;
product = "game";
productType = "pirate memory";
age = 5;
suffix = ".png";
s = "Lv9 is a cool kid"
hasLv9 = True;#Python的布尔值分别为True和False
if a < b:
print("Computer says yes");
else:
print("Computer says no");
if a < b:
pass;#空子句是不允许的 要创建一条空子句可用pass关键字
else:
print("Computer says no");
#使用or、and和not关键字可以建立布尔类型的表达式('\'可以在下一行继续书写上一条语句的内容 当单行语句过长时可以用这个将其分开)
if product == "game" and productType == "pirate memory" \
and not (age < 4 or age > 8):
print("I'll take it");
else:
pass;
#Python没有switch语句 只能用elif完成(相当于Java里的else if)
if suffix == ".htm":
print("text/html");
elif suffix == ".jpg":
print("image/jpeg");
elif suffix == ".png":
print("image/png");
else:
raise RuntimeError("Unknown content type");
'''
in关键字可以在一个指定的数组、MAP、字符串中去寻找指定的关键字
所有的关系运行符 返回的结果都是布尔类型结果(True或False)
'''
if 'Lv9' in s:
hasLv9 = True;
else:
hasLv9 = False;
|
b029886a76caba4d52b55a5262aa1afbb7f57477
|
gitForKrish/PythonInPractice
|
/TeachingPython/math03.py
| 611 | 3.828125 | 4 |
'''
5. Write all possible 2-digits numbers that can be formed by using the digits 2, 3 and 4.
Repetition of digits is not allowed. Also find their sum.
output: 23,24,32,34,42,43 - >
'''
def find_numbers(digits, decimal_place):
generated_numbers = []
for (index, value) in enumerate(digits): # 2,3,4
remaining = digits[:] # 0,1,2
remaining.pop(index)
for (ind2, val2) in enumerate(remaining):
generated_numbers.append(value * 10 + val2)
return generated_numbers
numbers = find_numbers([2, 3, 4, 5, 6], 2)
print(numbers)
print(len(numbers))
|
c8fefc38670bd237ea1eeeecc5469087add08b9e
|
deepashreeKedia/Solutions
|
/secret_number
| 698 | 4.1875 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 14 15:50:57 2018
@author: deep
"""
# Paste your code into this box
print("Please think of a number between 0 and 100!")
low = 0
high = 100
while True:
guess = (low + high) // 2
print("Is your secret number {}?".format(guess))
ans = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if ans == 'l':
low = guess
elif ans == 'h':
high = guess
elif ans == 'c':
print("secret number is", guess)
break
else:
print("Sorry, I did not understand your input.")
|
24840bf0b8d4fc375a84e0e04a88258639f304c6
|
ShanjinurIslam/HackerRank
|
/min_max_sum.py
| 500 | 3.59375 | 4 |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the miniMaxSum function below.
def miniMaxSum(arr):
min_val = 2e10
max_val = -1
total = 0
for each in arr:
if min_val > each:
min_val = each
if max_val < each:
max_val = each
total += each
print(total-max_val,total-min_val)
if __name__ == '__main__':
arr = list(map(int, input().rstrip().split()))
miniMaxSum(arr)
|
46342767b1a5a5b8c396e2084582cb025ecfe83e
|
pink-sheep/duplicates
|
/main.py
| 1,574 | 3.875 | 4 |
##########################################################
################# Plagiarism detection ###################
##########################################################
#### Main - user interation
# manages the plagiarism detection program, introduces
# human-computer interaction
import os, preprocessing, near, exact, finn
def choice(texts):
print (" For exact duplicates press - 1 \n" +
" For near duplicates press - 2 \n" +
" For Finn's plateu method press - 3\n" +
" To exit press Enter\n")
num = input("Enter your choice ")
print "\n"
try:
if (num == 1):
print "The candidates for exact duplicates are as follows:"
de = exact.exact_duplicates(texts)
for item in de:
print item
print "\n"
choice(texts)
elif (num == 2):
print "The candidates for near duplicates are as follows:"
dn = near.near_duplicates(texts)
for item in dn:
print item
print "\n"
choice(texts)
elif (num == 3):
print "The candidates for duplicates using Finn's metod are as follows:"
df = finn.finn_duplicates(texts)
for item in df:
print item
print "\n"
choice(texts)
except:
print "\nGood-bye"
if __name__ == "__main__":
print "Welcome to Plagiarism Detection program\n"
texts = preprocessing.prepare()
choice(texts)
|
1f67d7dd406c4eb85cc8be9f20c8010c6b20f47e
|
buyuxing/leetcode-cn
|
/python/679. 24点游戏.py
| 4,023 | 3.5 | 4 |
'''
https://leetcode-cn.com/problems/24-game/description/
679. 24点游戏
你有 4 张写有 1 到 9 数字的牌。你需要判断是否能通过 *,/,+,-,(,) 的运算得到 24。
示例 1:
输入: [4, 1, 8, 7]
输出: True
解释: (8-4) * (7-1) = 24
示例 2:
输入: [1, 2, 1, 2]
输出: False
注意:
除法运算符 / 表示实数除法,而不是整数除法。例如 4 / (1 - 2/3) = 12 。
每个运算符对两个数进行运算。特别是我们不能用 - 作为一元运算符。例如,[1, 1, 1, 1] 作为输入时,表达式 -1 - 1 - 1 - 1 是不允许的。
你不能将数字连接在一起。例如,输入为 [1, 2, 1, 2] 时,不能写成 12 + 12 。
'''
class Operator(object):
def realNum(self, x):
return x() if callable(x) else x
class Add(Operator):
def __init__(self,x,y):
self.x = x
self.y = y
def __call__(self):
return self.realNum(self.x) + self.realNum(self.y)
def __str__(self):
return '({0} + {1})'.format(self.x,self.y)
class Minus(Operator):
def __init__(self,x,y):
self.x = x
self.y = y
def __call__(self):
return self.realNum(self.x) - self.realNum(self.y)
def __str__(self):
return '({0} - {1})'.format(self.x,self.y)
class _Minus(Operator):
def __init__(self,x,y):
self.x = x
self.y = y
def __call__(self):
return self.realNum(self.y) - self.realNum(self.x)
def __str__(self):
return '({1} - {0})'.format(self.x,self.y)
class Mul(Operator):
def __init__(self,x,y):
self.x = x
self.y = y
def __call__(self):
return self.realNum(self.x) * self.realNum(self.y)
def __str__(self):
return '{0} * {1}'.format(self.x,self.y)
class Div(Operator):
def __init__(self,x,y):
self.x = x
self.y = y
def __call__(self):
return self.realNum(self.x) / self.realNum(self.y)
def __str__(self):
return '{0} / {1}'.format(self.x,self.y)
class _Div(Operator):
def __init__(self,x,y):
self.x = x
self.y = y
def __call__(self):
return self.realNum(self.y) / self.realNum(self.x)
def __str__(self):
return '{1} / {0}'.format(self.x,self.y)
calculate = [Add, Minus, _Minus, Mul, Div, _Div]
def canGet24(card):
try:
if len(card) == 1:
if(abs(24- card[0]()) < 0.0000000000001):
str = card[0].__str__()
if str[0]=='(':
str = str[1:-1]
print(str)
return True
else:
return False
if len(card) == 2:
# return card[0]+card[1] == 24 or card[0]-card[1]==24 or card[1]-card[0]==24 or card[0] * card[1]==24 or card[0]/card[1]==24 or card[1]/card[0]==24
for fun in calculate:
if canGet24([fun(card[0],card[1])]) == True:
return True
return False
if len(card) == 3:
for fun in calculate:
x,y,z = card
if canGet24([x,fun(y,z)]) == True:
return True
if canGet24([y,fun(x,z)]) == True:
return True
if canGet24([z,fun(x,y)]) == True:
return True
return False
for fun in calculate:
a,b,c,d = card
if canGet24([fun(a,b),c,d]) == True:
return True
if canGet24([fun(a,c),b,d]) == True:
return True
if canGet24([fun(a,d),b,c]) == True:
return True
if canGet24([fun(b,c),a,d]) == True:
return True
if canGet24([fun(b,d),a,c]) == True:
return True
if canGet24([fun(c,d),a,b]) == True:
return True
return False
except ZeroDivisionError:
return False
def main():
print(canGet24([4,1,8,7]))
if __name__ == '__main__':
main()
|
70968c67e7a72dab62fb7d4c42bc983eb4db9430
|
neeraj-badam/python
|
/Lab Internal/12.Dijkstra.py
| 1,291 | 3.703125 | 4 |
# Dijkstra's
import heapq as heap
import sys
class Pair:
def __init__(self,first,second) -> None:
self.first = first
self.second = second
def __lt__(self,next):
return self.first < next.first
def dijkstra(g,source,destination):
n = len(g)
dis = [sys.maxsize]*(n+1)
minHeap = []
dis[source] = 0
heap.heappush(minHeap,Pair(0,source))
while len(minHeap) != 0:
p = heap.heappop(minHeap)
u,dt = p.second,p.first
if u == destination :
return dis[u]
for pair in g[u]:
w,v = pair.first,pair.second
old_distance,new_distance = dis[v],dt+w
if new_distance < old_distance:
dis[v] = new_distance
heap.heappush(minHeap,Pair(new_distance,v))
heap.heapify(minHeap)
return None
for _ in range(int(input())):
n,edge = map(int,input().split())
g = []
for _ in range(n+1):
g.append([]*(n+1))
for _ in range(edge):
u,v,w = map(int,input().split())
g[u].append(Pair(w,v))
source,destination = map(int,input().split())
res = dijkstra(g,source,destination)
if res == None:
print("NO")
else:
print(res)
|
4275646ad3d54cf408852112c09698d69c51ce66
|
litvaOo/algorithms_and_structures
|
/Lab02.py
| 1,147 | 3.65625 | 4 |
class HashTable:
def __init__(self, size):
self.size = size
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hashvalue = self.hash(key)
if self.slots[hashvalue] is None:
self.slots[hashvalue] = key
self.data[hashvalue] = data
else:
self.data[hashvalue] = data
def hash(self, key):
sum = 0
for counter, char in enumerate(key):
sum += ord(char)*counter
return sum%self.size
def get(self, key):
starthash = self.hash(key)
if self.slots[starthash] is None:
return None
return self.data[starthash]
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, data):
self.put(key, data)
if __name__ == '__main__':
n, m = input().split()
hash_table = HashTable(int(n))
keys = []
for _ in range(int(n)):
key, value = input().split()
hash_table[key] = value
for _ in range(int(m)):
keys.append(input())
for key in keys:
print(hash_table[key])
|
a90e149f7147f8b4a3844d84e5fe768ea51f5e91
|
dhumindesai/Problem-Solving
|
/educative/two_heaps/MedianOfAStream.py
| 1,352 | 3.984375 | 4 |
from heapq import *
class MedianOfAStream:
max_heap = []
min_heap = []
def insert_num(self, num):
if not self.max_heap or -self.max_heap[0] > num:
heappush(self.max_heap, -num)
else:
heappush(self.min_heap, num)
# if min_heap has more elements than max_heap, adjust
if len(self.min_heap) > len(self.max_heap):
heappush(self.max_heap, -heappop(self.min_heap))
if len(self.max_heap) > len(self.min_heap) + 1:
heappush(self.min_heap, -heappop(self.max_heap))
def find_median(self):
if len(self.max_heap) == len(self.min_heap):
return (-self.max_heap[0] + self.min_heap[0]) / 2
else:
return -self.max_heap[0]
def main():
medianOfAStream = MedianOfAStream()
medianOfAStream.insert_num(3)
medianOfAStream.insert_num(1)
print("The median is: " + str(medianOfAStream.find_median()))
medianOfAStream.insert_num(5)
print("The median is: " + str(medianOfAStream.find_median()))
medianOfAStream.insert_num(4)
print("The median is: " + str(medianOfAStream.find_median()))
medianOfAStream.insert_num(2)
print("The median is: " + str(medianOfAStream.find_median()))
medianOfAStream.insert_num(6)
print("The median is: " + str(medianOfAStream.find_median()))
main()
|
9c28d69b00f31d5394112a31340e6c44b2de6faf
|
varshajoshi36/practice
|
/leetcode/python/easy/symmetricTree.py
| 1,217 | 4.4375 | 4 |
"""
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def checkLeftRight(self, l_root, r_root):
if l_root == None or r_root == None:
if l_root == None and r_root == None:
return True
else:
return False
elif l_root.val == r_root.val:
is_left_mirror = self.checkLeftRight(l_root.left, r_root.right)
is_right_mirror = self.checkLeftRight(l_root.right, r_root.left)
return is_left_mirror and is_right_mirror
else:
return False
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
return self.checkLeftRight(root.left, root.right)
|
03e81f455a5d2bab66078ff4c210da966c8958de
|
dinoivusic/Python-Challenges
|
/day35.py
| 222 | 3.609375 | 4 |
def overlap(arr,num):
count = 0
for i in range(len(arr)):
if arr[i][0] == num or arr[i][1] == num:
count+=1
if num > arr[i][0] and num < arr[i][1]:
count+=1
return count
|
73b01e4dd8b166684ab37d4a43213f367d294656
|
ArunkumarSennimalai/-Python-Assignment2
|
/Assingment2/37.py
| 1,588 | 3.5625 | 4 |
import json
def biggestDict(dict1,dict2,dict3):
biggestDict = dict2
if cmp(dict1,dict2):
biggestDict = dict1
if cmp(dict3,biggestDict):
biggestDict = dict3
return biggestDict
def addToDict(tempdict,key,val):
tempdict[key] = val #dict2['l'] = 12
def addDictToAnotherDict(tempdict1,tempdict2):
tempdict1.update(tempdict2) #dict1.update({'j':10,'k':11})
def findLength(tempdict):
return len(tempdict)
def convertToStringAndConcatenate(dict1,dict2,dict3):
return str(dict1) + str(dict2) + json.dumps(dict3) #str(dict3)
if __name__ == "__main__":
try:
dict1 = {'a':1,'b':2,'c':3}
dict2 = {'d':4,'e':5,'f':6}
dict3 = {'g':7,'h':8,'i':9}
#finding biggest dict
biggest = biggestDict(dict1,dict2,dict3)
print "biggest dict is ", biggest
#adding new elements to dict
addDictToAnotherDict(dict1,{'j':10,'k':11})
print dict1
addToDict(dict2,'l',12)
print dict2
#printing length
dict1_len = findLength(dict1)
print "length of",dict1,"is",dict1_len
dict2_len = findLength(dict2)
print "length of",dict2,"is",dict2_len
dict3_len = findLength(dict3)
print "length of",dict3,"is",dict3_len
#convert to string and concatenate
str = convertToStringAndConcatenate(dict1,dict2,dict3)
print "Final string is",str
except Exception as e:
print(e)
|
3a2738c0e3f007f9e2ad33bc5c55d91ca129842b
|
89chrisp/python-course-project
|
/adventure/one.py
| 3,999 | 3.890625 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Room one
"""
import gameItem
import game
descr = """-------------------------------------------------------------------------------
Room no. 1
You find yourself in a room without windows.
There is a table in the room and the walls are decorated with some paintings.
There is also a book upon the table.
-------------------------------------------------------------------------------
"""
solved = False
roomInv = {}
hint = """
There are some strange marks on the wall next to one of the paintings...
"""
look = """
As you look around the room you see a worn table and some mundane paintings
decorating the walls. There is a book lying on the table.
A sturdy door is the only exit from the room.
"""
door = gameItem.gameItem()
door.name = "door"
door.descr = "A sturdy door which looks too solid to force..."
door.openable = True
door.useable = True
roomInv[door.name] = door
table = gameItem.gameItem()
table.name = "table"
table.descr = "A wooden rectangular table with a drawer attached."
table.openable = True
roomInv[table.name] = table
painting_1 = gameItem.gameItem()
painting_1.name = "left painting"
painting_1.descr = "A painting depicting a boat."
painting_1.moveable = True
roomInv[painting_1.name] = painting_1
painting_3 = gameItem.gameItem()
painting_3.name = "right painting"
painting_3.descr = "A painting depicting a cow. This painting looks more worn."
painting_3.moveable = True
roomInv[painting_3.name] = painting_3
painting_2 = gameItem.gameItem()
painting_2.name = "middle painting"
painting_2.descr = "A painting depicting a meadow."
painting_2.moveable = True
roomInv[painting_2.name] = painting_2
book = gameItem.gameItem()
book.name = "book"
book.descr = "The title reads 'Secrets to move forward'."
book.openable = True
book.storeable = True
roomInv[book.name] = book
def wire_cutterItem():
"""
Creates the wire_cutter
"""
wire_cutter = gameItem.gameItem()
wire_cutter.name = "wire cutter"
wire_cutter.descr = "Used for cutting wires."
wire_cutter.storeable = True
roomInv[wire_cutter.name] = wire_cutter
def switchItem():
"""
Creates a switch item in the room
"""
switch = gameItem.gameItem()
switch.name = "switch"
switch.descr = "A small switch hidden behind the painting"
switch.useable = True
roomInv[switch.name] = switch
def openItem(item):
"""
Opens item
"""
if item == "book":
print("""As you open the book you find the pages are filled with unintelligible text.
The only discernable information is the name of the author: E. W. S. North """)
elif item == "door":
if solved:
print("The door is unlocked.")
else:
print("The door is locked.")
elif item == "table":
if "wire cutter" not in game.inv:
print("You open the drawer of the table. There is a wire cutter inside.")
wire_cutterItem()
else:
print("The drawer is empty. ")
# def kick(item):
# """
# Kicks item
# """
def move(item):
"""
Moves item
"""
if item == "left painting":
print("""The painting slides to the side as you move it and then returns
roughly to its original position.""")
elif item == "middle painting":
print("""The painting slides to the side as you move it and then returns
roughly to its original position.""")
elif item == "right painting":
print("""The painting slides to the side as you move it. There is a small
switch behind the painting!""")
switchItem()
def use(item):
"""
Uses the item
"""
global solved
if item == "switch":
print("""As you press the switch there is a subtle 'click' sound coming
from the locked door...""")
solved = True
game.solved_rooms["one"] = True
elif item == "door":
if solved:
print("The door is unlocked.")
else:
print("The door is locked.")
|
f7001ee78ebdfc5de4913ed025a95bad63de0593
|
candyer/leetcode
|
/2020 December LeetCoding Challenge/26_numDecodings.py
| 1,634 | 3.765625 | 4 |
# https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/572/week-4-december-22nd-december-28th/3581/
# Decode Ways
# A message containing letters from A-Z is being encoded to numbers using the following mapping:
# 'A' -> 1
# 'B' -> 2
# ...
# 'Z' -> 26
# Given a non-empty string containing only digits, determine the total number of ways to decode it.
# The answer is guaranteed to fit in a 32-bit integer.
# Example 1:
# Input: s = "12"
# Output: 2
# Explanation: It could be decoded as "AB" (1 2) or "L" (12).
# Example 2:
# Input: s = "226"
# Output: 3
# Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
# Example 3:
# Input: s = "0"
# Output: 0
# Explanation: There is no character that is mapped to a number starting with '0'. We cannot ignore a zero when we face it while decoding. So, each '0' should be part of "10" --> 'J' or "20" --> 'T'.
# Example 4:
# Input: s = "1"
# Output: 1
# Constraints:
# 1 <= s.length <= 100
# s contains only digits and may contain leading zero(s).
def numDecodings(s: str) -> int:
n = len(s)
if s[0] == '0': return 0
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for i in range(1, n):
if s[i] != '0':
dp[i + 1] = dp[i]
if s[i - 1] != '0' and 1 <= int(s[i - 1: i + 1]) <= 26:
dp[i + 1] += dp[i - 1]
return dp[n]
assert(numDecodings('12') == 2)
assert(numDecodings('226') == 3)
assert(numDecodings('0') == 0)
assert(numDecodings('1') == 1)
assert(numDecodings('102233') == 3)
assert(numDecodings('02233') == 0)
|
07d19e6dee75c1325cf33829f7f5e561066903e0
|
Vejusatko/Pyladies_beginners_course
|
/02/task07_house.py
| 355 | 3.640625 | 4 |
from turtle import forward, left, right, exitonclick
from math import sqrt
#house variables
x = 100
diagonal = sqrt(2*(x**2))
#let's draw
forward(x)
left(135)
forward(diagonal)
right(135)
forward(x)
left(120)
forward(x)
left(120)
forward(x)
left(30)
forward(x)
left(135)
forward(diagonal)
right(135)
forward(x)
#exit
exitonclick()
|
c0051c43975ff7d55df1fa1b4a205ad73c2dec91
|
ramsayleung/leetcode
|
/600/valid_parenthesis_string.py
| 1,614 | 4.28125 | 4 |
"""
source: https://leetcode.com/problems/valid-parenthesis-string/
author: Ramsay Leung
date: 2020-02-17
Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:
Any left parenthesis '(' must have a corresponding right parenthesis ')'.
Any right parenthesis ')' must have a corresponding left parenthesis '('.
Left parenthesis '(' must go before the corresponding right parenthesis ')'.
'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.
An empty string is also valid.
Example 1:
Input: "()"
Output: True
Example 2:
Input: "(*)"
Output: True
Example 3:
Input: "(*))"
Output: True
Note:
The string size will be in the range [1, 100].
"""
class Solution:
def checkValidString(self, s: str) -> bool:
if not s:
return True
chars = list(s)
leftBalanced = 0
for c in chars:
if c == '*' or c == '(':
leftBalanced += 1
else:
leftBalanced -= 1
# ensure `(` go before `)`
if leftBalanced < 0:
return False
if leftBalanced == 0:
return True
rightBalanced = 0
for c in reversed(chars):
if c == ')' or c == '*':
rightBalanced += 1
else:
rightBalanced -= 1
# ensure ')' go after '('
if rightBalanced < 0:
return False
return True
|
e5f2b0b03acefae21ed2009fcffb80a95731f628
|
thomasngn673/Python-with-ATBS
|
/conwaysGameOfLife.py
| 3,092 | 4.1875 | 4 |
# Conway's Game of Life Rules
# 1. If a living square has 2-3 living neighbors, it continues to live
# 2. If a dead square has exactly 3 living neighbors, it comes to live
import random, time, copy
width = 12
height = 4
# creates a list of x values that each have own individual list of y values
# creates a list of lists
nextCells = []
for x in range(width):
column = [] # create a new column
for y in range(height):
if random.randint(0, 1) == 0:
column.append('#') # add a living cell
else:
column.append(' ') # add a dead cell
nextCells.append(column)
while True: # main program loop
print('\n\n\n\n\n') # separate each step with newlines
currentCells = copy.deepcopy(nextCells)
# print currentCells on the screen
for y in range(height):
for x in range(width):
print(currentCells[x][y], end='') # prints the '#' or 'space'
# "for y in range" is put first because "end=''" deletes newline
# "end=''" creates horizontal prints, so order is reversed
# in current loop, y value does not change, only x
print() # prints a newline at the end of the row
# without this, the entire box is printed on one line
# calculate the next step's cells based on current step's cells
for x in range(width):
for y in range(height):
# % ensures that the number is always positive, doesn't change value of (x-1) unless negative
leftCoord = (x-1) % width
rightCoord = (x+1) % width
aboveCoord = (y-1) % height
belowCoord = (y+1) % height
numNeighbors = 0
if currentCells[leftCoord][aboveCoord] == '#':
numNeighbors += 1 # top-left neighbor is alive
if currentCells[x][aboveCoord] == '#':
numNeighbors += 1 # top neighbor is alive
if currentCells[rightCoord][aboveCoord] == '#':
numNeighbors += 1 # top-right neighbor is alive
if currentCells[leftCoord][y] == '#':
numNeighbors += 1 # left neighbor is alive
if currentCells[rightCoord][y] == '#':
numNeighbors += 1 # right neighbor is alive
if currentCells[leftCoord][belowCoord] == '#':
numNeighbors += 1 # bottom-left neighbor is alive
if currentCells[x][belowCoord] == '#':
numNeighbors += 1 # bottom neighbor is alive
if currentCells[rightCoord][belowCoord] == '#':
numNeighbors += 1 # bottom-right neighbor is alive
# set cell based on the rules
if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
# living cells with 2 or 3 neighbors stay alive
nextCells[x][y] = '#'
elif currentCells[x][y] == ' ' and numNeighbors == 3:
# dead cells with 3 neighbors become alive
nextCells[x][y] = '#'
else:
nextCells[x][y] = ' '
time.sleep(1)
|
c8cf540c6abccfc7c23e41cb6a86fb6685fd0ff8
|
GGolfz/100DaysOfPythonPro
|
/Day002/Ex2-2.py
| 122 | 4.125 | 4 |
height = float(input("Enter you height: "))
weight = float(input("Enter you weight: "))
print(int(weight/(height*height)))
|
f2b3b851cbc8170d6eb2a60b8996560b9c6ab9c0
|
ijuarezb/InterviewBit
|
/06_TreesDataStructure/kth_smallest_element_ina_tree.py
| 2,168 | 3.890625 | 4 |
#!/usr/bin/env python3
import sys
from BST import TreeNode
from BST import insertNode
from BST import inOrderTraversal
# Kth Smallest Element In Tree
# https://www.interviewbit.com/problems/kth-smallest-element-in-tree/
#
# Given a binary search tree, write a function to find the kth smallest element in the tree.
#
# Example :
#
# Input :
# 2
# / \
# 1 3
#
# and k = 2
#
# Return : 2
#
# As 2 is the second smallest element in the tree.
# NOTE : You may assume 1 <= k <= Total number of nodes in BST
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def _kthsmallest(self, A, i, B):
if not A:
return None
kthsmallest = self._kthsmallest(A.left, i, B)
if kthsmallest is None:
if i[0] == B:
return A.val
i[0] += 1
kthsmallest = self._kthsmallest(A.right, i, B)
return kthsmallest
# @param A : root node of tree
# @param B : integer
# @return an integer
def kthsmallest(self, A, B):
return self._kthsmallest(A, [1], B)
def _kthsmallestIJB(self, A, i, B):
if not A:
return None
kthsmallest = self._kthsmallestIJB(A.left, i, B)
if kthsmallest is None:
if i[0] == B:
return A.val
i[0] += 1
kthsmallest = self._kthsmallestIJB(A.right, i, B)
return kthsmallest
def kthsmallestIJB(self, A, B):
return self._kthsmallestIJB(A, [1], B)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if __name__ == '__main__':
# A = [11 2 9 13 57 25 17 1 90 3]; B = 5; Answer = 11
kth = int(sys.argv[1])
r = TreeNode(int(sys.argv[2]))
for arg in range(3, len(sys.argv), 1):
insertNode(r, TreeNode(int(sys.argv[arg])))
s = Solution()
print("The Kth:{} smallest element in tree is: {}".format(kth, s.kthsmallestIJB(r, kth)))
|
6b478f510d43c3eabcd26a623817002ba7033770
|
vjs7898/pythonProject1
|
/binarysearch.py
| 476 | 3.6875 | 4 |
pos = -1
def search(list,n):
l = 0
u = len(list) - 1
for i in range(l,u+1):
mid = (l + u)//2
if(list[mid]==n):
globals()['pos'] = mid
return True
else:
if(list[mid] < n):
l = mid + 1
else:
u = mid - 1
return False
lst= list(map(int,input().split(' ')))
n = int(input())
if (search(lst,n)):
print(n," is found at",pos)
else:
print(n," is not found")
|
95e57df785f2d508856e71be2143818a54621a5a
|
quitaiskiluisf/TI4F-2021-LogicaProgramacao
|
/atividades/avaliacao-02/a02_03.py
| 647 | 4.125 | 4 |
# Apresentação
print('Programa para calcular estatísticas dos números e um vetor')
print()
# Solicita os 18 valores
valores = list()
for i in range(18):
valores.append(float(input('Informe um número: ')))
# Calcula a média dos valores (somatório de todos os
# valores dividido pela quantidade de valores existentes)
media = sum(valores) / len(valores)
# Calcula a amplitude (diferença entre o maior valor e
# o menor valor existentes no vetor)
amplitude = max(valores) - min(valores)
# Apresenta os resultados
print()
print(f'A média dos valores informados é {media}')
print(f'A amplitude dos valores informados é {amplitude}')
|
10d81e4d4f9fdc9af33a2735b01bae7e7ea0d1fb
|
vickyrr24/guvi
|
/countstr.py
| 78 | 3.640625 | 4 |
st=input()
count=0
for i in st:
if(i!=" "):
count+=1
print(count)
|
04d959ec43ecf8efef397ff38e1d2147fa777f45
|
sediame/mad-libs
|
/mad-libs.py
| 519 | 3.625 | 4 |
import re
with open('data/template.txt') as f:
mylist = list(f)
text = mylist[0]
print('Enter an adjective:')
new1 = input()
print('Enter a noun:')
new2 = input()
print('Enter a verb:')
new3 = input()
print('Enter a noun:')
new4 = input()
text = re.sub("ADJECTIVE", new1, text, count=1)
text = re.sub("NOUN", new2, text, count=1)
text = re.sub("VERB", new3, text, count=1)
text = re.sub("NOUN", new4, text, count=1)
print(text)
f.close()
ff = open('data/result.txt', 'w')
ff.write('%s' % text)
ff.close()
|
c3c75d6f1644af5a1aff889442da7bd0a596bf37
|
MarioFried/Project03
|
/Dicionario.py
| 252 | 4.3125 | 4 |
"""
Pequeno Exemplo de Funcionamento da Estrutura Dicionario em Python
"""
Database={}
Database['Cliente']={1:'Mario',2:'Ana'}
Database['Leads']={1:'Manu',2:'David',3:'Marcelo'}
print(Database['Cliente'][1])
print(Database['Leads'][3])
print(Database)
|
4e5ea9dd3da0ab0360df0126ea35ff3ea4992981
|
SourabhKul/Adversarial-attacks-NN
|
/mnist-example-cnn.py
| 2,757 | 3.765625 | 4 |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# read in data
mnist = input_data.read_data_sets("", one_hot=True)
# define number of hidden layers and nodes per hidden layer
# define number of classes and batch size to avoid ram overload
n_classes = 10
batch_size = 128
# x is data, flattened out, so it will be a 1 x 784. it's well defined, so that the data of that shape is input and random data may not be pushed into the tf
x = tf.placeholder ('float',[None, 784])
# y is label
y = tf.placeholder ('float')
def conv2d(x,W):
return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')
def maxpool2d(x):
# size of window movement of window
return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
def convolutional_neural_network(x):
weights = {'W_conv1':tf.Variable(tf.random_normal([5,5,1,32])),
'W_conv2':tf.Variable(tf.random_normal([5,5,32,64])),
'W_fc':tf.Variable(tf.random_normal([7*7*64, 1024])),
'out':tf.Variable(tf.random_normal([1024,n_classes])),}
baises = {'b_conv1':tf.Variable(tf.random_normal([32])),
'b_conv2':tf.Variable(tf.random_normal([64])),
'b_fc':tf.Variable(tf.random_normal([1024])),
'out':tf.Variable(tf.random_normal([n_classes])),}
x = tf.reshape(x, shape=[-1,28,28,1])
conv1 = conv2d(x, weights['W_conv1'])
conv1 = maxpool2d(conv1)
conv2 = conv2d(conv1, weights['W_conv2'])
conv2 = maxpool2d(conv2)
fc = tf.reshape(conv2,[-1,7*7*64])
fc = tf.nn.relu(tf.matmul(fc, weights['W_fc'])+baises['b_fc'])
output = tf.matmul(fc, weights['out'])+ baises['out']
return(output)
def train_neural_network(x):
prediction = convolutional_neural_network(x)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))
optimizer = tf.train.AdamOptimizer().minimize(cost)
#number for cycles
hm_epochs = 20
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(hm_epochs):
epoch_loss = 0
for _ in range(int(mnist.train.num_examples/batch_size)):
epoch_x, epoch_y = mnist.train.next_batch(batch_size)
_, c = sess.run([optimizer, cost], feed_dict={x:epoch_x, y:epoch_y})
epoch_loss += c
print('Epoch', epoch, 'completed out of', hm_epochs, 'loss', epoch_loss)
correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct,'float'))
print('Accuracy', accuracy.eval({x:mnist.test.images, y:mnist.test.labels}))
train_neural_network(x)
|
f61fdc9801d3f28d22549709ffab4c6740b7e9c3
|
Srikesh89/PythonBootcamp
|
/Python Scripts/MilestoneProject2.py
| 8,215 | 3.765625 | 4 |
'''Blackjack Game: Player vs Dealer'''
import random
SUITS = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
RANKS = ('Two', 'Three', 'Four', 'Five', 'Six',
'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
VALUES = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7,
'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':1}
class Card():
'''Card class contains card suit, rank, value'''
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
self.value = VALUES[rank]
def __str__(self):
return f'{self.rank} of {self.suit}'
class Deck():
'''Deck class holds standard 52 card deck'''
def __init__(self):
self.all_cards = []
for suit in SUITS:
for rank in RANKS:
self.all_cards.append(Card(suit, rank))
def shuffle(self):
random.shuffle(self.all_cards)
def deal_card_from_deck(self):
return self.all_cards.pop()
class Dealer():
'''Dealer follows conventional Blackjack rules
to decide when to hit or stand'''
def __init__(self):
self.name = 'Dealer'
self.hand = []
def add_card_to_hand(self, new_card):
self.hand.append(new_card)
def get_deal(self):
'''Second card is dealt face down
on initial deal to dealer'''
return self.hand[0]
def get_hand(self):
return self.hand
def decide(self, num):
if num <= 16:
return 'hit'
return 'stand'
def clear_hand(self):
self.hand.clear()
class Player():
'''Player contains player methods especially for bankroll'''
def __init__(self, name, bankroll):
self.name = name
self.bankroll = int(bankroll)
self.hand = []
def add_card_to_hand(self, new_card):
self.hand.append(new_card)
def add_to_bankroll(self, gains):
self.bankroll += gains
def bet(self, amt):
self.bankroll -= amt
def get_hand(self):
return self.hand
def clear_hand(self):
self.hand.clear()
def show_hand(cards):
print('Cards are ', *cards, sep='.')
print(f'Value of cards is {calculate_hand(cards)}')
def calculate_hand(cards):
hand_value = 0
aces_count = 0
for card in cards:
if card.rank == 'Ace':
aces_count += 1
hand_value += card.value
if hand_value <= 11 and aces_count >= 1:
hand_value += 10
return hand_value
def is_busted(cards):
hand_value = 0
for card in cards:
hand_value += card.value
return hand_value > 21
def prompt_for_player_info():
name = input('Enter your name: ')
bankroll = input('Enter starting funds: ')
while not bankroll.isdigit:
print('Please enter valid number')
bankroll = input('Enter starting funds: ')
return name, int(bankroll)
def prompt_to_place_bet(player):
bet = input('Place a bet: ')
while not bet.isdigit or int(bet) > player.bankroll:
print('Please enter valid number less than or equal to bankroll')
bet = input('Place a bet: ')
player.bet(int(bet))
return int(bet)
def prompt_hit_or_stand(player):
decision = input(f'Hit or stand: ')
while decision.lower() not in ['hit', 'stand']:
print(f"Not a valid entry. Enter 'hit' or 'stand'.")
decision = input(f'Hit or stand: ')
return decision.lower()
def prompt_keep_playing():
decision = input(f'Keep playing? (Yes/No): ')
while decision.lower() not in ['yes', 'no']:
print(f"Not a valid entry. Enter 'Yes' or 'No'.")
decision = input(f'Keep playing? (Yes/No): ')
return decision.lower() == 'yes'
if __name__ == '__main__':
print('***** Blackjack ******')
p_name, bank = prompt_for_player_info()
player = Player(p_name, bank)
print(f'Hello {player.name}, you are starting with ${player.bankroll:0.2f} in chips')
print("Let's play!")
dealer = Dealer()
print('Shuffling cards...')
deck = Deck()
deck.shuffle()
keep_playing = True
while keep_playing:
#Place Bet
print(f'Player bankroll is ${player.bankroll:0.2f}')
bet = prompt_to_place_bet(player)
print(f'You are betting ${bet:0.2f}')
#Deal cards
print(f'Dealing cards...')
player.add_card_to_hand(deck.deal_card_from_deck())
dealer.add_card_to_hand(deck.deal_card_from_deck())
player.add_card_to_hand(deck.deal_card_from_deck())
dealer.add_card_to_hand(deck.deal_card_from_deck())
#Initial reveal of dealer hand
print(f'The dealer is showing', end=' ')
print(f'{dealer.get_deal()}')
is_player_busted = False
is_dealer_busted = False
while (not is_player_busted and not is_dealer_busted):
#The Play (Hit or Stand by player)
continue_to_deal = True
while continue_to_deal and not is_player_busted:
print(f'Player', end=' ')
show_hand(player.get_hand())
decision = prompt_hit_or_stand(player)
if decision == 'stand':
continue_to_deal = False
else:
player.add_card_to_hand(deck.deal_card_from_deck())
is_player_busted = is_busted(player.get_hand())
if is_player_busted:
print(f'Player', end=' ')
show_hand(player.get_hand())
print(f'Player is Bust!')
break
#The Dealer's Play (Hit or stand by dealer)
'''If the total is 17 or more, it must stand.
If the total is 16 or under, they must take a card.
The dealer must continue to take cards until the total is 17 or more,
at which point the dealer must stand. If the dealer has an ace,
and counting it as 11 would bring the total to 17 or more (but not over 21),
the dealer must count the ace as 11 and stand. '''
continue_to_deal = True
while continue_to_deal and not is_dealer_busted:
print(f'Dealer', end=' ')
show_hand(dealer.get_hand())
decision = dealer.decide(calculate_hand(dealer.get_hand()))
if decision == 'stand':
continue_to_deal = False
else:
dealer.add_card_to_hand(deck.deal_card_from_deck())
print(f'Dealer has hit')
is_dealer_busted = is_busted(dealer.get_hand())
if is_dealer_busted:
print(f'Dealer', end=' ')
show_hand(dealer.get_hand())
print(f'Dealer is Bust!')
break
if not continue_to_deal:
break
#Settlement
dealer_hand_total = calculate_hand(dealer.get_hand())
player_hand_total = calculate_hand(player.get_hand())
if is_player_busted:
print(f'Dealer wins ${bet:0.2f}')
elif is_dealer_busted and not is_player_busted:
bet *= 1.5
print(f'Player wins ${bet:0.2f}')
player.add_to_bankroll(bet)
elif dealer_hand_total > player_hand_total:
#player lost bet
print(f'Dealer wins ${bet:0.2f}')
elif dealer_hand_total < player_hand_total:
#player won bet
bet *= 1.5
print(f'Player wins ${bet:0.2f}')
player.add_to_bankroll(bet)
elif dealer_hand_total == player_hand_total:
#player drew
print(f'Draw. Player gets back {bet:0.2f}')
player.add_to_bankroll(bet)
#Ask to keep playing
keep_playing = prompt_keep_playing()
if keep_playing:
#reset deck and hands
deck = Deck()
deck.shuffle()
player.clear_hand()
dealer.clear_hand()
else:
print(f'You left with ${player.bankroll:0.2f}')
break
if player.bankroll < 1:
print(f'You have ${player.bankroll:0.2f}')
print(f'Insufficient funds. Get more chips.')
break
|
8e4c026eba08f044cb29bd848bb85950e70d7fc9
|
minhyeong-joe/coding-interview
|
/Array/ReverseInPlace.py
| 465 | 4.21875 | 4 |
'''
Given a list, reverse the order without using extra arrays.
'''
def reverse(arr):
left = 0
right = len(arr)-1
print(left, right)
while left < right:
arr[left] = arr[left] + arr[right]
arr[right] = arr[left] - arr[right]
arr[left] = arr[left] - arr[right]
left += 1
right -= 1
def main():
arr = [1, 2, 3, 4, 5]
print(arr)
reverse(arr)
print(arr)
if __name__=="__main__":
main()
|
6f8152facd772df3b6efdb19e022b82a36d379dc
|
pczubows/img-crypt
|
/img_crypt/imgcrypt.py
| 11,294 | 3.71875 | 4 |
"""Img Crypt
Script for testing different image encryption methods. It implements
traditional stream ciphers and an algorithm designed for image encryption
based on chaotic map lattices.
Chosen image is being encrypted and decrypted. When procedure finishes script
displays image before and after encryption, along with histograms of their respective
pixel values.
Usage is described in README.md
"""
import os
from argparse import ArgumentParser
from io import BytesIO
from urllib.request import urlopen, pathname2url, urlparse
from PIL import Image
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import numpy as np
import matplotlib.pyplot as plt
from multiproc_handler import MultiprocHandler
from cml import cml_encrypt, cml_decrypt
from exceptions import SchemeException, ImageLocatorException
def image_from_url(locator):
"""Load image from path or url
Parameters:
locator (str): Path to the image or url of an image hosted on the internet
Returns:
PIL.Image: Chosen image converted to the Pillow Image object
"""
if os.path.isfile(locator):
locator = 'file:' + pathname2url(locator)
else:
url_parsed = urlparse(locator)
if url_parsed.netloc == '':
raise ImageLocatorException(f'Wrong image locator {locator}, file does not exist or url is malformed')
with urlopen(locator) as f:
img_file = BytesIO(f.read())
im = Image.open(img_file)
if im.mode != 'RGB':
im = im.convert('RGB')
return im
def standard_encrypt(im, algorithm, mode):
"""Encrypt image using one the traditional stream ciphers
Parameters:
im (PIL.Image): Image to be encrypted loaded into Pillow Image object
algorithm : Cryptography object with stream cipher algorithm
mode: Cryptography object with encryption mode
Returns:
PIL.Image: Encrypted image object
"""
data = im.tobytes()
cipher = Cipher(algorithm, mode, backend=default_backend())
encryptor = cipher.encryptor()
padder = padding.PKCS7(algorithm.block_size).padder()
padded_data = padder.update(data) + padder.finalize()
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
return Image.frombytes('RGB', im.size, ciphertext)
def standard_decrypt(im, algorithm, mode):
"""Decrypt image using one the traditional stream ciphers
Parameters:
im (PIL.Image): Image to be encrypted loaded into Pillow Image object
algorithm : Cryptography object with stream cipher algorithm
mode: Cryptography object with encryption mode
Returns:
PIL.Image: Decrypted image object
"""
data = im.tobytes()
cipher = Cipher(algorithm, mode, backend=default_backend())
decryptor = cipher.decryptor()
padder = padding.PKCS7(algorithm.block_size).padder()
padded_ciphertext = padder.update(data) + padder.finalize()
plaintext = decryptor.update(padded_ciphertext) + decryptor.finalize()
return Image.frombytes('RGB', im.size, plaintext)
def encrypt_image(im, scheme, **kwargs):
"""Encrypt image with chosen scheme
Parameters:
locator (str): Path or url of chosen image
scheme (str): String specifying chosen encryption scheme
Keyword Arguments:
key (bytes | (float, bytes)): Encryption key, length and type depends on the chosen
algorithm
iv (bytes): Initialization vector for cbc encryption mode
iterations (int): number of iterations over single pixel for CML algorithm
cycles (int): number of cycles over whole image for cml algorithm
Returns:
PIL.Image: Encrypted image as Pillow Image object
"""
key = kwargs.get('key')
iv = kwargs.get('iv')
iterations = kwargs.get('iterations')
cycles = kwargs.get('cycles')
if scheme == '3DES_ECB':
enc_im = standard_encrypt(im, algorithms.TripleDES(key), modes.ECB())
elif scheme == '3DES_CBC':
enc_im = standard_encrypt(im, algorithms.TripleDES(key), modes.CBC(iv))
elif scheme == 'AES_ECB':
enc_im = standard_encrypt(im, algorithms.AES(key), modes.ECB())
elif scheme == 'AES_CBC':
enc_im = standard_encrypt(im, algorithms.AES(key), modes.CBC(iv))
elif scheme == 'CML':
enc_im = cml_encrypt(im, key, iterations=iterations, cycles=cycles)
elif scheme == 'CML_MULTI':
handler = MultiprocHandler()
enc_im = handler.multiproc_encrypt(im, key, iterations=iterations, cycles=cycles)
else:
raise SchemeException('Invalid encryption scheme')
return enc_im
def decrypt_image(im, scheme, **kwargs):
"""Decrypt image with chosen scheme
Parameters:
locator (str): Path or url of chosen image
scheme (str): String specifying chosen encryption scheme
Keyword Arguments:
key (bytes | (float, bytes)): Encryption key, length and type depends on the chosen
algorithm
iv (bytes): Initialization vector for cbc encryption mode
iterations (int): number of iterations over single pixel for CML algorithm
cycles (int): number of cycles over whole image for cml algorithm
Returns:
PIL.Image: Decrypted image as Pillow Image object
"""
key = kwargs.get('key')
iv = kwargs.get('iv')
iterations = kwargs.get('iterations')
cycles = kwargs.get('cycles')
if scheme == '3DES_ECB':
dec_im = standard_decrypt(im, algorithms.TripleDES(key), modes.ECB())
elif scheme == '3DES_CBC':
dec_im = standard_decrypt(im, algorithms.TripleDES(key), modes.CBC(iv))
elif scheme == 'AES_ECB':
dec_im = standard_decrypt(im, algorithms.AES(key), modes.ECB())
elif scheme == 'AES_CBC':
dec_im = standard_decrypt(im, algorithms.AES(key), modes.CBC(iv))
elif scheme == 'CML_MULTI':
handler = MultiprocHandler()
dec_im = handler.multiproc_decrypt(im, key, iterations=iterations, cycles=cycles)
elif scheme == 'CML':
dec_im = cml_decrypt(im, key, iterations=iterations, cycles=cycles)
else:
raise SchemeException('Invalid decryption scheme')
return dec_im
def encrypt_then_decrypt(locator, scheme, **kwargs):
"""Perform encryption and decryption consecutively
Parameters:
locator (str): Path or url of chosen image
scheme (str): String specifying chosen encryption scheme
Keyword Arguments:
key (bytes | (float, bytes)): Encryption key, length and type depends on the chosen
algorithm
iv (bytes): Initialization vector for cbc encryption mode
iterations (int): number of iterations over single pixel for CML algorithm
cycles (int): number of cycles over whole image for cml algorithm
Returns:
(PIL.Image, PIL.Image): Tuple containing decrypted image and encrypted image
"""
im = image_from_url(locator)
enc_im = None
dec_im = None
key = kwargs.get('key')
iv = kwargs.get('iv')
iterations = kwargs.get('iterations')
cycles = kwargs.get('cycles')
if scheme in ['3DES_ECB', 'AES_ECB', '3DES_CBC', 'AES_CBC']:
key = key if key is not None else os.urandom(16)
if scheme in ['3DES_ECB', 'AES_ECB']:
enc_im = encrypt_image(im, scheme, key=key)
dec_im = decrypt_image(enc_im, scheme, key=key)
else:
if scheme == '3DES_CBC':
iv = iv if iv is not None else os.urandom(8)
else:
iv = iv if iv is not None else os.urandom(16)
enc_im = encrypt_image(im, scheme, key=key, iv=iv)
dec_im = decrypt_image(enc_im, scheme, key=key, iv=iv)
elif scheme in ['CML', 'CML_MULTI']:
cml_default_cycles = 3
cml_default_iterations = 10
key = key if key is not None else 0.3, os.urandom(4)
cycles = cycles if cycles is not None else cml_default_cycles
iterations = iterations if iterations is not None else cml_default_iterations
enc_im = encrypt_image(im, scheme, key=key, iterations=iterations, cycles=cycles)
dec_im = decrypt_image(enc_im, scheme, key=key, iterations=iterations, cycles=cycles)
else:
raise SchemeException('Invalid encryption scheme')
return dec_im, enc_im
def plot_channels(dec_im, enc_im, scheme):
"""Draw histograms of the decrypted and encrypted image
Parameters:
dec_im (PIL.Image): Pillow Image object containing decrypted Image.
enc_im (PIL.Image): Pillow Image object containing encrypted Image
scheme (str): String specifying encryption scheme
"""
dec_pixels = np.array(dec_im)
enc_pixels = np.array(enc_im)
dec_channels = [dec_pixels[:, :, i].ravel() for i in range(3)]
enc_channels = [enc_pixels[:, :, i].ravel() for i in range(3)]
hist_kwargs = {'bins': 256, 'range': [0, 256], 'color': ['red', 'green', 'blue']}
fig, (hist_dec, hist_enc) = plt.subplots(nrows=1, ncols=2)
hist_dec.hist(dec_channels, **hist_kwargs)
hist_enc.hist(enc_channels, **hist_kwargs)
hist_dec.set_title('plain')
hist_enc.set_title(f"{scheme.replace('_', ' ').lower()} encrypted")
plt.show()
# example pictures for tests
example_urls = {
'obelix': "https://www.asterix.com/illus/asterix-de-a-a-z/les-personnages/perso/g28b.gif",
'matterhorn': "https://www.zermatt.ch/extension/portal-zermatt/var/storage/images/media/bibliothek/berge/matterhorn/sicht-aufs-matterhorn-vom-gornergrat/58955-3-ger-DE/Sicht-aufs-Matterhorn-vom-Gornergrat_grid_624x350.jpg",
'cat': "https://www.petmd.com/sites/default/files/what-does-it-mean-when-cat-wags-tail.jpg",
'balloon': "https://i.pinimg.com/originals/33/c8/b0/33c8b01484886f1b075ee2d1d7b9d12b.gif",
}
if __name__ == '__main__':
arg_parser = ArgumentParser()
arg_parser.add_argument('-s', '--scheme', type=str, default='3DES_CBC', help='specify encryption scheme'
'allowed schemes: 3DES_ECB, 3DES_CBC, AES_ECB, AES_CBC, CML, CML_MULTI')
arg_parser.add_argument('-l', '--locator', type=str, default=None,
help='specify image to be encrypted, can be path to the local'
'file or url of an image hosted on internet')
arg_parser.add_argument('-e', '--example', type=str, default=None,
help=f'Name of example picture to be fetched from internet'
f'Example names {example_urls.keys()}')
cl_args = arg_parser.parse_args()
scheme = cl_args.scheme.upper()
cli_locator = cl_args.locator
example = cl_args.example
if cli_locator is not None:
locator = cli_locator
elif example in example_urls.keys():
locator = example_urls[example]
else:
raise ImageLocatorException('No proper image locator specified, please use path to local file'
'or url of an image hosted on internet')
dec_im, enc_im = encrypt_then_decrypt(locator, scheme)
dec_im.show()
enc_im.show()
plot_channels(dec_im, enc_im, scheme)
|
edec7c17e0f732fd22fa3ce5f14402d9fbe24985
|
eulersformula/Lintcode-LeetCode
|
/Product_of_Array_Exclude_Itself.py
| 1,076 | 3.65625 | 4 |
# Lintcode 50//Easy
# Description
# Given an integers array A.
# Define B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]B[i]=A[0]∗...∗A[i−1]∗A[i+1]∗...∗A[n−1], calculate B WITHOUT divide operation.Out put B
# Example
# Example 1:
# Input:
# A = [1,2,3]
# Output:
# [6,3,2]
# Explanation:
# B[0] = A[1] * A[2] = 6; B[1] = A[0] * A[2] = 3; B[2] = A[0] * A[1] = 2
# Example 2:
# Input:
# A = [2,4,6]
# Output:
# [24,12,8]
# Explanation:
# B[0] = A[1] * A[2] = 24; B[1] = A[0] * A[2] = 12; B[2] = A[0] * A[1] = 8
from typing import (
List,
)
class Solution:
"""
@param nums: Given an integers array A
@return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
"""
def product_exclude_itself(self, nums: List[int]) -> List[int]:
# write your code here
res = [1] * len(nums)
for i in range(len(nums)-1):
res[i+1] *= res[i] * nums[i]
tmp = 1
for i in range(len(nums)-1, 0, -1):
tmp *= nums[i]
res[i-1] *= tmp
return res
|
1e7257295f1e7746e142863197627c0402cb8852
|
hazardg/CP1404-Practicals-GeraldoGenesius
|
/Practical 1/menu.py
| 337 | 4.0625 | 4 |
name = str(input("Enter name: "))
menu = """(H)ello
(G)oodbye
(Q)uit"""
print(menu)
choose_menu = str(input(">>> "))
while choose_menu != 'Q':
if choose_menu == 'H':
print("Hello ", name)
elif choose_menu == 'G':
print("Goodbye ", name)
print(menu)
choose_menu = str(input(">>> "))
|
e5ee8c64a2f764ce6484cf37a33e7a1ad2728182
|
bfonta/OutliersGAN
|
/src/letters.py
| 3,584 | 3.5625 | 4 |
from matplotlib import pyplot as plt
import numpy as np
class Letters():
def __init__(self, hsize, vsize):
"""
Creates the frame where a single letter will be drawn
"""
self.frame = np.zeros(shape=(hsize*vsize), dtype=float)
self.hsize = hsize
self.vsize = vsize
def _check_pixel(self, pixel):
if pixel < 0 or pixel > self.hsize*self.vsize:
raise ValueError('Pixel {} does not exist.'.format(pixel))
def _draw(self, begin, number, direction):
"""
Converts the specified number of pixels into white along the specified direction.
Directions: 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'
Returns the number of the pixel where it stopped drawing.
"""
wind_rose = {'n': -self.hsize, 'ne': -self.hsize+1, 'e': 1,
'se': self.hsize+1, 's': self.hsize, 'sw': self.hsize-1,
'w': -1, 'nw': -self.hsize-1}
if direction not in wind_rose.keys():
raise ValueError('Please insert a valid direction.')
pixel = begin
for i in range(number):
self._check_pixel(pixel)
self.frame[pixel] = 1.
if i!=number-1: pixel = pixel + wind_rose[direction]
return pixel
def reset(self):
self.frame[:] = 0.
def get_frame(self):
return np.reshape(self.frame, (self.hsize, self.vsize))
def save_as_fig(self, name):
self.fig = plt.figure(figsize=(6,6))
plt.axis('off')
plt.imshow(self.frame.reshape(self.hsize,self.vsize), cmap='Greys_r')
plt.savefig('figs/letter_{}.png'.format(name))
plt.close()
def draw_letter(self, letter):
letters = {'a', 'e', 'm', 'n'}
if letter not in letters:
raise ValuerError('The specified letter cannot be drawn.')
if letter == 'a':
pix_init = int(3*self.hsize / 2)
pixel = pix_init - 1
i=0
while (pixel-1)%self.hsize != 0: #left diagonal
pixel = self._draw(pixel, number=2, direction='sw')
pixel = self._draw(pixel, number=2, direction='s')
pixel = pix_init
while (pixel+2)%self.hsize != 0: #right diagonal
pixel = self._draw(pixel, number=2, direction='se')
pixel = self._draw(pixel, number=2, direction='s')
self._draw(begin=self.hsize*10 + 8, number=11, direction='e')
self._draw(begin=self.hsize*11 + 8, number=11, direction='e')
elif letter == 'e':
self._draw(begin=3 + 2*self.hsize, number=22, direction='e') #first horizontal bar
self._draw(begin=3 + 11*self.hsize, number=18, direction='e') #second horizontal bar
self._draw(begin=3 + 24*self.hsize, number=22, direction='e') #third horizontal bar
self._draw(begin=3 + 2*self.hsize, number=23, direction='s') #vertical bar
elif letter == 'm':
pixel = self._draw(begin=self.vsize*self.hsize - 3*self.hsize + 5, number=22, direction='n')
pixel = self._draw(begin=pixel, number=9, direction='se')
pixel = self._draw(begin=pixel, number=9, direction='ne')
pixel = self._draw(begin=pixel, number=22, direction='s')
elif letter == 'n':
pixel = self._draw(begin=self.vsize*self.hsize - 3*self.hsize + 3, number=22, direction='n')
pixel = self._draw(begin=pixel, number=22, direction='se')
pixel = self._draw(begin=pixel, number=22, direction='n')
|
7c94dfab1a10ebaa927b1da32dba7ba0e7e5abdd
|
juliafealves/advanced-algorithms-basic
|
/list-02/p3.py
| 898 | 3.9375 | 4 |
# -*- coding: utf-8 -*-
# Author: Júlia Fernandes Alves. <[email protected]>
# Handle: juliafealves
# Problem: B. Queries about less or equal elements
def binary_search(array, number, length):
i, j = 0, length
while i <= j:
middle = (i + j) / 2
if array[middle] > number:
if middle - 1 >= 0 and array[middle - 1] <= number:
return middle
j = middle - 1
else:
if middle + 1 < length and array[middle + 1] > number:
return middle + 1
i = middle + 1
sizes = map(int, raw_input().split())
a = map(int, raw_input().split())
b = map(int, raw_input().split())
a = sorted(a)
output = ''
for number in b:
if a[0] > number:
value = 0
elif a[-1] <= number:
value = sizes[0]
else:
value = binary_search(a, number, sizes[0])
output += str(value) + ' '
print output.strip()
|
4375db9c019e58b6947c4c6080b579ecf0ed9b1c
|
navinraman1996/Connected-Devices-Python_workspace
|
/apps/labs/common/SensorData.py
| 2,985 | 3.71875 | 4 |
'''
Created on Jan 24, 2019
@author: Navin Raman
'''
from datetime import datetime
import os
class SensorData(object):
'''
this class contains sensor data's and attributes
'''
timestamp = None
name = 'not set'
curVal = 0;
avgVal = 0;
minVal = 0;
maxVal = 30;
totVal = 0;
diffVal = 0;
sampleCount = 0;
#to store the updated data in the local SensorData
surpassed_values = list();
'''
Constructor to create object of SensorData Class
@param name: Sensor name
@param minVal: Minimum allowed value of the sensor
@param maxVal: Maximum allowed value of the sensor
'''
def __init__(self, name, minVal, maxVal):
'''
Constructor
'''
self.timestamp = str(datetime.now());
self.name = name;
self.maxVal = maxVal;
self.minVal = minVal;
'''
AddValue function is used to add value to previous total and calculate avg
@param newVal: new Sensor value
'''
def addValue(self, newVal):
self.sampleCount += 1
self.timeStamp = str(datetime.now())
self.curVal = newVal
self.totVal += newVal
if (self.curVal < self.minVal):
self.minVal = self.curVal
if (self.curVal > self.maxVal):
self.maxVal = self.curVal
if (self.totVal != 0 and self.sampleCount > 0):
self.avgVal = self.totVal / self.sampleCount
def getAvgValue(self):# returns the average value
return self.avgVal
def getMaxValue(self):# returns the maximum value
return self.maxVal
def getMinValue(self):# returns the minimum value
return self.minVal
def getValue(self):# returns the current value
return self.curVal
'''
ToString function returns object in human readable format
@return: Object in human readable customized format
'''
def __str__(self):
self.customStr = \
str(self.name + ':' + \
os.linesep + '\tTime: ' + self.timeStamp + \
os.linesep + '\tSample number: ' + str(self.sampleCount) + \
os.linesep + '\tCurrent Temperature value is: ' + str(self.curVal) + chr(176) +'C' + \
os.linesep + '\tAverage Temperature: ' + str(self.avgVal) + chr(176) +'C' + \
os.linesep + '\tMinimum Temperature: ' + str(self.minVal) + chr(176) +'C' + \
os.linesep + '\tMaximum Temperature: ' + str(self.maxVal) + chr(176) +'C' + \
os.linesep + '----------------------------------------------------------------\n')
return self.customStr
|
a81c59c1187145afc32852bf7d5db6c860953b89
|
ZukhriddinMirzajanov/Data-structures
|
/bstree.py
| 3,332 | 3.765625 | 4 |
import queue
class BSTree:
def __init__(self, data):
self.data = data
self.left_child = None
self.right_child = None
def insert(self, root_node, node_value):
if root_node.data is None:
root_node.data = node_value
elif node_value <= root_node.data:
if root_node.left_child is None:
root_node.left_child = BSTree(node_value)
else:
self.insert(root_node.left_child, node_value)
else:
if root_node.right_child is None:
root_node.right_child = BSTree(node_value)
else:
self.insert(root_node.right_child, node_value)
return 'Inserted'
def level_order(self, root_node):
if not root_node:
return 'BT is not exist'
else:
costom_queue = queue.Queue()
costom_queue.enqueue(root_node)
while not costom_queue.isEmpty():
root = costom_queue.dequeue()
print(root.value.data)
if root.value.left_child is not None:
costom_queue.enqueue(root.value.left_child)
if root.value.right_child is not None:
costom_queue.enqueue(root.value.right_child)
def search(self, root_node, node_value):
if root_node.data == node_value:
return 'Found'
elif node_value < root_node.data:
if root_node.left_child.data == node_value:
return 'Found'
else:
self.search(root_node.left_child, node_value)
else:
if root_node.right_child.data == node_value:
return 'Found'
else:
self.search(root_node.right_child, node_value)
def min_node_value(self, root_node):
node = root_node
while node.left_child is not None:
node = node.left_child
return node
def delete_node(self, root_node, node_value):
if root_node is None:
return root_node
if node_value < root_node.data:
root_node.left_child = self.delete_node(
root_node.left_child, node_value)
elif node_value > root_node.data:
root_node.right_child = self.delete_node(
root_node.right_child, node_value)
else:
if root_node.left_child is None:
temp = root_node.right_child
root_node = None
return temp
if root_node.right_child is None:
temp = root_node.left_child
root_node = None
return temp
temp = self.min_node_value(root_node.right_child)
root_node.data = temp.data
root_node.right_child = self.delete_node(
root_node.right_child, temp.data)
return root_node
def delete_bst(self, root_node):
root_node.data = None
root_node.left_child = None
root_node.right_child = None
return 'BST is deleted'
bstree = BSTree(None)
bstree.insert(bstree, 60)
bstree.insert(bstree, 90)
bstree.insert(bstree, 30)
bstree.delete_bst(bstree)
bstree.level_order(bstree)
|
6eae1f12227c23a47e0045c5a2b40ab7d70308bc
|
Toranian/hackerspace-control-panel
|
/src/file_finder.py
| 5,734 | 3.625 | 4 |
from pathlib import Path
from sys import platform
import os, re, time
class FindFile:
"""Returns a selected file."""
def __init__(self):
# Helpful variables and home directory
self.home_dir = str(Path.home())
self.working_dir = self.home_dir
os.chdir(self.working_dir)
self.select_file = ""
# Operating system dependant variables
if platform == "linux" or platform == "darwin":
self.slash = "/"
self.execute_file = "./"
self.clear = "clear"
else:
self.slash = "\\"
self.execute_file = "call"
self.clear = "cls"
def back(self, directory):
"""Go back one directory. Takes one parameter, change_directory
and takes off the CWD ending."""
self.directory = directory
self.directory = self.directory[::-1] # Inverts string
self.index = self.directory[1:].find(self.slash) + 1 # Finds "\" char and indexes it
self.directory = self.directory[self.index:] # Slices word without the ending
self.directory = self.directory[::-1] # Flips the string back
return self.directory # Returns the word
def help_func(self):
"""Displays some text that describes how to use the program.
Will also wait for user input before continuing with the program"""
print("""
1. Try typing the number of the file you want to open
2. Type (q)uit to close the program
3. Type (b)ack to revert to a previous directory
4. Type: select [num] to select a file for use. | Ex: select 7
""")
self.wait = input("""
Press enter to continue""")
def clean_files(self, d_files):
"""Removes all hidden files within a list."""
self.d_files = d_files
self.c_files = []
for f in self.d_files:
if str(f[0]) != ".":
self.c_files.append(f)
return self.c_files
def user_choice(self, message):
self.message = message
self.choice = ""
while len(self.choice) == 0:
self.choice = input("{} Y/n: ".format(self.message)).lower()
if self.choice == "y":
return True
elif self.choice == "n":
return False
def change_directory(self):
"""Changes the directory based on what the user wants."""
self.files = self.clean_files(os.listdir(self.working_dir)) # CWD of cleaned files
# Command input
self.command = ""
while len(self.command) == 0:
self.command = input("select: ").lower() # Command, lowercased to
self.command = self.command.replace(" ", "") # Replace all whitespace with nothing
if self.command== "quit" or self.command[0] == "q": quit() # Exit the program
if self.command == "help" or self.command[0] == "h": # Displays text that may be useful
self.help_func()
if self.command == "back" or self.command[0] == "b": # Revert to a previous directory
self.working_dir = self.back(self.working_dir)
if re.search(r"select\d+", self.command):
self.digits = re.search(r"\d+", self.command).group()
self.select_file = "{}{}{}".format(self.working_dir, self.slash, str(self.files[int(self.digits)]))
# Try to change the directory to a number
if self.command.isdigit():
self.file_name = str(self.files[int(self.command)])
# Run file if it is not a folder
if "." in self.file_name:
self.choice = self.user_choice("Would you like to run {}?".format(self.file_name))
if self.choice:
try:
os.system("{} {}".format(self.execute_file, self.file_name))
print("<File Executed>")
self.cont = input("\nPress enter to continue.")
return self.back(self.working_dir)
except: pass
else:
return self.working_dir
# Return the new directory
else:
return "{}{}{}".format(self.working_dir, self.slash, str(self.files[int(self.command)]))
try:
return self.working_dir
except:
return self.back(self.working_dir)
def list_files(self, file_list):
"""Lists all the files in a file variable in the list format"""
self.file_list = file_list
self.i = 0
for self.file in self.file_list:
if self.file[0] != ".":
print("{}| {}".format(self.i, self.file))
self.i += 1
def get_directory(self):
while True:
self.files = self.clean_files(os.listdir(self.working_dir)) # Files in that directory
os.system(self.clear) # Clear the terminal of last file list
self.list_files(self.files)
print("\nCmd: (b)ack, (h)elp, (q)uit")
print("cwd: ", self.working_dir,"\n")
# Current working directory
self.working_dir = self.change_directory()
if len(self.select_file) > 0:
print("Selected File: ", self.select_file); time.sleep(1)
return self.select_file
try:
os.chdir(self.working_dir)
except:
try:
os.chdir(self.back(self.working_dir))
except:
pass
help_func()
variable = FindFile()
variable.get_directory()
|
895dfb4c61759a34a3e5bd1b5f706e1f2d4afae4
|
leticiafelix/python-exercicios
|
/08 - Repetições (while)/desafio071.py
| 980 | 4.15625 | 4 |
#faça um programa que simula o funcionamento de um caixa eletrônico
#no inicio pergunte ao usuario qual o valor a ser sacado (inteiro)
#o programa informa quantas cédulas de cada valor serão entregues
#considere que o caixa possui cédulas de 20, 50, 10 e 1 real
print('--------------------------------')
print(' BANCO CEV ')
print('--------------------------------')
cedulas = 0
ced = 50
total = float(input('Valor do saque: R$'))
while True:
if total >= ced:
cedulas = total // ced #este operador é o floor division, retorna apenas a parte inteira da divisão
total -= cedulas*ced
else:
if cedulas > 0:
print(f'{cedulas:.0f} cédulas de R${ced:.2f}.')
if ced == 50:
ced = 20
elif ced == 20:
ced = 10
elif ced == 10:
ced = 1
cedulas = 0
if total == 0:
break
print('Volte sempre ao Banco CEV! Tenha um bom dia!')
|
cd2fc25b9b32d762b298e702edf4beecb474aad5
|
treesakul/LR-1-parser-generator
|
/Parser.py
| 1,571 | 3.671875 | 4 |
def parser(table, string):
stack = ['$',0]
input_string = string+'$'
input_index = 0
table = {0: {'c': ('s', 1), 'd': ('s', 2), 'S': ('s', 3), 'C': ('s', 4), "S'": ('', 'accept')}, 1: {'c': ('s', 1), 'd': ('s', 2), 'C': ('s', 5)}, 2: {'d': ('r', ('C', ('d',))), 'c': ('r', ('C', ('d',)))}, 3: {'$': ('r', ("S'", ('S',)))}, 4: {'c': ('s', 6), 'd': ('s', 7), 'C': ('s', 8)}, 5: {'d': ('r', ('C', ('c', 'C'))), 'c': ('r', ('C', ('c', 'C')))}, 6: {'c': ('s', 6), 'd': ('s', 7), 'C': ('s', 9)}, 7: {'$': ('r', ('C', ('d',)))}, 8: {'$': ('r', ('S', ('C', 'C')))}, 9: {'$': ('r', ('C', ('c', 'C')))}}
start_symbol = "S'"
while stack[-1] != 'accept':
print(stack)
current_state = stack[-1]
if input_string[input_index] not in table[current_state]:
# reject the string
print('reject')
break
action, goto = table[current_state][input_string[input_index]]
if action == 's':
stack.append(input_string[input_index])
stack.append(goto)
input_index += 1
elif action == 'r':
new_symbol, RHS = goto
for item in RHS:
stack.pop() # state number
stack.pop() # symbol
stack.append(new_symbol)
if new_symbol not in table[stack[-2]]:
# reject the string
print('reject')
break
_, goto = table[stack[-2]][new_symbol]
stack.append(goto)
if stack[-1] == 'accept':
print('accept')
|
4f61f3c44329b8b0294f074b88138a3fe6323b4d
|
poonampatil26/StudentAddressExceptionTask
|
/result.py
| 10,576 | 4.125 | 4 |
from ProjectTaskStudent import *
class InvalidInput(Exception):
def __init__(self,msg):
self.msg=msg
def len_pincode(pincode):
count=0
while pincode>0:
count+=1
pincode=pincode//10
return count
def add_pincode_check(pin):
if len_pincode(pin)>6 or len_pincode(pin)<6:
raise InvalidInput("Pincode should be 6 digits only")
else:
return pin
def check_pincode(pin):
if any(pin in s1 for s1 in Addresslist)==False:
raise InvalidInput("This city is not available please select Another pincode ")
else:
return pin
def check_marks(mark):
if mark > 100 or mark <= 0:
raise InvalidInput("Marks must not be less than zero or greater than 100")
else:
return mark
Addresslist=[]
studentlist=[]
while True:
ch=int(input("----select operation----"\
"\n1.Address"\
"\n2.Student"\
"\n3.Exit"\
"\nEnter your choice for operation : "))
if ch==1:
while True:
ch1=int(input("\n1.Create Address"\
"\n2.Update Address"\
"\n3.Delete Address"\
"\n4.Show Address"\
"\n5.Exit"\
"\nEnter your choice: "))
if ch1==1:
no_of_address=int(input("Enter no of cities u want to add : "))
for i in range(no_of_address):
citylist=[]
while True:
try:
pin=add_pincode_check(int(input(f"Enter pincode of city {i+1} : ")))
break
except (ValueError,InvalidInput) as e:
print(e)
city=input(f"Enter city {i+1} : ")
a1.set_city(city)
a1.set_pincode(pin)
citylist.append(a1.get_pincode())
citylist.append(a1.get_city())
print(citylist)
for i in Addresslist:
if citylist[0] in i:
print(citylist)
print("This pincode available already: ")
Addresslist.append(citylist)
elif ch1==2:
if len(Addresslist)==0:
print("No addresses Available ")
else:
while True:
try:
pin=check_pincode(int(input("Enter pincode u want to change: ")))
print(pin)
break
except (InvalidInput) as e:
print(e)
for i in Addresslist:
if i[0]==pin:
new_city=input("Enter new city name: ")
i[1]=new_city
print(Addresslist)
elif ch1==3:
while True:
try:
pin=check_pincode(int(input("Enter pincode: ")))
print(pin)
break
except (InvalidInput) as e:
print(e)
for i in Addresslist:
if i[0]==pin:
Addresslist.remove(i)
elif ch1==4:
for i in Addresslist:
print(i)
elif ch1==5:
break
else:
print("\n Wrong choice")
elif ch==2:
while True:
ch1=int(input("1.Create Student"\
"\n2.Update Student"\
"\n3.Delete Student"\
"\n4.Show Student"\
"\n5.Show student by descending marks "\
"\n6.Exit"\
"\nEnter your choice: "))
if ch1==1:
if len(Addresslist)==0:
citylist=[]
print("No cities available please add city first")
pin=add_pincode_check(int(input("Enter pincode of city : ")))
city=input("Enter city : ")
a1.set_city(city)
a1.set_pincode(pin)
citylist.append(a1.get_pincode())
citylist.append(a1.get_city())
Addresslist.append(citylist)
print(f"\n{a1.get_pincode()} {a1.get_city()} added successfully")
no_of_students=int(input("Enter no of student u want to add: "))
for i in range(no_of_students):
students=[]
rn=int(input("Enter Roll no: "))
name=input("Enter Name: ")
while True:
try:
mark=check_marks(int(input("Enter Marks: ")))
break
except InvalidInput as e:
print(e)
while True:
try:
address=check_pincode(int(input("Enter pincode: ")))
break
except (InvalidInput) as e:
print(e)
s1.set_rn(rn)
s1.set_name(name)
s1.set_marks(mark)
if any(address in s1 for s1 in Addresslist)==True:
for subarray in Addresslist:
if address in subarray:
position=Addresslist.index(subarray)
s1.set_address(Addresslist[Addresslist.index(subarray)])
print(s1.get_address())
students.append(s1.get_rn())
students.append(s1.get_name())
students.append(s1.get_marks())
students.extend(s1.get_address())
studentlist.append(students)
print(studentlist)
elif ch1==2:
if len(studentlist)==0:
print("No students Available ")
else:
rn=int(input("Enter roll no u want to update the data: "))
for i in studentlist:
if i[0]==rn:
print(f"\nCurrently Avaialble information of roll no {rn}","\n",i)
while True:
ch2=int(input("----select operation for student info update----"\
"\n1.change name"\
"\n2.change marks"\
"\n3.change address"\
"\n4.Exit"\
"\nEnter your choice for operation : "))
if ch2==1:
new_name=input("Enter New name: ")
for i in studentlist:
if i[0]==rn:
i[1]=new_name
elif ch2==2:
new_mark=int(input("Enter New marks: "))
for i in studentlist:
if i[0]==rn:
i[2]=new_mark
elif ch2==3:
print("Currently available cities")
for i in Addresslist:
print(i)
while True:
try:
new_address=check_pincode(int(input("Select pincode form Currently available cities for changing address: ")))
break
except (InvalidInput) as e:
print(e)
for subarray in Addresslist:
if new_address in subarray:
position=Addresslist.index(subarray)
for i in studentlist:
if i[0]==rn:
add_new_address=Addresslist[position]
print(add_new_address)
i.pop()
i.pop()
i.extend([add_new_address])
elif ch2==4:
break
else:
print("Wrong Choice")
elif ch1==3:
if len(studentlist)==0:
print("No students Available ")
else:
rn=int(input("\nEnter Roll no u want to Delete : "))
for i in studentlist:
if i[0]==rn:
studentlist.remove(i)
print(f"Deleted Successfully roll no {rn}")
elif ch1==4:
if len(studentlist)==0:
print("No students Available ")
else:
for i in studentlist:
print(i)
elif ch1==5:
marks_list=[]
for i in studentlist:
marks_list.append(i[2])
new_list=sorted(marks_list)
print(new_list)
for i in reversed(new_list):
for j in studentlist:
if i==j[2]:
print(j)
elif ch1==6:
break
else:
print("\n Wrong choice")
|
211cb57a1bd7157355a378fa8cc330e49e0b298e
|
sforrester23/Veterinary_Class_Project
|
/Pet_Class.py
| 332 | 3.84375 | 4 |
# Define a Pet class
class Pet():
def __init__(self, name, owner, breed, animal='Dog'):
self.name = name
self.owner = owner
self.breed = breed
self.animal = animal
def get_pet_info(self):
return '{} is a {} {} owned by {}.'.format(self.name, self.breed, self.animal, self.owner.name)
|
bdd0227f6cac5ef35ebfe81ad7c0d0fdf02f476f
|
filozyu/leetcode-journey
|
/src/string/group_anagrams.py
| 1,661 | 3.75 | 4 |
from collections import defaultdict, Counter
def groupAnagrams(strs):
"""
Hacking (slow)
Time: O(nk), n: length of strs; k: max length of words;
Space: O(nk), same as strs
"""
res_dict = defaultdict(list)
for word in strs:
key = frozenset(Counter(word).items())
res_dict[key].append(word)
return res_dict.values()
def groupAnagrams_sorted_str(strs):
"""
Sorted string (fast)
Time: O(nklogk), n: length of strs; k: max length of words; klogk for sorting
Space: O(nk), same as strs
"""
res_dict = defaultdict(list)
for word in strs:
# list is unhashable
res_dict[tuple(sorted(word))].append(word)
return res_dict.values()
def groupAnagrams_count(strs):
"""
Counting letters
Time: O(nk), n: length of strs; k: max length of words
Space: O(nk), same as strs
"""
res_dict = defaultdict(list)
for word in strs:
# count for each letter in alphabet
count = [0] * 26
for char in word:
# ord() return the Unicode integer representing the character
# therefore ord("b") - ord("a") = 1
# ord("z") - ord("a") = 25 etc.
count[ord(char) - ord("a")] += 1
res_dict[tuple(count)] = word
return res_dict.values()
test = [
"hos","boo","nay","deb","wow","bop","bob","brr","hey","rye",
"eve","elf","pup","bum","iva","lyx","yap","ugh","hem","rod",
"aha","nam","gap","yea","doc","pen","job","dis","max","oho",
"jed","lye","ram","pup","qua","ugh","mir","nap","deb","hog",
"let","gym","bye","lon","aft","eel","sol","jab"
]
print(groupAnagrams(test))
|
4afd4b26dac5707bc319d251608cb13cee76b57b
|
suyalmukesh/python
|
/warmup/CeasarCipher.py
| 1,042 | 3.59375 | 4 |
class CeasarCipher:
def __init__(self,shift):
encoder = [None] * 26
decoder = [None] * 26
for k in range(26):
encoder[k] = chr((k+shift)%26 + ord('A'))
decoder[k] = chr((k-shift))%26 + ord('A')
self._forward = ''.join(encoder)
self._backward = ''.join(decoder)
def encrypt(self,message):
return self._transform(message,self._forward)
def decrypt(self,secret):
return self._transform(secret,self._backward)
def _transform(self,original,code):
msg = list(original)
for k in range(len(msg)):
if msg[k].isupper():
j = ord(msg[k])-ord('A')
msg[k] = code[j] # replace this character
return ''.join(msg)
if __name__ == '__main__':
cipher = CeasarCipher(3)
message = "THE EAGLE IS IN THE PLAY:MEET AT JOE'S."
coded = cipher.encrypt(message)
print('Secret: ',coded)
answer = cipher.decrypt(coded)
print('Message',answer)
|
44a0963016dfbfa13263a78eb03d5df256cf166e
|
sandi0805/vba_challenge
|
/Minis/house_of_pies_bonus Sandra Hall.py
| 698 | 3.8125 | 4 |
pie_purchases = [0,0,0,0,0,0,0,0,0,0]
print("Welcome to the House of Pies! Here are our pies:")
pies = ["Pecan", "Apple Crisp", "Bean", "Banoffee", "Black Bun", "Blueberry", "Buko", "Burek", "Tamale", "Steak"]
print(pies)
pie_cart = []
x = input("Which pie would you like to try? Choose 0-9. ")
print(f"Great! We will have your {x} right out for you!")
pies.count(x)
print(f"Thank you for purchasing {x} pies today!")
pie_purchases[int(x)-1] = pie_purchases[int(x)-1] +1
shopping=input("Would you like to make another purchase? Y or N ")
Print = ("You purchased: ")
for pie_index in range(len(pies)):
print(str(pie_purchases[pie_index])+" " + str(pies[pie_index]))
|
e22612d5f4536b688b0c04d0633c97e5e4431db1
|
zingzheng/LeetCode_py
|
/242Valid Anagram.py
| 591 | 3.859375 | 4 |
##Valid Anagram
##Given two strings s and t,write a function to determine if t is an anagram of s.
##
##2015年8月23日 19:17:58 AC
##zss
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dic={}
for c in s:
if c not in dic:
dic[c]=0
dic[c]+=1
for c in t:
if c not in dic or dic[c]==0:
return False
dic[c]-=1
for n in dic.values():
if n >0:return False
return True
|
12af2884232a70d1cbe2a1b938d64e42d74d8378
|
Andrew940/robot-europa
|
/catkin_ws/src/local_mapper/nodes/numpy_extra.py
| 870 | 3.921875 | 4 |
#!/usr/bin/env python3
"""
Extra functions that should probably have been features of numpy.
"""
import numpy as np
def shift_2d_replace(data, dx, dy, constant=False):
"""
Shifts the array in two dimensions while setting rolled values to constant
:param data: The 2d numpy array to be shifted
:param dx: The shift in x
:param dy: The shift in y
:param constant: The constant to replace rolled values with
:return: The shifted array with "constant" where roll occurs
"""
shifted_data = np.roll(data, dx, axis=1)
if dx < 0:
shifted_data[:, dx:] = constant
elif dx > 0:
shifted_data[:, 0:np.abs(dx)] = constant
shifted_data = np.roll(shifted_data, dy, axis=0)
if dy < 0:
shifted_data[dy:, :] = constant
elif dy > 0:
shifted_data[0:np.abs(dy), :] = constant
return shifted_data
|
96a1eb2b4d5a3d855366915d7e1732471a29a6e1
|
sancharibasak/tusk
|
/List1.py
| 1,153 | 3.53125 | 4 |
#list of states in India
#Mutable Objects - Lists:
listA = [2.3, 4, 67, 12.8, "Python", True]
for i in range(len(listA)):
print(listA[i], end=' ')
print()
for i in range(-1, -len(listA)-1, -1):
print(listA[i], end=' ')
print()
tupA = tuple(listA)
print(tupA)
#List Comprehension:
listB = [x for x in range(10)]
print(listB)
listC = []
for x in range(10):
listC.append(x)
print(listC)
listD = [x*2 for x in range(5)] #0,1,2,3,4
print(listD)
listE = [1/x for x in range(2,10)] #2,3,....9
print(listE)
listF = [x/4 for x in listB]
print(listF)
listG = [x for x in listF if 0.5 <= x <= 1.25]
print((listG))
listH = []
for x in listF:
if (0.5 <= x <= 1.25):
listH.append(x)
print(listH)
#Using Nested Loop
# x=2, y= 1,2,3 3,4,5
# X = 3, y= 1,2,3 4,5,6
# x = 4, y =1,2,3 5,6,7
listI = []
for x in range(2,5):
for y in range(1,4):
listI.append((x+y))
print(listI)
listJ = [x+y for x in range(2,5) for y in range(1,4)]
print(listJ)
a = ['a', 'b', 'c']
b = ['x', 'y', 'z']
listK = [i + j for i in a for j in b]
print(listK)
listL = []
for i in a:
for j in b:
listl.append(i+j)
print(listL)
|
6c76f871c1bb8bcb4903865c00ba3e6e313a569f
|
JessiMcKissick/RPyG
|
/Learn it/step_7.py
| 4,365 | 3.71875 | 4 |
import os # Allows you to utilize OS functions.
import random # Allows you to utilize math randomization and the likes.
import time # Allows access to time. This will mostly be used for delays.
import platform # We'll use this to find the current devices platform.
version = "0.0"
lb = "-----------------------------------------------------------------------------"
def lbl():
print(lb)
def br():
print(" ")
def clear_screen():
if platform.system() == "Windows":
os.system("cls")
else:
os.system("clear")
def intro():
clear_screen()
print("Welcome to RPyG version " + version + "!")
lbl()
print("In this text based game, your goal is to survive as many consecutive battles in a row as possible.")
print("In the next step, you will create your character by selecting your class, a specialty, and name your character.")
lbl()
print("Keep in mind: This game is meant to be played in single sittings and as such you cannot save.")
lbl()
input("Press enter to continue...")
print("NOTE")
def app_start():
clear_screen()
lbl()
print("First, let's pick a class.")
print("1. warrior. Balance between attack rating and defense rating. Good health.")
print("2. wizard. A strong magical class with insane power but terrible defenses.")
print("3. falanx. A heavily armored defender class with massive defense but mediocre offense.")
class_input = input("Class choice: ")
lbl()
if class_input == "warrior" or class_input == "wizard" or class_input == "falanx" or class_input == "1" or class_input == "2" or class_input == "3":
print("Welcome, mighty " + class_input + "!")
class_stats(class_input)
elif class_input == "exit":
exit()
clear_screen()
else:
print("Please type one of the following: warrior, wizard, falanx.")
app_start()
strength = 0
defense = 0
health = 0
current_health = 0
specialty = 0
name = "null"
enemy_strength = 0
enemy_defense = 0
enemy_health = 0
enemy_current_health = 0
enemy_name = "null"
victory_count = 0
def class_stats(class_choice):
global current_health, health, strength, defense
print("Note: stats are randomly generated based on your class choice.")
print(lb)
if class_choice == "warrior" or class_choice == "1":
strength = random.randint(2, 5)
defense = random.randint(2, 5)
health = random.randint(20, 30)
current_health = health
print("You, fine warrior have: " + str(strength) + " attack. " +
str(defense) + " defense. " + str(health) + " health.")
elif class_choice == "wizard" or class_choice == "2":
strength = random.randint(5, 15)
defense = random.randint(0, 3)
health = random.randint(5, 20)
current_health = health
print("You, fine warrior have: " + str(strength) + " attack. " +
str(defense) + " defense. " + str(health) + " health.")
elif class_choice == "falanx" or class_choice == "3":
strength = random.randint(1, 5)
defense = random.randint(5, 15)
health = random.randint(1, 40)
current_health = health
print("You, fine warrior have: " + str(strength) + " attack. " +
str(defense) + " defense. " + str(health) + " health.")
special_select()
def special_select():
global specialty, health, strength, defense
clear_screen()
lbl()
print("Next, let's select a specialty.")
lbl()
print("1. medical knowledge. Add 5 to health")
print("2. berserker. Add 4 to attack")
print("3. technical. Permanently gain 4 extra defense")
lbl()
special_input = input("Specialty: ")
lbl()
if special_input == "1":
specialty = 1
health += 5
####
elif special_input == "2":
specialty = 2
strength += 4
####
elif special_input == "3":
specialty = 3
defense += 4
####
elif special_select == "exit":
exit()
else:
clear_screen()
print("please select a specialty by typing the number of the specialty.")
special_select()
def name_select():
global name
clear_screen()
print("Alright. What is your name fair adventurer?")
name = input("Name: ")
game_start() # This will be used later.
|
3e0f29145531b9b66f4be2c011c6ea098114b0f5
|
wayneshun/LPTHW
|
/spider/列表.py
| 403 | 3.71875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 04 00:09:32 2014
@author: shunxu
"""
def swap(lst,a,b):
c = lst[a]
lst[a] = lst[b]
lst[b] = c
def shift_left(lst):
tmp = lst[0]
for i in range(len(lst)-1):
lst[i] = lst[i+1]
lst[-1] = tmp
x = [10,20,30]
shift_left(x)
#print x
def f(l):
l[1] = [5]
return l
a = [1, 2, 3]
f(a)
print a[1]
|
8df8c2eeb973eccca47bfa41f1c7c628f60079e6
|
aerosayan/Learning-Machine-Learning
|
/src/01_soup_sale.py
| 1,446 | 4.125 | 4 |
# LANG : Python 2.7
# FILE : 01_soup_sale.py
# AUTH : Sayan Bhattacharjee
# EMAIL: [email protected]
# DATE : 2/JULY/2018
# INFO : How does hot soup sale change in winter based on temperature?
# : Here, we do linear regression with ordinary least squares
import numpy as np
import matplotlib.pyplot as plt
n = 100 # no. of data points
temp = np.linspace(3, 30, n) # temperature (deg C)
noise = np.random.randint(-5,7,size = n) # noise to simulate RL
soup = np.linspace(40, 22 , n, dtype = 'int') + noise # soup sale count
# We are re-assigning the data since we like to write in this form
x = temp # x co-ordinate
y = soup # y co-ordinate
x_bar = sum(x)/float(n) # average of x
y_bar = sum(y)/float(n) # average of y
m = sum((x-x_bar)*(y-y_bar))/ float(sum((x-x_bar)**2) ) # slope
b = y_bar - m*x_bar # y intercept
print("The linear regression has resulted in ...")
print("m(slope) : ",m )
print("b(y intercept) : ",b )
plt.scatter(x,y)
plt.plot(x,m*x + b,'-r')
plt.title("Temperature vs Soup Sale \n (linear regression with ordinary least squares)")
plt.xlabel("Temp in degree Celcius")
plt.ylabel("Hot soup bowls sold")
plt.grid()
plt.show()
|
cf7ae57d863e390eb9f4170c0d27cb26c87d38de
|
saurabhkawli/PythonHackerRankCodes
|
/TestSmartNumber.py
| 612 | 3.921875 | 4 |
import math
num = 1
val = int(math.sqrt(num))
print("num: ",num," Val: ",val)
print("Num/val",num/val)
print("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG")
num = 2
val = int(math.sqrt(num))
print("num: ",num," Val: ",val)
print("Num/val",num/val)
print("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG")
num = 7
val = int(math.sqrt(num))
print("num: ",num," Val: ",val)
print("Num/val",num/val)
print("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG")
num = 169
val = int(math.sqrt(num))
print("num: ",num," Val: ",val)
print("Num/val",num/val)
|
3801624e79f5e49f1a36f382afc8237a485aa126
|
Osmel1999/holbertonschool-higher_level_programming
|
/0x0B-python-input_output/10-class_to_json.py
| 388 | 3.625 | 4 |
#!/usr/bin/python3
"""Module 10-class_to_json.
Returns the dictionary description with
simple data structure (list, dictionary,
string, integer and boolean)
for JSON serialization of an object.
"""
def class_to_json(obj):
"""Creates a dict description of obj.
Args:
- obj: object to serialize
Returns: dictionnary description of obj
"""
return obj.__dict__
|
f742a6010866badbb9f77203c6f6b4e69cd6c56f
|
Prabhjyot2/workshop-python
|
/L3/p4.py
| 196 | 3.765625 | 4 |
# wapp to generate
num = int(input("enter the number "))
if num < 0:
print("b +ve")
else:
n = 0
for i in range(1 , num+1):
for j in range(1, i+1):
print(n, end="")
n = n + 1
print()
|
66620ac288f4f441fd7d34ef92a70c7a62248fbc
|
DavidGrice/CSC-241-Doubly-Link-List-Hanoi
|
/Delimiter_Check.py
| 1,645 | 4.5625 | 5 |
# for sys.argv, the command-line arguments
import sys
from Stack import Stack
# def delimiter_check(filename):
# Sets a constructor equal to the stack
# Has a set to check against the delimiters and creates a variable
# to open the file
# From here it goes through the file and if the characters match
# then they are popped off until the length is 0 returning True
# Otherwise it returns False
# It then closes the file (always good practice).
def delimiter_check(filename):
stackInput = Stack()
characterMap = {"]" : "[", "}" : "{", ")" : "("}
fileToOpen = open(filename)
for char in (fileToOpen):
if (char == '(' or char == '[' or char == '{'):
stackInput.push(char)
elif (char == ')' or char == ']' or char == '}'):
if characterMap[char] == stackInput.peek():
stackInput.pop()
else:
return False
if (len(stackInput) == 0):
return True
fileToOpen.close()
if __name__ == '__main__':
# The list sys.argv contains everything the user typed on the command
# line after the word python. For example, if the user types
# python Delimiter_Check.py file_to_check.py
# then printing the contents of sys.argv shows
# ['Delimiter_Check.py', 'file_to_check.py']
if len(sys.argv) < 2:
# This means the user did not provide the filename to check.
# Show the correct usage.
print('Usage: python Delimiter_Check.py file_to_check.py')
else:
if delimiter_check(sys.argv[1]):
print('The file contains balanced delimiters.')
else:
print('The file contains IMBALANCED DELIMITERS.')
|
228daf2ad0aa547a911030c45b6dacedff295ede
|
bliack-swan/my_github
|
/fast_sort.py
| 792 | 3.953125 | 4 |
def the_biggest_el ( arg ) :
if len ( arg ) <= 1 :
return arg [ 0 ] if len ( arg ) != 0 else None
elif len ( arg ) == 2 :
return arg [ 0 ] if arg [ 0 ] > arg [ 1 ] else arg [ 1 ]
else :
max_value = the_biggest_el ( arg [ 1 : ] )
return arg [ 0 ] if arg [ 0 ] > max_value else max_value
def qsort ( array ) :
if len ( array ) < 2 :
return array
else :
high = len ( array )
mid = (high) // 2
base_el = array [ mid ]
less = [ i for i in array if i < base_el ]
greater = [ i for i in array if i > base_el ]
return qsort ( less ) + [ base_el ] + qsort ( greater )
a = qsort ( [ 2 , 1 , 4 , 25 , 6 , 3547 , 6444 , 345 , 732345 , 831 , 346788 , 2 ] )
print ( a )
|
5ea80dafde3893cf542d99360decf7c36969dc8f
|
sunnyhyo/big_data
|
/Python/064 oop.py
| 595 | 4.3125 | 4 |
student = {'name': '홍길동', 'year': 2,'class':3, 'student_id':35}
print( '{}, {}학년 {}반 {}번'.format(student['name'], student['year'], student['class'], student['student_id']))
class student(object):
def __init__(self,name, year, class_num, student_id):
self.name=name
self.year=year
self.class_num=class_num
self.student_id=student_id
def introduce_myself(self):
return ('{}, {}학년 {}반 {}번'.format(self.name, self.year, self.class_num, self.student_id))
student=student('홀길동',2,3,36)
print(student.introduce_myself())
|
906fb5e0f1fcc8267e63f178e984bdbde5d55509
|
JackRyannn/LeetCode
|
/24.py
| 929 | 3.71875 | 4 |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
first = head
if not first:
return head
second = head.next
if not second:
return head
ret = second
h = ListNode(0)
while second:
first.next = second.next
second.next = first
h.next = second
h = first
if first.next:
first = first.next
second = first.next
else:
break
return ret
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n4 = ListNode(4)
n1.next = n2
n2.next = n3
n3.next = n4
h = Solution().swapPairs(n4)
while h:
print(h.val)
h = h.next
|
55dbef2eeb6d1fab43281a44f8c99366b3bbafca
|
yagnyasridhar/Python
|
/Training/Flask/EmployeeManagement/DBLoadJob.py
| 3,711 | 3.828125 | 4 |
import sqlite3
from sqlite3 import Error
import Employee
def sql_connection():
try:
con = sqlite3.connect('Employee.db')
return con
except Error:
print(Error)
def sql_table(con):
try:
cursorObj = con.cursor()
cursorObj.execute("CREATE TABLE employees(id integer PRIMARY KEY, name text, salary integer, department text, position text, hireDate text)")
con.commit()
except Error:
print(Error)
finally:
con.close()
def sql_SelectAll(con):
rows = None
try:
cursorObj = con.cursor()
cursorObj.execute('Select * from employees')
rows = cursorObj.fetchall()
con.commit()
cursorObj.close()
except Error:
print(Error)
finally:
con.close()
return rows
def sql_SelectByName(con, name):
rows = None
try:
cursorObj = con.cursor()
stmt = ("Select * from employees where name in ('{0}')").format(name)
print(stmt)
cursorObj.execute(stmt)
rows = cursorObj.fetchall()
con.commit()
cursorObj.close()
except Error:
print(Error)
finally:
con.close()
return rows
def sql_insert(con, entities):
try:
cursorObj = con.cursor()
cursorObj.execute('INSERT INTO employees(id, name, salary, department, position, hireDate) VALUES(?, ?, ?, ?, ?, ?)', entities)
con.commit()
cursorObj.close()
except Error:
print(Error)
finally:
con.close()
def sql_Insert(con, emp):
try:
cursorObj = con.cursor()
cursorObj.execute('INSERT INTO employees(id, name, salary, department, position, hireDate) VALUES(?, ?, ?, ?, ?, ?)', emp)
con.commit()
cursorObj.close()
except Error:
print(Error)
finally:
con.close()
def sql_bulkInsert(con, empLst):
try:
cursorObj = con.cursor()
#print(empLst)
cursorObj.executemany("INSERT INTO employees VALUES(?, ?, ?, ?, ?, ?)", empLst)
con.commit()
cursorObj.close()
except Error:
print(Error.__class__)
finally:
con.close()
def sql_update(con, empl):
try:
cursorObj = con.cursor()
stmt = ("UPDATE employees SET name = '{1}', salary = {2}, department = '{3}', position = '{4}', hireDate = '{5}' where id = {0}").format(empl[0], empl[1], empl[2], empl[3], empl[4], empl[5])
#print(stmt)
cursorObj.execute(stmt)
con.commit()
cursorObj.close()
except Error:
print(Error)
finally:
con.close()
def sql_bulkUpdate(con, emplst):
try:
cursorObj = con.cursor()
for empl in emplst:
stmt = ("UPDATE employees SET name = '{1}', salary = {2}, department = '{3}', position = '{4}', hireDate = '{5}' where id = {0}").format(empl[0], empl[1], empl[2], empl[3], empl[4], empl[5])
print(stmt)
cursorObj.execute(stmt)
con.commit()
cursorObj.close()
except Error:
print(Error)
finally:
con.close()
def sql_delete(con,id):
try:
cursorObj = con.cursor()
stmt = ("DELETE from employees where id={0}").format(id)
#print(stmt)
cursorObj.execute(stmt)
con.commit()
cursorObj.close()
except Error:
print(Error)
finally:
con.close()
#con = sql_connection()
#sql_table(con)
#entities = (2, 'Sridhar', 2800000, 'IT', 'Tech', '2021-07-01')
#sql_insert(con, entities)
|
4f6c06632daaa4851676644db6036a32fd594c04
|
julian59189/ThePythonMegaCourse
|
/script3.py
| 582 | 4.0625 | 4 |
import random, string
vowels='aeiouy'
consonants='bcdfghjklmnpqrstvwxz'
letters=vowels+consonants
letter_input_1=input("What letter do you want? Enter 'v' for vowels, 'c' for consonants, 'l' for any letter: ")
letter_input_2=input("What letter do you want? Enter 'v' for vowels, 'c' for consonants, 'l' for any letter: ")
letter_input_3=input("What letter do you want? Enter 'v' for vowels, 'c' for consonants, 'l' for any letter: ")
def plot():
if letter_input_1 == 'v':
l1=random.choice(vowels)
elif letter_input_1 == 'c':
l1=random.choice(consonants)
|
726e0ec2151c342a3325ee4614793eae278cd2fe
|
LucyHsu/training1
|
/perfect_number.py
| 494 | 3.765625 | 4 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
def perfect_number_check(test_num):
listtwo = [ i for i in range(1,(test_num/2)+1) if test_num % i ==0 ]
# print repr(test_num) + ' is perfect number' if sum(listtwo) == test_num else 'false'
return True if sum(listtwo) == test_num else False
if __name__ == '__main__':
# TestNum = int(sys.argv[1])
# print 'TestNum = ', TestNum
sum1 = 0
# perfect_number_check(TestNum)
# del sys.argv[1:]
unittest.main()
|
0c1ecd4b63dfb926fb4583d8be6944d49eba2d47
|
swizzard/selector
|
/selector.py
| 8,426 | 3.59375 | 4 |
"""
Mimic `select`-type behavior over a set of generators
"""
from itertools import cycle
from operator import itemgetter
class Selector(object):
"""
'Select' inputs from a collection of generators. Generators are paused or
stopped based on user-defined conditions.
"""
def __init__(self, stop_condition, pause_condition=None, gens=None):
"""
:param stop_condition: a predicate that should return `True` when a
generator should be stopped
:type stop_condition: function (predicate)
:param pause_condition: a predicate that should return `True` when a
generator should be paused so inputs can be taken from other
generators. Defaults to `Selector.false`, which returns False
regardless of input; each generator will thus be exhausted in turn,
similar to `itertools.chain`
:type pause_condition: function (predicate)
NB: the functions passed to `stop_condition` and `pause_condition`
should each take a single argument and return a boolean.
:param gens: list of generators to add to the Selector
:type gens: list of generator objects
"""
self.gens = gens or []
self.started = None
self.curr = None
self.stop_condition = stop_condition
self.pause_condition = pause_condition or self.false
def add_gen(self, gen):
"""
Add a generator to this Selector.
:param gen: the generator to add
:type gen: generator object
"""
self.gens.append(gen)
def add_gens(self, gens):
"""
Add multiple generators
:param gens: generators to add
:type gens: sequence of generator objects
"""
for gen in gens:
self.add_gen(gen)
def start(self):
"""
Start the selector
:return: generator object
"""
self.started = cycle(self.gens)
self.curr = next(self.started)
while True:
try:
res = next(self.curr)
except StopIteration:
self.remove_gen(self.curr)
else:
if self.stop_condition(res):
self.remove_gen(self.curr)
elif self.pause_condition(res):
self.pause_gen()
else:
yield res
def stop(self):
"""
Stop the selector by resetting it to its original state
"""
self.started = None
self.gens = []
self.curr = None
def pause_gen(self):
"""
Start taking values from the next generator
"""
self.curr = next(self.started)
def remove_gen(self, gen):
"""
Remove a generator from the selector and re-initialize self.started
"""
self.gens.remove(gen)
self.started = cycle(self.gens)
self.curr = next(self.started)
def __iter__(self):
"""
Allow selector to be iterated through
:return: generator object
"""
return self.start()
def __getitem__(self, idx):
"""
Access an individual generator
:param idx: index of the generator to be accessed
:type idx: int
"""
return self.gens[idx]
def __repr__(self):
"""
Formatted representation of `Selector` object
"""
fmt_str = "{}: stop_condition: {}, pause_condition: {}, gens: {}>"
return fmt_str.format(str(self.__class__)[:-1], self.stop_condition,
self.pause_condition, self.gens)
def select_on(self, gen):
"""
Wrapper around `.add_gen` that can be used as a decorator
"""
# pylint: disable=missing-docstring
def wrapper(*args, **kwargs):
self.add_gen(gen(*args, **kwargs))
return gen(*args, **kwargs)
# TODO: doc assignment doesn't seem to be working
wrapper.__doc__ = gen.__doc__
wrapper.__name__ = gen.__name__
return wrapper()
@staticmethod
def false(_):
"""
A dummy predicate that returns `False` regardless of input
>>> Selector.false(True)
False
"""
return False
class LabeledSelector(Selector):
"""
Subclass of Selector that allows outputs to be labeled by origin
"""
def __init__(self, stop_condition, pause_condition=None, gen_dict=None):
"""
:param stop_condition: a predicate that should return `True` when a
generator should be stopped
:type stop_condition: function (predicate)
:param pause_condition: a predicate that should return `True` when a
generator should be paused so inputs can be taken from other
generators. Defaults to `Selector.false`, which returns False
regardless of input; each generator will thus be exhausted in turn,
similar to `itertools.chain`
:type pause_condition: function (predicate)
NB: the functions passed to `stop_condition` and `pause_condition`
should each take a single argument and return a boolean.
:param gen_dict: a dict of labeled generators to add to the Selector
:param gen_dict: dict ({'label': <generator>})
"""
super(LabeledSelector, self).__init__(stop_condition, pause_condition)
self.labels = []
if gen_dict:
self.add_gens(gen_dict)
@property
def gens_dict(self):
"""
A dictionary mapping generators to labels
"""
return dict(zip(self.gens, self.labels))
@property
def labels_dict(self):
"""
A dictionary mapping labels to generators
"""
return dict(zip(self.labels, self.gens))
def start(self):
"""
Start the LabeledSelector
"""
gen = super(LabeledSelector, self).start()
while True:
val = next(gen)
label = self.gens_dict[self.curr]
yield {label: val}
def remove_gen(self, gen):
"""
Remove a generator and its label, and reinitialize self.started
:param gen: the generator object to remove
:type gen: a generator object
"""
self.labels.remove(self.gens_dict[gen])
super(LabeledSelector, self).remove_gen(gen)
# pylint: disable=arguments-differ
def add_gen(self, gen, label):
"""
Add a generator to this LabeledSelector
:param gen: the generator to add
:type gen: generator object
:param label: label to assign to the generator's output
:type label: str
"""
self.labels.append(label)
super(LabeledSelector, self).add_gen(gen)
def add_gens(self, gen_dict):
"""
Add generators from a {'label': <generator>} dict
:param gen_dict: dict of labeled generators
:type gen_dict: dict ({'label': <generator>})
"""
for label, gen in sorted(gen_dict.iteritems(), key=itemgetter(1)):
self.add_gen(gen, label)
def select_on(self, label):
"""
Wrapper around `.add_gen` that can be used as a decorator
:param label: the label to assign to the decorated generator's
output
"""
# pylint: disable=missing-docstring
def gen_wrapper(gen):
def wrapper(*args, **kwargs):
self.add_gen(gen(*args, **kwargs), label)
return gen(*args, **kwargs)
# TODO: doc assignment doesn't seem to be working
gen_wrapper.__doc__ = gen.__doc__
gen_wrapper.__name__ = gen.__name__
return wrapper()
return gen_wrapper
def stop(self):
"""
Stop the selector by resetting it to an empty state
"""
super(LabeledSelector, self).stop()
self.labels = []
def __repr__(self):
"""
Formatted representation of `LabeledSelector` object
"""
fmt_str = "{}: stop_condition: {}, pause_condition: {}, gens: {}>"
return fmt_str.format(str(self.__class__)[:-1], self.stop_condition,
self.pause_condition, self.labels_dict)
def __getitem__(self, label):
"""
Access a specific generator by label
"""
return self.labels_dict[label]
|
130049813722047d8668c04715d845d858001c84
|
claudiodornelles/CursoEmVideo-Python
|
/Exercicios/ex039 - Alistamento militar.py
| 1,384 | 4.0625 | 4 |
"""
Faça um programa que leia a idade de nascimento de um jovem e informe, de acordo com sua idade:
- Se ele ainda deve se alistar ao serviço militar.
- Se é a hora de se alistar.
- Se já passou do tempo do alistamento.
Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.
"""
from datetime import date
color = {'null': '\033[m',
'txt_blue': '\033[34m',
'txt_red': '\033[31m'}
yb = int(input("Qual o seu ano de nascimento? "))
idade = date.today().year - yb
if idade == 18:
print(f"{color['txt_blue']}Está na hora{color['null']} de você se alistar ao serviço militar!")
print("O alistamento deve ocorrer no ano em que você completa 18 anos de idade.")
elif idade < 18:
tempo = 18 - idade
print(f"{color['txt_red']}Você ainda não tem{color['null']} idade para se alistar ao serviço militar.")
print("O alistamento deve ocorrer no ano em que você completa 18 anos de idade.")
print(f"Você poderá se alistar em {color['txt_blue']}{tempo} ano(s){color['null']}.")
else:
tempo = idade - 18
print(f"{color['txt_red']}Já passou o momento do seu alistamento.{color['null']}")
print("O alistamento deve ocorrer no ano em que você completa 18 anos de idade.")
print(f"Caso você não tenha se alistado, {color['txt_red']}você deveria ter o feito {tempo} ano(s) atrás{color['null']}.")
|
2e7ee81d95dc1e7318a5a4147f50b47979266c6e
|
jhonatanmaia/python
|
/study/curso-em-video/exercises/075.py
| 401 | 4 | 4 |
x=(int(input('Digite um valor: ')),int(input('Digite um valor: ')),
int(input('Digite um valor: ')),int(input('Digite um valor: ')))
print(f'O valor 9 apareceu {x.count(9)} vezes')
if 3 in x:
print(f'O valor 3 aparece primeiro no índice {x.index(3)}')
else:
print('O número 3 não foi digitado')
print('Os valores pares foram: ', end='')
for i in x:
if i%2==0:
print(i,end=' ')
|
4efdbc64538470bcc25e2d0a0e47e72959fdc078
|
lein-hub/python_basic
|
/programmers/find_prime_number.py
| 554 | 3.734375 | 4 |
# def solution(n):
# def isPrime(n):
# if n != 2 and n % 2 == 0:
# return False
# for a in range(2, n//2+1):
# if n % a != 0:
# continue
# else:
# return False
# return True
# answer = 0
# for i in range(2, n+1):
# if isPrime(i):
# answer += 1
# return answer
def solution(n):
primes = set(i for i in range(2, n+1))
for i in range(2, len(primes)):
primes -= set(range(i*2, n+1, i))
return len(primes)
|
5019cb29f92406085636e737439008774e6e593f
|
DRomanova-A/Base_project_python
|
/основы программирования python (ВШЭ)/solutions/week-2/task_2_17_seq_len_even.py
| 660 | 4.40625 | 4 |
'''
Количество четных элементов последовательности
Определите количество четных элементов в последовательности,
завершающейся числом 0.
Формат ввода: Вводится последовательность целых чисел,
оканчивающаяся числом 0 (само число 0 в последовательность не входит,
а служит как признак ее окончания).
'''
n = int(input())
len_ = 0
while n != 0:
if not n % 2:
len_ += 1
n = int(input())
print(len_)
|
809aa2234fa08e6291c09b46fc858f9bd8bb99c9
|
SpringSnowB/All-file
|
/m1/d4/esercise08.py
| 149 | 3.703125 | 4 |
"""
几 + 几 =几
"""
import random
number1, number2 = random.randint(1,10),random.randint(1,10)
print("%d+%d=%d"%(number1,number2,number1+number2))
|
1e7d00285e3386c5cf2bae84386bb04294a06b69
|
lijubjohn/python-stuff
|
/algorithms/linkedlist/remove_nth_node_frm_end.py
| 453 | 4.09375 | 4 |
# '''
# Given a linked list, remove the n-th node from the end of list and return its head.
# Example:
# Given linked list: 1->2->3->4->5, and n = 2.
# After removing the second node from the end, the linked list becomes 1->2->3->5.
# '''
#
#
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# class Solution:
# def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
#
#
|
135d327f5aeb122c5c61838c1bcd42170afcc3af
|
mandalaalex1/MetricsConverionTool
|
/MetricsConversionTool.py
| 1,906 | 4.15625 | 4 |
print("Options:")
print("[P] Print Options")
print("[C] Convert from Celsius")
print("[F] Convert from Fahrenheit")
print("[M] Convert from Miles")
print("[KM] Convert from Kilometers")
print("[In] Convert from Inches")
print("[CM] Convert from Centimeters")
print("[Q] Quit")
while True:
Option1 = input("Option: ")
if Option1 == "C":
Celsius = int(input("Celsius Temperature: "))
F1 = float(Celsius*9//5 +32)
print("Fahrenheit: " + str(F1))
elif Option1 == "F":
Fahrenheit = int(input("Fahrenheit Temperature: "))
C1 = float((Fahrenheit-32)*5//9)
print("Celcius: " + str(C1))
elif Option1 == "M":
Miles = int(input("Miles Distance: "))
M1 = float((Miles//1.609))
print("Kilometers: " + str(M1))
elif Option1 == "KM":
Kilometers = int(input("Kilometers Distance: "))
KM1 = float((Kilometers*1.609))
print("Miles: " + str(KM1))
elif Option1 == "In":
Inches = int(input("Inches: "))
In = float((Inches*2.54))
print("Centimeters: " + str(In))
elif Option1 == "CM":
Centimeters = float(input("Centimeters: "))
CM1 = float((Centimeters//2.54))
print("Inches: " + str(CM1))
elif Option1 == "Y":
Yard = float(input("Yard: "))
Y1 = float((Yard//1.094))
print("Meters: " + str(Y1))
elif Option1 == "MT":
Meters = float(input("Meters: "))
MT1 = float((Meters*1.094))
print("Yard: " + str(MT1))
elif Option1 == "P":
print("[C] Convert from Celsius")
print("[F] Convert from Fahrenheit")
print("[M] Convert from Miles")
print("[KM] Convert from Kilometers")
print("[In] Convert from Inches")
print("[CM] Convert from Centimeters")
print("[Q] Quit")
elif Option1 == "Q":
print("Good bye!! :)")
break
|
9a6bcdbc9ef9307f229326ec584d77fe001c1de2
|
dbconfession78/holbertonschool-webstack_basics
|
/0x01-python_basics/10-simple_delete.py
| 309 | 3.84375 | 4 |
#!/usr/bin/python3
"""
Module 10-simple_delete
"""
def simple_delete(my_dict, key=""):
"""
Description - deletes a key in a dictionary
:param my_dict: dict to delete from
:param key: key of dict element to delete
"""
if my_dict:
my_dict.pop(key, None)
return my_dict
|
a553136bc8047e1d45f6cab4c34e290b9874d31f
|
apple-han/Learning_python
|
/python/python_automation/string_encoding.py
| 725 | 4.125 | 4 |
python2 编码问题
def to_unicode(unicode_or_str):
if isinstance(unicode_or_str, str):
value = unicode_or_str.decode('utf-8')
else:
value = unicode_or_str
return value
def to_str(unicode_or_str):
if isinstance(unicode_or_str, str):
value = unicode_or_str.encode('utf-8')
else:
value = unicode_or_str
return value
python3 编码
def to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str, str):
value = bytes_or_str.encode('utf-8')
else:
value = bytes_or_str
return value
|
2df60ffb99ecac399ac959168224e58f96372bb2
|
attacker2001/Algorithmic-practice
|
/Codewars/Find the odd int.py
| 672 | 4.25 | 4 |
# coding=UTF-8
'''
Given an array, find the int that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
test.describe("Example")
test.assert_equals(find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]), 5)
即找出列表中 出现次数为奇数的元素
'''
def find_it(seq):
for i in seq:
if seq.count(i) % 2 != 0:
return i
return None
def main():
numbers = [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]
print find_it(numbers)
if __name__ == "__main__":
main()
'''
Other Soluntion:
import operator
def find_it(xs):
return reduce(operator.xor, xs)
'''
|
f23ada6de8dde7f22d00f1648c97da02c0da22f2
|
mahamadousylla/GPS-via-MapQuest
|
/ducktyping.py
| 4,189 | 3.796875 | 4 |
#Mahamadou Sylla
class Steps:
def lookup(self, json_object):
'''
takes in a json object and
finds out directions about
a particular trip
'''
directions = [ ] #empty list
for dictionary in json_object['route']['legs']: #we are at the dictionary under [route][legs]
for subdict in dictionary['maneuvers']: #we go in another layer deep and sublist is another dictionary inside dictionary[maneuvers]
directions.append(subdict['narrative']) #in this dictionary, add all narratives to the list 'directions'
print('DIRECTIONS') #print this message
for narrative in directions: #for every narrative in this list
print(narrative) #prints narrative
return #returns and leaves function
class Total_distance:
def lookup(self, json_object):
'''
takes in a json object and
finds the total distance about
a particular trip
'''
return 'TOTAL DISTANCE: ' + str(round(json_object['route']['distance'])) + ' miles' #prints 'Total distance' along with the total amount of miles the trip is
class Total_time:
def lookup(self, json_object):
'''
takes in a json object and
finds out the total time about
a particular trip
'''
return 'TOTAL TIME: ' + str(round(json_object['route']['time']/60)) + ' minutes' #prints 'Total time' along with the total amount of time it will take to complete the trip
class Latlong:
def lookup(self, json_object):
'''
takes in a json object and
finds out the lattitude and
longitude about a particular trip
'''
latLng = [ ] #empty list
index = 0 #used as an index. To be used as iteration
print('LATLONGS') #prints this message to the console
for dictionary in json_object['route']['locations']: #for the dictionary in this dictionary
latLng.append(dictionary['latLng']['lat']) #appends the latitude to the 'latLng' list
latLng.append(dictionary['latLng']['lng']) #appends the longitude to the 'latLng' list
if str(latLng[index]).startswith('-'): #if the lattitude is negative
latLng[index] = str(latLng[index]).replace('-', '') #removes the negative sign
print('{:.2f}S {:.2f}E'.format(float(latLng[index]),float(latLng[-1]))) #prints the latitude in this format showing it is South
elif str(latLng[-1]).startswith('-'): #if the longitude is negative
latLng[-1] = str(latLng[-1]).replace('-', '') #removes the negative sign
print('{:.2f}N {:.2f}W'.format(float(latLng[index]),float(latLng[-1]))) #prints the longitude in this format showing it is East
elif str(latLng[index]).startswith('-') and latLng[-1].startswith('-'): #if the lattitude and longitude are both negative
latLng[index] = str(latLng[index]).replace('-', '') #removes the negative sign
print('{:.2f}S {:.2f}W'.format(float(latLng[index]),float(latLng[-1]))) #prints the latitude and longitude in this format showing it is South and East respectively
else: #otherwise
print('{:.2f}N {:.2f}E'.format(float(latLng[index]),float(latLng[-1]))) #prints the latitude and longitude in this format showing it is North and West respectively
index += 2 #this is used to grab the lattidue and longitude as pairs as the latLng list is increasing by these 2 elements at the same time
return #leaves function
class Elevation:
def lookup(self, json_object):
'''
takes in a json object and
finds out elevation details about
a particular trip
'''
print('ELEVATIONS') #prints this message
for item in json_object: #this object is a list, so for every item in this list
item = round((float(item)) *3.280952380952381) #converts elevation to feet
print(item) #print item
print()
return #leaves function
|
1dbc81627b5d9f096a94946072d51f09ef7b9d5d
|
phuonghoangpham/phamhoangphuong-fundamental-c4e20
|
/Session02/sum_function.py
| 78 | 3.546875 | 4 |
numb=int(input("enter a number = "))
total = sum(range(numb+1))
print(total)
|
754651adfa862bf68453fc90b5f8abdddd2c4930
|
op-secure/ML-Python-Scikit-Notes
|
/5_numpy_bool-array.py
| 242 | 3.859375 | 4 |
# Boolean arrays
# - Handle indexing with boolean logic
import numpy as np
a = np.arange(10).reshape(5,2) + 1
# Create a boolean array
ba = a > 5
print(ba)
# Filter by a boolean array
# Example 1
print(a[ba])
# Example 2
print(a[a < 5])
|
b1763841a3ce3cec9230ba460fcf4b76b33f03df
|
MollyKate-G/file_managment_MG
|
/shop_list.py
| 1,358 | 4.21875 | 4 |
def shopping_list():
print("Shopping List!\n")
choice = " "
while choice.upper() != 'Q':
choice = input("""--------------------------\n\nChoose an option:
(P)rint shopping list
(A)dd item to shopping list
(C)lear shopping list
(Q)uit
""")
if choice.upper() == 'P':
with open("shopping_list.txt", "r") as my_file:
print(my_file.read())
if choice.upper() == 'A':
shop_item = input("Enter shopping list item: ")
with open("shopping_list.txt", "a") as my_file:
my_file.write(f'\n{shop_item}\n')
print(f"\n{shop_item}, have been added to your shopping list\n")
if choice.upper() == 'C':
erase_shopping = " "
erase_shopping = input("Are you sure you want to delete your shopping list? Y/N \n")
if erase_shopping.upper() == 'Y':
print("Your shopping list has been cleared")
with open("shopping_list.txt", "w") as my_file:
my_file.write(" ")
else:
print("Your shopping list is still saved")
if choice.upper() == 'Q':
print("Exiting the program. Your shopping list has been saved in 'shopping_list.txt'. Goodbye!")
return
|
d6e86fd486f908e5e0561cdfde9a11e375673453
|
xaviergoby/Python-Data-Structure
|
/Excersise/EvenOrOddWithoutUsingModDiv.py
| 1,107 | 4.5 | 4 |
__author__ = 'Sanjay'
# The below program is to check whether the given number is odd or even
# The logic is acheived by Bit wise operator
# normally people will use Modulo or division operator to find its even or odd.
numList = range(0, 10, 2) # [0,2,4,6,8]
def commonLogicPlusMyOwnImplementation(n):
# used bit wise operator logic and also checking whether the last number of the digit
# is there in numList, which is a common declared list at the top
if ((n & 1 == 0) or (n in numList)):
print("It's a Even Number")
else:
print("It's a Odd Number")
if __name__ == '__main__':
try:
getIn = raw_input("Please give a input to check whether the number is even or odd")
if getIn.isdigit(): # checks whether the user given input is valid or not.
if getIn == 1 or getIn >1:
commonLogicPlusMyOwnImplementation(int(getIn))
else:
raise ArithmeticError("Something is wrong in the given input!Check it.")
except ArithmeticError as e:
print(e.message)
else:
print("Thanks for testing me!")
|
b0012d11daa4dfd8e1e146a3c2fe637cd3455aee
|
ahartikainen/avroc
|
/avroc/util.py
| 749 | 3.84375 | 4 |
from typing import Dict, Union, List, Any
import random
import re
# SchemaType is a type which describes Avro schemas.
SchemaType = Union[
str, # Primitives
List[Any], # Unions
Dict[str, Any], # Complex types
]
def rand_str(length: int) -> str:
"""Generate a random string of given length."""
alphabet = "0123456789abcdef"
return "".join(random.choices(alphabet, k=length))
def clean_name(name: str) -> str:
"""
Clean a name so it can be used as a python identifier.
"""
if not re.match("[a-zA-Z_]", name[0]):
name = "_" + name
name = re.sub("[^0-9a-zA-Z_]+", "_", name)
if all(c == "_" for c in name):
name = "v"
return name
class LogicalTypeError(Exception):
pass
|
f7a09db70f8cf4429535df53db401e9a570d5ff9
|
AbandonBlue/Coding-Every-Day
|
/NLP_Useful_Function/functions.py
| 2,686 | 3.703125 | 4 |
def stem(word):
"""
Find stem like (a little different)
ex:
pattern = r"^.*(?:ing|ly|ed|iout|ies|ive|es|s|ment)$"
re.findall(pattern, 'processing')
"""
word = word.lower() # lower first
for suffix in ['ing', 'ly', 'ed', 'ious', 'ies', 'ive', 'ed', 's', 'ment']:
if word.endswith(suffix):
return word[:-len(suffix)]
# others
return word
def segment(text, segs):
"""
Use '1' to segment sentences
ex:
text = "doyouseethekittyseethedoggydoyoulikethekittylikethedoggy"
seg1 = "0000000000000001000000000010000000000000000100000000000"
segment(text, seg1) ---> ['doyouseethekitty', 'seethedoggy', 'doyoulikethekitty', 'likethedoggy']
"""
words = []
last = 0
for i in range(len(segs)):
if segs[i] == '1':
words.append(text[last:i+1])
last = i+1
words.append(text[last:])
return words
def evaluate(text, segs):
"""
To evaluate the score of seg.
less score means better seg.
ref: (Brent & Cart-wright, 1995)
"""
words = segment(text, segs)
text_size = len(words)
lexicon_size = len(' '.join(list(set(words))))
return text_size + lexicon_size
# 模擬退火算法的非確定性搜尋
from random import randint
def flip(segs, pos):
return segs[:pos] + str(1-int(segs[pos])) + segs[pos+1:]
def flip_n(segs, n):
for i in range(n):
segs = flip(segs, randint(0,len(segs)-1))
return segs
def anneal(text, segs, iterations, cooling_rate):
temperature = float(len(segs))
while temperature > 0.5:
best_segs, best = segs, evaluate(text, segs)
for i in range(iterations):
guess = flip_n(segs, int(round(temperature)))
score = evaluate(text, guess)
if score < best:
best, best_segs = score, guess
score, segs = best, best_segs
temperature = temperature / cooling_rate
print(evaluate(text, segs), segment(text, segs))
print()
return segs
def ie_preprocess(document):
import nltk
# pipeline for 信息提取
"""
"""
sentences = nltk.sent_tokenize(document) # 分句
sentences = [nltk.word_tokenize(sent) for sent in sentences] # 分詞
sentences = [nltk.pos_tag(sent) for sent in sentences] # pos_tag
return sentences
def get_np_tree(sent, grammar="NP: {<DT>?<JJ>*<NN>}", ):
# 搭配ie_preprocess處理完的結果去繼續使用
import nltk
cp = nltk.RegexpParser(grammar)
result = cp.parse(sent)
result.draw()
return result
if __name__ == "__main__":
pass
|
dc4ad722af7e7f3fbe1fbe6ff54f4ef97db57f61
|
tarekalmowafy/Compatetive_Programming
|
/hackerrank/domains/python/sets/set_intersection.py
| 140 | 3.75 | 4 |
input()
english=set([x for x in input().split() ])
input()
french=set([x for x in input().split()])
print(len(english.intersection(french)))
|
67ed09aeabb92bda5b975c6dcc7991f4130a980a
|
danalrds/FP
|
/Other/A2.py
| 4,911 | 3.9375 | 4 |
def printmenu():
print("0.Read numbers")
print("1.Strictly increasing numbers")
print("3.All consecutive number pairs have the greatest common divisor 1")
print("5.Consist of a single number")
print("4.Only prime numbers")
print("7.The difference between the absolute value of consecutive numbers is a prime number.")
print("8.All elements in [0,10] range")
print("-1.EXIT")
def readnumbers(nlist,n): #subprogram pt citire a celor n numere
for i in range(1,n+1):
nr=int(input())
nlist.append(nr)
def writesequence(nlist,st,dr): #subprogram care afiseaza secventa[st,dr] din nlist
if st<=dr:
for i in range(st,dr+1):
print(nlist[i])
else:
print("There is no sequence! ")
def gcd(a,b): #subprogram care calculeaza cel mai mare divizor comun
r=1
if a<b:
aux=a
a=b
b=aux
a=abs(a)
b=abs(b)
while r!=0:
r=a%b
a=b
b=r
return a
def prime(x): #functia de numar prim
if x==1 or x==0:
return False
else:
for d in range(2,int(x**0.5)+1):
if x%d==0:
return False
return True
def prob1(nlist,n):
l=1
max=0
st=0
sf=0
stbun=0
sfbun=0
for i in range(1,n):
if nlist[i-1]>=nlist[i]:
if l>max:
max=l
stbun=st
sfbun=sf
st=i
l=0
else:
l+=1
sf=i
if l>max:
max=l
stbun=st
sfbun=i
writesequence(nlist,stbun,sfbun)
def prob3(nlist,n):
l=1
max=0
st=0
sf=0
stbun=0
sfbun=0
for i in range(1,n):
if gcd(nlist[i-1],nlist[i])!=1:
if l>max:
max=l
stbun=st
sfbun=sf
st=i
l=0
else:
l+=1
sf=i
if l>max:
max=l
stbun=st
sfbun=i
writesequence(nlist,stbun,sfbun)
def prob4(nlist,n):
max=0
l=0
st=0
sf=0
stbun=0
sfbun=0
for i in range(0,n):
if prime(nlist[i])==True:
sf=i
l+=1
else:
if l>max:
max=l
stbun=st
sfbun=sf
l=0
st=i+1
if l>max:
max=l
stbun=st
sfbun=i
writesequence(nlist,stbun,sfbun)
def prob5(nlist,n):
l=1
max=0
st=0
sf=0
stbun=0
sfbun=0
for i in range(1,n):
if nlist[i-1] != nlist[i]:
if l>max:
max=l
stbun=st
sfbun=sf
st=i
l=0
else:
l+=1
sf=i
if l>max:
max=l
stbun=st
sfbun=i
writesequence(nlist,stbun,sfbun)
def prob7(nlist,n):
l=1
max=0
st=0
sf=0
stbun=0
sfbun=0
for i in range(1,n):
if prime(abs(nlist[i-1]-nlist[i]))==False:
if l>max:
max=l
stbun=st
sfbun=sf
st=i
l=0
else:
l+=1
sf=i
if l>max:
max=l
stbun=st
sfbun=i
writesequence(nlist,stbun,sfbun)
def prob8(nlist,n):
max=0
l=0
st=0
for i in range(0,n):
if (nlist[i]>=0) and nlist[i]<=10:
sf=i
l+=1
else:
if l>max:
max=l
stbun=st
sfbun=sf
l=0
st=i+1
if l>max:
max=l
stbun=st
sfbun=i
writesequence(nlist,stbun,sfbun)
def start():
nlist=[7, 4, 1, 2, 3, 9, 7, 1, 1, 1, 5, 14, 3, 9, 7]
n=15
x=1
while x!=0:
print(nlist)
printmenu()
x=input()
if x=="0":
nlist=[]
n=int(input("Give the number n: "))
readnumbers(nlist,n)
elif x=="1":
print("The longest sequence of strictly increasing numbers: ")
prob1(nlist,n)
elif x=="3":
print("The longest sequence of consecutive number pairs which have the greatest common divisor 1: ")
prob3(nlist,n)
elif x=="4":
print("The longest sequence of prime numbers: ")
prob4(nlist,n)
elif x=="5":
print("The longest sequence of one single number: ")
prob5(nlist,n)
elif x=="7":
print("The longest sequence in wich the difference between the absolute value of consecutive numbers is a prime number: ")
prob7(nlist,n)
elif x=="8":
print("The longest sequence of numbers in [0,10]: ")
prob8(nlist,n)
else:
break
start()
|
fbedc5db38e482a5f7606c5b03bdd0b6e527c4df
|
TLS97/sudoku-solver
|
/utilities.py
| 3,203 | 3.59375 | 4 |
import cell
knight = False
king = False
def empty_cell(b):
for i in range(9):
for j in range(9):
if b[i][j].num == 0:
return i, j
return False
def print_board(b):
print("\nBoard: ")
for i in range(9):
if (i == 3) or (i == 6):
print("- - - - - - - - - - -")
print("{} {} {} | {} {} {} | {} {} {}".format(b[i][0].num, b[i][1].num, b[i][2].num, b[i][3].num, b[i][4].num,
b[i][5].num, b[i][6].num, b[i][7].num, b[i][8].num))
def apply_constraints(cons):
global knight, king
if cons == "kn":
knight = True
print("Knight is True")
elif cons == "ki":
king = True
elif cons == "r":
knight = False
king = False
else:
print("Error: Constraint not valid!")
return knight, king
def check_row_col_box(b, n, row, col):
for i in range(9):
if b[i][col].num == n:
return False
for i in range(9):
if b[row][i].num == n:
return False
r = (row // 3) * 3
c = (col // 3) * 3
for di in range(0, 3):
for dj in range(0, 3):
if b[di + r][dj + c].num == n:
return False
return True
def check_knight(b, n, row, col):
for i in range(row - 2, row + 3, 4):
for j in range(col - 1, col + 2, 2):
if (row, col) != (i, j) and (0 < i < 9) and (0 < j < 9):
if b[i][j].num == n:
print("Knight not valid")
return False
for i in range(row - 1, row + 2, 2):
for j in range(col - 2, col + 3, 4):
if (row, col) != (i, j) and (0 < i < 9) and (0 < j < 9):
if b[i][j].num == n:
print("Knight not valid")
return False
return True
def check_king(b, n, row, col):
for dr in range(row - 1, row + 2):
for dc in range(col - 1, col + 2):
if row != dr and col != dc and 0 <= dr < 9 and 0 <= dc < 9:
if b[dr][dc].num == n:
return False
return True
def validity(b, n, row, col):
if knight == True:
return check_row_col_box(b, n, row, col) and check_knight(b, n, row, col)
elif king == True:
return check_row_col_box(b, n, row, col) and check_king(b, n, row, col)
else:
return check_row_col_box(b, n, row, col)
# def check_correctness(b):
# checklist = []
# for i in range(9):
# for j in range(9):
# if check_validity(b, b[i][j].num, i, j):
# checklist.append(True)
# if all(checklist):
# return True
#
#
# def decision(b):
# # If board is full
# if not empty_cell(b) and check_correctness(b):
# print("The solution is correct")
# else:
# for i in range(9):
# for j in range(9):
# if b[i][j].num != 0:
# if validity(b, b[i][j].num, i, j):
# print("Board number: {}, Row: {}, Col: {}".format(b[i][j].num, i, j))
# return True
# else:
# return False
|
7a744bde105d59e43a4b6555c9dc758d345959be
|
fabiiogomes/exerciciospy
|
/exercicios/015.py
| 325 | 3.640625 | 4 |
#Progama que ler a quantidade de dia e km de um carro alugado
#e mostra o preço a pagar sabendo que: 1dia = R$60 e 1km = R$0,15
quantkm = float(input('Quantos Km rodados? '))
quantdia = int(input('Quantos dias alugados? '))
preço = (quantkm * 0.15) + (quantdia * 60)
print('O total a pagar é de R${:.2f}'.format(preço))
|
b0b800cc68991927eef966829e076bfd115dc74f
|
PedroAM/Euler-project
|
/PE_7.py
| 547 | 3.6875 | 4 |
import time
def isPrime(n):
if n==1:
return False
if n==2 or n==3 or n==5 or n==7:
return True
if n%2 ==0 or n%3==0 or n%5==0 or n%7==0:
return False
for i in xrange(3,int(n**0.5+1),2):
if n % i ==0:
return False
i +=1
return True
def genPrime(n):
ini=time.time()
p=[2]
i=3
while len(p)!=n:
if isPrime(i):
p.append(i)
i = i+2
print p[n-1]
end=time.time()-ini
print end
|
d5d4df79ab090a4f1a898c47dc65fdd428ac2cd1
|
PandaWhoCodes/udhaar.site
|
/db_utils.py
| 2,411 | 3.71875 | 4 |
"""
functions for interaction with the database.
"""
from db_secrets import DB_NAME, USER_NAME, PASSWORD, HOST
import pymysql
def create_connection():
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or Noneinsert_into_user_input
"""
try:
conn = pymysql.connect(host=HOST,
user=USER_NAME,
password=PASSWORD,
db=DB_NAME,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
return conn
except:
return None
def run_query(query, args=[], conn=None):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param query: a SQL query
:return:
"""
if conn == None:
conn = create_connection()
with conn.cursor() as cursor:
if query.lower().startswith("select"):
cursor.execute(query=query, args=args)
return cursor.fetchall()
else:
cursor.execute(query=query, args=args)
try:
conn.commit()
except Exception as e:
print("ERROR OCCURED WHILE DB COMMIT --- DB_UTILS", e)
def insert_into_users(user_name, name, email):
"""
:return:
"""
sql_query = """insert into users (user_name,name,email) VALUES (%s,%s,%s)"""
run_query(sql_query, [user_name, name, email])
def insert_into_udhaar(user_name, name, email, amount):
sql_query = """insert into udhaars (user_name,name,email,amount) VALUES (%s,%s,%s,%s)"""
run_query(sql_query, [user_name, name, email, amount])
def get_udhaars(user_name):
sql_query = """select * from udhaars where user_name = "%s" """ % user_name
return run_query(sql_query)
def get_udhaar(id):
sql_query = """select * from udhaars where id = %s """ % id
return run_query(sql_query)
def get_user_mail_and_name(user_name):
sql_query = """select email,name from users where user_name = "%s" """ % user_name
return run_query(sql_query)
def delete_udhaar(udhaar_id):
sql_query = """DELETE from udhaars where id = %s""" % udhaar_id
run_query(sql_query)
def get_user(user_name):
sql_query = """SELECT * from users where user_name = "%s" """ % user_name
return run_query(sql_query)
|
df104b81674fb0a06ea94c1fe587814f7b4e6cc3
|
ricardo64/Over-100-Exercises-Python-and-Algorithms
|
/src/examples_in_my_book/general_problems/numbers/convert_from_decimal.py
| 523 | 4.15625 | 4 |
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def convert_from_decimal(number, base):
''' convert any decimal number to another base. '''
multiplier, result = 1, 0
while number > 0:
result += number%base*multiplier
multiplier *= 10
number = number//base
return result
def test_convert_from_decimal():
number, base = 9, 2
assert(convert_from_decimal(number, base) == 1001)
print('Tests passed!')
if __name__ == '__main__':
test_convert_from_decimal()
|
21cc164694d6a079b4cb221c0703e23ed25ed995
|
ApplauseWow/IT_new_technique_assignment
|
/practice1/practice1-1.py
| 836 | 3.765625 | 4 |
# -*-coding:utf-8-*-
# created by HolyKwok 201610414206
# practice1-1
# detect the quality of the air
def air_detection(air_data):
# a function for air detection
if air_daata >= 250 : # severe pollution
print(u'严重污染')
elif air_data >= 150: # heavy pollution
print(u'重度污染')
elif air_data >= 115: # middle poluution
print(u"中度污染")
elif air_data >= 75: # light pollution
print(u"轻度污染")
elif air_data >= 35: # good
print(u'良')
elif air_daata >=0: # awesome
print(u'优')
else:
print(u'输入错误')
if __name__ == '__main__':
try:
air_daata = eval(input(u'今日空气质量:')) # 输入空气数据
air_detection(air_daata)
except Exception:
print(u"输入格式不正确!")
|
6e7641c80563678626da5aaa8c75971829d0d30b
|
AmitAps/python
|
/pythontute/string1.py
| 55 | 3.6875 | 4 |
s = input("Name: ")
print(f"Hello, {s.capitalize()}")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.