blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d5b50dc98afa6fe56cca90e3a98900be87d558d7 | Aasthaengg/IBMdataset | /Python_codes/p02257/s294042094.py | 490 | 3.9375 | 4 | """素数を求める。
以下の性質を用いる。
合成数 x は p <= sqrt(x) を満たす素因子 pをもつ。
"""
import math
def is_prime(x):
if x == 2:
return True
if x < 2 or x % 2 == 0:
return False
for i in range(3, math.floor(math.sqrt(x)) + 1):
if x % i == 0:
return False
return True
N = int(input())
data = [int(input()) for i in range(N)]
cnt = 0
for d in data:
if is_prime(d):
cnt += 1
print(cnt)
|
d5ce5fd1c4b75f9d922bde437526e4a02b1ee51b | extra-virgin-olive-eul/pe_solutions | /3/PE-P3_VSX.py | 3,290 | 3.734375 | 4 | #!/usr/bin/env python3
'''
Program: PE-P3_VSX.py
Author: vsx-gh (https://github.com/vsx-gh)
Created: 20171002
Project Euler Problem 2:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
This program approaches the problem from the perspective that the only tests
needed to find both the factors of an input and to test whether a factor is
prime is to test the range 2..sqrt(input). For example, the factors of 24 are:
1 x 24
2 x 12
3 x 8
4 x 6
6 x 4
8 x 3
12 x 2
24 x 1
The breakover point where we start to repeat happens after "4 x 6". If we test
up to and including sqrt(24) (which is 4 and some change), we will grab the
test for 4 and 6 will come along with it. This divide-and-conquer strategy
eliminates a big chunk of the search space and avoids a brute-force approach.
Since a number is not prime if it has any factors besides itself and 1, we are
once again just looking for factors; so, we can use the same test range.
Prime tests are almost an entire field unto themselves, so there is probably
room for improvement here. But I decided not to get any fancier than I did here.
I hope I hope I hope this program does not have any serious flaws. I have tested
with several inputs, including the problem input, and my answer was accepted.
I'm still open to suggestions for improvements.
'''
import argparse
import math
def test_prime(candidate):
""" Tests if candidate is a prime number """
candidate_sqrt = int(math.sqrt(candidate))
range_end = 2
# There is no "range" to test
if candidate_sqrt < range_end:
return True
for div in range(range_end, candidate_sqrt + 1):
if div == candidate_sqrt:
if candidate % div == 0:
return False
elif candidate % div == 0: # Another factor involved
return False
return True # Passed all disqualification tests
def find_largest_pf(input_item):
""" Finds largest prime factor of input_item """
largest_pf = 1
for item in range(1, int(math.sqrt(input_item)) + 1):
if input_item % item == 0: # Item is a factor of input_item
div = int(input_item / item) # Python 3 will return float
if test_prime(div):
largest_pf = div
elif test_prime(item):
largest_pf = item
return largest_pf
def find_factors(input_item):
""" Finds all factors of input_item """
factors = []
for item in range(1, int(math.sqrt(input_item)) + 1):
if input_item % item == 0:
factors.append(item)
factors.append(int(input_item / item))
return sorted(factors, reverse=True)
# Get some args
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input',
required=True,
type=int,
help='Input integer to test'
)
all_args = parser.parse_args()
input_int = all_args.input
# Run tests
print('All factors of {}: {}.'.format(input_int, find_factors(input_int)))
print('Largest prime factor of {} is {}.'.format(input_int, find_largest_pf(input_int)))
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
22114982f91f6a8b58e53432b5dec6cf6b45cda3 | gauravyantriks/PythonPractice | /Exercise3.py | 1,131 | 4.5 | 4 | '''
Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the
elements of the list that are less than 5.
'''
list_1=[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print('first loop approach')
for no in list_1:
if no < 5:
print(no)
#extras
'''
Instead of printing the elements one by one,
make a new list that has all the elements
less than 5 from this list in it and print
out this new list.
Write this in one line of Python.
Ask the user for a number and
return a list that contains only elements
from the original list a that are smaller
than that number given by the user.
'''
#filtering list in 1 line
list_new= [x for x in list_1 if x<5]
print('comprehension approach')
for no in list_new :
print(no)
#another approach using lambda
list_new=list(filter(lambda x:x<5,list_1))
print('lambda approach')
for no in list_new :
print(no)
print("Now we will show only those no less than no entered by user")
num=int(input("Enter a no"))
print('using comprehension approach')
for number in [x for x in list_1 if x<num]:
print(number) |
174b45a35d01c35adaf2436f9cf14aaa90e6ea63 | uosoul/soul | /力扣题目/206链表逆序.py | 561 | 4.0625 | 4 | def reverselist(head):
cur =head
pre = None
while cur:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre
def reverse_list(head):
cur = head
pre = None
while cur:
temp = cur.next
cur.next =pre
pre = cur
cur = temp
return pre
|
537a0bce959fec499626bd41f76e6f7578a4da0c | Dilshodbek23/Python-lessons | /34_2.py | 237 | 3.53125 | 4 | import json
student_json = """{"name":"Hasan","surname":"Husanov","ybirth":2000}"""
student = json.loads(student_json)
print(student['name'], student['surname'])
with open('student.json', 'w') as f:
json.dump(student, f) |
452997b701f784cbe1dfbf51d6358ee4456831e3 | srbrettle/Sandbox-Algorithms | /HackerRank/Tutorials/10 Days of Statistics/Day 0 Mean, Median, and Mode.py | 358 | 3.703125 | 4 | size = int(input())
numbers = list(map(int, input().split(" ")))
numbers.sort()
# mean
mean = sum(numbers)/size
print(mean)
# median
if size%2==1:
# odd size
median = numbers[int(size/2-0.5)]
else:
# even size
median = (numbers[int(size/2-1)]+numbers[int(size/2)])/2
print(median)
# mode
mode = max(numbers, key=numbers.count)
print(mode)
|
d75fd4ec35ba613b8698aaf04ffb0a28fb97535d | pedrillogdl/ejemplos_python | /contrasena.py | 241 | 3.859375 | 4 | contrasena=input("Por favor, introduce tu contrasena: ")
valida=True
for i in contrasena:
if i==" ":
valida=False
if len(contrasena)>8 and valida==True:
print("La contrasena es Correcta")
else:
print("La contrasena es Incorrecta")
|
90f7851f88a34a9b0389274d743ea5035aded2b8 | spmvg/evt | /src/evt/methods/peaks_over_threshold.py | 3,478 | 3.828125 | 4 | from numbers import Real
import matplotlib.pyplot as plt
from evt import utils
from evt.dataset import Dataset
from scipy.stats import expon
class PeaksOverThreshold:
"""
The peaks over threshold method is one of the two fundamental approaches in extreme value theory.
The peaks of the ``Dataset`` ``dataset`` are determined by applying a threshold ``threshold`` :math:`\geq 0`
and the resulting peaks are stored in ``self.series_tail``.
"""
def __init__(
self,
dataset: Dataset,
threshold: Real
):
if threshold < 0:
raise ValueError('The threshold must be positive. Consider shifting the data.')
self.threshold = threshold
self.dataset = dataset
self.series_tail = dataset.series[dataset.series > threshold].copy()
def plot_tail(
self,
ax: plt.Axes
):
"""
Plot the peaks over threshold against the index of the original data.
The original dataset is shown for comparison.
"""
ax.plot(
self.dataset.series[
self.dataset.series.index.isin(self.series_tail.index)
],
'xr',
label='Tail',
zorder=101
)
ax.plot(
self.dataset.series,
'-k',
alpha=.3,
label='Dataset',
zorder=100
)
ax.axhline(
y=self.threshold,
linestyle='--',
alpha=.8,
color='k',
label='Threshold',
zorder=102
)
ax.set_xlabel(self.dataset.series.index.name or '')
ax.set_ylabel(self.dataset.series.name or '')
ax.grid()
ax.set_title('Peaks over threshold')
ax.legend(loc='lower right').set_zorder(200)
def plot_qq_exponential(
self,
ax: plt.Axes
):
"""
Quantile-quantile plot of the empirical survival function of the peaks over threshold against a fitted
exponential distribution.
"""
empirical_survival = 1 - utils.empirical_cdf(self.series_tail)
loc, scale = expon.fit(self.series_tail)
survival_function = expon.sf(empirical_survival.index, loc=loc, scale=scale)
ax.loglog(
survival_function,
empirical_survival,
'xk',
alpha=.8
)
ax.plot(
survival_function,
survival_function,
'r--',
alpha=.8,
label='Diagonal'
)
ax.invert_xaxis()
ax.invert_yaxis()
ax.set_xlabel('Exponential survival function')
ax.set_ylabel('Empirical survival function')
ax.legend(loc='upper left')
ax.set_title('Q–Q plot against exponential distribution')
def plot_zipf(
self,
ax: plt.Axes
):
"""
Log-log plot of the empirical survival function. The :math:`x`-axis corresponds to the values of the original
dataset.
"""
empirical_survival = 1 - utils.empirical_cdf(self.series_tail)
ax.loglog(
empirical_survival,
'xk',
label='Empirical survival',
alpha=.8
)
ax.set_xlabel(self.series_tail.name or '')
ax.set_ylabel('Empirical survival function')
ax.set_title('Zipf plot')
ax.grid()
ax.legend(loc='upper right')
|
c20d449afb6a9517578af89bddb25e12e1b3ff15 | FredC94/MOOC-Python3 | /UpyLab/UpyLaB 5.14 - Méthodes Séquences.py | 1,393 | 3.921875 | 4 | """ Auteur = Frédéric Castel
Date : Avril 2020
Projet : MOOC Python 3 - France Université Numérique
Objectif:
Nous pouvons définir la distance entre deux mots de même longueur (c’est-à-dire
ayant le même nombre de lettres) mot_1 et mot_2 comme le nombre minimum de fois où
il faut modifier une lettre de mot_1 pour obtenir mot_2 (distance de Hamming).
Par exemple, les mots « lire » et « bise » sont à une distance de 2, puisqu’il faut changer
le “l” et le “r” du mot « lire » pour obtenir « bise ».
Écrire une fonction distance_mots(mot_1, mot_2) qui retourne la distance entre deux mots.
Vous pouvez supposer que les deux mots sont de même longueur, et sont écrits sans accents.
Exemples:
distance_mots("lire", "bise") doit retourner: 2
distance_mots("Python", "Python") doit retourner: 0
distance_mots("merci", "adieu") doit retourner: 5
Consignes:
Dans cet exercice, il vous est demandé d’écrire seulement la fonction distance_mots.
Le code que vous soumettez à UpyLaB doit donc comporter uniquement la définition de cette fonction,
et ne fait en particulier aucun appel à input ou à print.
"""
def distance_mots(mot_1, mot_2):
res = 0
for i in range(len(mot_1)):
if id(mot_1[i]) != id(mot_2[i]):
res = res + 1
return res
distance_mots("lire", "bise") |
a497a1afb0059dee82a0195a8d372b5fe979e503 | ReshmaRajanChinchu/python-programming | /A16.py | 128 | 3.96875 | 4 | n=int("Enter the number:")
s=int("Enter the number:")
for i in range(n+1,s):
if(n%i == 0):
print(i)
else:
print('invalid')
|
9c3e59e0fd3477f3dd66059f67f0ec6eeeaa5d9f | weiyinfu/learnNumpy | /ndenumerate.py | 142 | 3.515625 | 4 | import numpy as np
a = np.random.random((2, 2, 3))
for index, value in np.ndenumerate(a):
print(index, value, type(index), type(value))
|
b747303e9d95e5ab0c86b0b0c78f48f69f3535dd | hi1rayama/PythonAlgorithm | /Sort/RadixSort.py | 3,901 | 3.859375 | 4 | '''
基数ソート(k=3桁の場合)
1. 10 個の容器(バケツ)を用意(a[0]~a[9])
2. k(3) 番目から 1 番目まで以下を繰り返し(最下位桁(1 の位)から最上位桁(3)まで)
3. 当該要素をキーとして,用意した容器でバケットソート
0~Aの整数値が対象の時
平均計算量:O(nlogA)
最悪計算量:O(nlogA)
内部ソート:×
安定ソート:○
'''
def radixSort(N, INPUT_VALUE):
print("ソート前:", INPUT_VALUE)
bucket = [[] for i in range(10)]
bucket2 = [[] for i in range(10)]
bucket3 = [[] for i in range(10)]
result = []
try:
for value in INPUT_VALUE:
R = value % 10
if(R == 0):
bucket[0].append(value)
elif(R == 1):
bucket[1].append(value)
elif(R == 2):
bucket[2].append(value)
elif(R == 3):
bucket[3].append(value)
elif(R == 4):
bucket[4].append(value)
elif(R == 5):
bucket[5].append(value)
elif(R == 6):
bucket[6].append(value)
elif(R == 7):
bucket[7].append(value)
elif(R == 8):
bucket[8].append(value)
elif(R == 9):
bucket[9].append(value)
#関数化可能
for value in bucket:
for i in value:
R = int((i % 100) / 10)
if(R == 0):
bucket2[0].append(i)
elif(R == 1):
bucket2[1].append(i)
elif(R == 2):
bucket2[2].append(i)
elif(R == 3):
bucket2[3].append(i)
elif(R == 4):
bucket2[4].append(i)
elif(R == 5):
bucket2[5].append(i)
elif(R == 6):
bucket2[6].append(i)
elif(R == 7):
bucket2[7].append(i)
elif(R == 8):
bucket2[8].append(i)
elif(R == 9):
bucket2[9].append(i)
#関数化可能
for value in bucket2:
for i in value:
R = int(i / 100)
if(R == 0):
bucket3[0].append(i)
elif(R == 1):
bucket3[1].append(i)
elif(R == 2):
bucket3[2].append(i)
elif(R == 3):
bucket3[3].append(i)
elif(R == 4):
bucket3[4].append(i)
elif(R == 5):
bucket3[5].append(i)
elif(R == 6):
bucket3[6].append(i)
elif(R == 7):
bucket3[7].append(i)
elif(R == 8):
bucket3[8].append(i)
elif(R == 9):
bucket3[9].append(i)
for value in bucket3:
result.extend(value)
print("1桁目:", bucket)
print("2桁目:", bucket2)
print("3桁目:", bucket3)
print("ソート後:", result)
except:
print("ERROR!")
N = int(input())
INPUT = list(map(int, input().split())) # 入力
radixSort(N, INPUT)
'''''''''''''''''''''''''''''''''
結果
$ python3 RadixSort.py
9
374 889 309 397 987 473 346 607 881
ソート前: [374, 889, 309, 397, 987, 473, 346, 607, 881]
1桁目: [[], [881], [], [473], [374], [], [346], [397, 987, 607], [], [889, 309]]
2桁目: [[607, 309], [], [], [], [346], [], [], [473, 374], [881, 987, 889], [397]]
3桁目: [[], [], [], [309, 346, 374, 397], [473], [], [607], [], [881, 889], [987]]
ソート後: [309, 346, 374, 397, 473, 607, 881, 889, 987]
'''''''''''''''''''''''''''''''''
|
c50e6313e8f83b81e31462b230f38ca3865768b5 | pychthonic/python-3 | /password_hash.py | 6,854 | 4.28125 | 4 | from hashlib import sha256
from getpass import getpass
import re
class LoginSession:
"""This program demonstrates password hashing, that is, how
computers authenticate users. Instead of keeping databases full of
plaintext passwords, or even encrypted passwords, they often store
hashes of the passwords. When a user enters their password, the
computer makes a hash of that password and compares it to its stored
hash for the user. If the two hashes match, the user is
authenticated. A hash cipher is an irreversible algorithm - it takes
a string of characters (in this case, the password), and scrambles
it into a long string of what look like random characters called the
hash. You can always get the hash if you have the password (you can
use sha256 to make a hash of the password 'password1234' on a
Tuesday then run sha256 on 'password1234' a year later on a
different computer in a different country and you'll get the same
hash), but you can't go in the opposite direction and get the
password from the hash, except with an unsafe hash algorithm like
sha1 or MD5, neither of which should be used to protect sensitive
information. The sha256 hashing algorithm is chugging along just
fine, and is safe to use (as of 2018...).
The program asks the user to either login with an existing username
or create a username and password. The first time the program is
run, it creates an archive file kept in the same directory the
executable was run from, called 'hashes.archive'. That file contains
hashes of the usernames and passwords that are created through the
program, so someone who opens the file can only see how many people
have created accounts, and nothing more.
It uses regular expressions to make sure the created usernames are
letters, numbers, and underscores, and that passwords contain at
least one lowercase letter, one uppercase letter, one number, and
one of these symbols: !@#$%^&*()
"""
def __init__(self):
"""Prompt user for username. If user chooses to make a new
username, 1/ allow user to input new username, 2/ check
whether new username is valid, 3/ create hash of username,
4/ accept password and check its validity, 5/ create hash of
password, 6/ write hash to hashes.archive file. If user
wishes to login using an existing username/password, hash
the username input by the user, and check it with each line
in the hashes.archive file. If it is not found, "user not
found" is output to the screen. If the username hash is found,
the boolean "found" variable is toggled to True, and the user is
given three chances to enter the correct password. Each password
is hashed and compared to the hash found next to the hash of
the login name in the hashes.archive file.
"""
self.login_name = input(
"Login Name (Press Enter to create new user): ")
self.login_success = False
if not self.login_name:
self.login_name = input("\nEnter new login name: ")
while not self.is_valid_login(self.login_name):
self.login_name = input("\nEnter new login name: ")
self.login_hash = sha256(self.login_name.encode()).hexdigest()
self.pw_string = ""
while not self.is_valid_password(self.pw_string):
print("\nPassword must be 8 or more characters and contain at "
"least one of each of the following: \n\t -uppercase "
"letters \n\t -lowercase letters \n\t -numbers \n\t -one"
" or more of these symbols: !@#$%^&*()\n")
self.pw_string = getpass("Enter new password: ")
self.password_hash = sha256(self.pw_string.encode()).hexdigest()
with open('hashes.archive', 'a') as self.password_file:
self.password_file.write(
f"login hash: {self.login_hash} : "
f"password hash: {self.password_hash}\n")
try:
with open('hashes.archive', 'r') as self.password_file:
self.found = False
for line in self.password_file:
login_entry_line = line.split(':')
if login_entry_line[1].strip() == sha256(
self.login_name.encode()).hexdigest():
print(f"Hello {self.login_name}")
self.found = True
break
if not self.found:
print("Login name not found.")
if self.found:
self.password_tries = 0
while self.password_tries < 3:
if (sha256(getpass(
"Enter your password: "
).encode())).hexdigest() == \
login_entry_line[3].strip():
print("Congrats, you remembered your password.\n")
self.login_success = True
break
else:
self.password_tries += 1
print(f"Wrong password. {3 - self.password_tries}"
" more tries\n")
except FileNotFoundError as err:
print("\nNo hashes.archive file was found because you haven't "
"made your first account yet. When that happens, a file "
"will be created called hashes.archive to store username & "
"password hashes (not the usernames and passwords "
"themselves).\n")
def is_valid_login(self, login_string):
"""Use regular expressions to check the validity of a new
username.
"""
if re.match('^[a-zA-Z0-9_]+$', login_string):
return True
else:
print("\nLogin names must be only letters, numbers, or _\n")
return False
def is_valid_password(self, pw_string):
"""Use regular expressions to check validity of new password."""
if (8 <= len(pw_string) < 256) and re.match(
'^[a-zA-Z0-9!@#$%^&*()]+$', pw_string) and re.search(
'[a-z]', pw_string) and re.search(
'[A-Z]', pw_string) and re.search(
'[0-9]', pw_string) and re.search(
'[!@#$%^&*()]', pw_string):
return True
else:
return False
def successful_login(self):
"""Return True or False depending on whether login was
successful.
"""
return self.login_success
if __name__ == '__main__':
sesh = LoginSession()
|
d16500e000f0208292921659b90472036e9aa0de | sudheemujum/Python-3 | /Print_All_Prime_numbers.py | 319 | 4.09375 | 4 | n=int(input('Please enter the number:'))
if n<=1:
print('entered number is not prime')
else:
n1=2
while n1<=n:
is_prime=True
for i in range(2,n1):
if n1%i==0:
is_prime==False
break
if is_prime==True:
print(n1)
n1+=1
|
42cd57ec608346cf420351e7b1b2339458947f8b | aldob02/York-Summer-Camp-Python | /Python II/oop_isometry.py | 1,639 | 4.125 | 4 | import turtle
import math
turtle.speed(0)
# create and draw Box objects with:
# >>> box1 = Box(0, 0, 0)
# >>> box2 = Box(0, 0, 1)
# >>> box3 = Box(1, 1, 0)
# >>> box1.draw()
# >>> box2.draw()
# >>> box3.draw()
class Box:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return "Box at (" + str(self.x) + ", " + str(self.y) + ", " + str(self.z) + ")"
def get2DCoords(self):
x2D = 87*self.x - 87*self.y
y2D = 100*self.z - 50*self.x - 50*self.y
return (x2D, y2D)
def draw(self):
(x, y) = self.get2DCoords()
turtle.penup()
turtle.setpos(x, y)
turtle.pendown()
turtle.color("red")
turtle.begin_fill()
turtle.setpos(x+87, y+50)
turtle.setpos(x+87, y+150)
turtle.setpos(x, y+100)
turtle.setpos(x, y)
turtle.end_fill()
turtle.color("blue")
turtle.begin_fill()
turtle.setpos(x-87, y+50)
turtle.setpos(x-87, y+150)
turtle.setpos(x, y+100)
turtle.setpos(x, y)
turtle.end_fill()
turtle.penup()
turtle.setpos(x, y+100)
turtle.pendown()
turtle.color("green")
turtle.begin_fill()
turtle.setpos(x+87, y+150)
turtle.setpos(x, y+200)
turtle.setpos(x-87, y+150)
turtle.setpos(x, y+100)
turtle.end_fill()
lst = []
for i in range(6):
lst.append(Box(0, i, 2*i))
print(lst[i])
for box in lst:
box.draw() |
88f9c9f08979e1aa3ee2c9969885c93998eb4bba | chriszhangm/Scrap_python | /MyFirstScrapy-.py | 6,192 | 3.546875 | 4 |
# coding: utf-8
# # Make more money by buying lottery?
# ## --- (Python Crawler+Data Analysis)
# ## Introduction
#
# **In this report, I will extract 100 pages of '3d' lottery data from http://www.zhcw.com to see if there is any strategy to make more money by buying the lottery. '3d' lottery is one of the favorite lottery game in China. People can choose 3 numbers from 000 to 999 and wait for one winning numbers. Firstly, let's see the data structure: we have Date(One time per day), period, winning numbers, sale amount and reward ratio.**
# 
# ## Get the Data
#
# **By analyzing the web source code, and using the 'Requests' package, 'Xpath' method to get the lottery data from 2013 to current date.**
# In[1]:
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} #Simulate the browser, keep-alive to make the process
url = 'http://kaijiang.zhcw.com/zhcw/html/3d/list_1.html'
response = requests.get(url = url,headers = headers)
print(response)
# **Code '200' means that the we can successfully extract the data.**
# In[2]:
response_default = requests.get(url = url)
print(response_default.request.headers)
# **The code is not always equal 200 because some website did not allow the python to extract the information. Thus, we need change our heaeders sometimes to make the website always know that it is not the robot(python) to extract the data.**
# In[3]:
response.request.headers
# In[4]:
from lxml import etree
# In[5]:
res_xpath = etree.HTML(response.text) #turn html to xpath structure
# In[6]:
print(res_xpath.xpath('/html/body/table//tr[3]/td[2]/text()'))
# In[7]:
trs = res_xpath.xpath('/html/body/table//tr')
# **trs will have 20 elements to be stored because there are 20 items shown in one page.**
# In[8]:
print(trs)
# ## Write the data into Excel
# In[9]:
import xlwt
# In[10]:
#create one working sheet
f = xlwt.Workbook()
# In[11]:
lotto = f.add_sheet('lottery',cell_overwrite_ok=True)
# In[12]:
#header in excel
row = ['Date','Period','number1','number2','number3','sale_amount','reward ratio']
for i in range(0,len(row)):
lotto.write(0,i,row[i])
# In[ ]:
#We need to scrap more data so we need different url and same process above.(I plan to get 100 pages of lottery info)
#we have already opened a xls file and have it headers.
# In[13]:
j = 1
for i in range(1,101):
url = 'http://kaijiang.zhcw.com/zhcw/html/3d/list_{}.html'.format(i)
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
response = requests.get(url = url,headers = headers)
res_xpath = etree.HTML(response.text)
trs = res_xpath.xpath('/html/body/table//tr')
for tr in trs[2:-1]:
lotto.write(j,0,tr.xpath('./td[1]/text()'))
lotto.write(j,1,tr.xpath('./td[2]/text()'))
lotto.write(j,2,tr.xpath('./td[3]/em[1]/text()'))
lotto.write(j,3,tr.xpath('./td[3]/em[2]/text()'))
lotto.write(j,4,tr.xpath('./td[3]/em[3]/text()'))
lotto.write(j,5,tr.xpath('./td[7]/strong[1]/text()'))
lotto.write(j,6,tr.xpath('./td[8]/text()'))
j += 1
# In[14]:
f.save('lotto.xls')
# **Now,we have our xls file to store 2000 lottery data (2000 days)**
# ## Analyze the data
# In[15]:
import pandas as pd
# In[16]:
data = pd.read_csv('lotto.csv')
# In[17]:
data.head()
# In[18]:
data.info() #there is no missing value to be imputed
# In[19]:
#visualization
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# **from the data, the there is no significant correlation between winning numbers and orders.**
# In[20]:
figsize = 18,4
fig = plt.figure(figsize=figsize)
ax1 = fig.add_subplot(1,3,1)
ax1.hist(data['number1'])
ax1.set_title('number1')
ax2 = fig.add_subplot(1,3,2)
ax2.hist(data['number2'],color='green')
ax2.set_title('number2')
ax3 = fig.add_subplot(1,3,3)
ax3.hist(data['number3'],color='pink')
ax3.set_title('number3')
# **Next I will examine whether the company will prefer any specific number**
# In[21]:
li1 = []
for i in range(2,5):
for j in data.iloc[:,i]:
li1.append(j)
# In[22]:
#plt.hist(li1,orientation='horizontal')
for i in range(10):
print('number',i,':',li1.count(i))
# **it seems number 3 7 8 is more likely to be chosen, next I will find the relationship between numbers and date.**
# In[23]:
li2 = []
for i in range(0,2000):
li2.append(pd.to_datetime(data.iloc[i,0]).weekday()+1)
# In[24]:
data['DayoftheWeek'] = li2
# In[25]:
data.head() #1:Monday,2:Thuesday..7:Sunday
# In[26]:
data[data['DayoftheWeek']==1].head()
# In[27]:
#set the function to count each number in every day of the week
def countday(data):
li1 = []
for i in range(2,5):
for j in data.iloc[:,i]:
li1.append(j)
for i in range(10):
print('number',i,':',li1.count(i),' probability:',round(li1.count(i)/len(li1),3))
# In[28]:
countday(data[data['DayoftheWeek']==1])
# ## Conclusion
#
# **After checking every date, I make a table for chossing the best 3 numbers for each day of the week, which is the most likely numbers in that day based on these 5 years dataset. However, this strategy may not the best one to use, and we need combine more data to consider. We cannot use lottery to earn money even we have better strategy because, actually, each number will have eventually same probability (1/10) to be picked, and we should just have fun playing it.**
# In[29]:
from prettytable import PrettyTable
x= PrettyTable(["Day of Week", "number1", 'number2','number3'])
x.add_row(['Monday',7,8,9])
x.add_row(["Thuesday",4,6,8])
x.add_row(["Wednesday",3,5,8])
x.add_row(["Thursday",1,3,8])
x.add_row(["Friday",3,6,8])
x.add_row(["Saturday",1,7,0])
x.add_row(["Sunday",1,0,7])
print(x)
|
00789e1ed7647672b7557232be77e7db1b9ad5e7 | holim0/Algo_Study | /python/네트워크.py | 544 | 3.546875 | 4 | from collections import deque
def solution(n, computers):
answer = 0
size = len(computers)
check = [False for _ in range(size)]
q = deque([])
for i in range(size):
if not check[i]:
check[i] = True
answer += 1
q.append(i)
while q:
cur = q.popleft()
for j in range(size):
if computers[cur][j] == 1 and not check[j]:
check[j] = True
q.append(j)
return answer
|
2f3554616019c8e21f1f8ae2bc08758ee44c5cd8 | fernandorssa/CeV_Python_Exercises | /Desafio 25.py | 481 | 3.890625 | 4 | print('Método 3')
nome = str(input('Digite o seu nome completo: ')).lower().strip()
x = str('silva' in nome)
print('Seu nome tem "Silva"?')
print(x)
'''
MÉTODO 1
n = str(input('Digite o seu nome completo: '))
a = int(n.count('Silva'))
print('Vejamos...')
if a >= 1:
print('Seu nome tem Silva')
else:
print('Seu nome não tem Silva')
MÉTODO 2
n = str(input('Digite o seu nome completo: ')).strip()
print('Seu nome tem Silva? {}'.format('silva' in nome.lower()))
'''
|
786f2d3b7bf35f6a0e2d697ec705102532338cbd | idahopotato1/learn-python | /01-Basics/007-Files/Files.py | 753 | 4.3125 | 4 | # Files
# When you're working with Python, you don't need to
# import a library in order to read and write files. ...
# When you use the open function, it returns something called a
# file object. File objects contain methods and attributes that can
# be used to collect information about the file you opened.
file = open('some-text')
print(file.read()) # Hey Assad how are you ? Hey Jawad how are you ?
print(file.read()) #
file.seek(0) #
print(file.read()) # Hey Assad how are you ? Hey Jawad how are you ?
file.seek(0)
print(file.readlines()) # ['Hey Assad how are you ?\n', 'Hey Jawad how are you ?']
print('=============================================================================')
for line in open('some-text'):
print(line) |
7946fd0c2e6364a4600f5fad2e5c22bd017b4156 | PPinto22/LeetCode | /codejam/2022 Qualification Round/a.py | 532 | 3.515625 | 4 | def print_punch_card(rows, columns):
print('..+' + '-+' * (columns - 1))
print('..|' + '.|' * (columns - 1))
print('+-+' + '-+' * (columns - 1))
for _ in range(rows - 1):
print('|.|' + '.|' * (columns - 1))
print('+-+' + '-+' * (columns - 1))
def main():
n_test_cases = int(input())
for case_i in range(1, n_test_cases + 1):
rows, columns = map(int, input().split())
print(f'Case #{case_i}:')
print_punch_card(rows, columns)
if __name__ == '__main__':
main()
|
758fdbdd558d0052fd00f71691e728e62fae0abb | vincentliao/euler_project | /largest_palindrome_product.py | 515 | 3.9375 | 4 | #! /usr/bin/env python
# description : Euler project, problem 4: Largest palindrome product
# author : vincentliao
# date : 20140503
from itertools import product
# palindromic number is like 121, 9009, etc....
def is_palindromic(number):
number_str = str(number)
return True if number_str == number_str[::-1] else False
candidate = []
for num1, num2 in product(range(999, 99, -1), range(999, 99, -1)):
p = num1 * num2
if is_palindromic(p) == True:
candidate.append(p)
print max(candidate)
|
986294475b2aa78b1864329448c784edaf6d601b | suraphel/RSA-file-encryptor- | /padding&grouping.py | 947 | 3.875 | 4 | # This is the padding and the division part of the code
# taking the user input
def padding ( read, calculate, padd):
read.read()
return len(read)
def odd(x):
if x % 2 == 0:
return("odd")
else:
return ("even")
p_text = input ("what would like to send\n")
p_to_file = open("p_txt_container","a")
#p_to_file.write(" this is a trail")
p_to_file.write(p_text)
p_to_file.close()
#This is the reading part +++++++++++++++++++++++++
read_file = open("p_txt_container" , "r")
containent = read_file.read()
read_file.close
# here we will do some division and padding if needed!==================
print ("this is some thing and we are not sure what will happen\n")
print (containent)
quantity = len (containent)
if quantity > 0:
for quantity is odd:
else:
even
#open("p_txt_container","a")
#p_to_file.write("x")
#p_to_file.close()
print(quantity)
|
6c3191d475a852514339007fa7db66833bb82fce | MohammadRezaHassani/HomeWorks | /HW1/8.py | 143 | 3.953125 | 4 | number = int(input())
for i in range(1,number*2):
if i <=number:
print("*" * i)
else:
print("*" * (number*2 -i))
|
5e67254d5b691ff51a3cc8eb6e01d5ba823b1094 | kwoodson/euler | /python/euler20.py | 237 | 4.0625 | 4 | #!/usr/bin/env python
'''
n! means n x (n - 1) x ... x 3 x 2 x 1
Find the sum of the digits in the number 100!
'''
def fact(x):
return (1 if x==0 else x * fact(x-1))
astring = str(fact(100))
print sum([int(x) for x in astring])
|
2849c314dbcd2b006c995e9fbdefd8eab7d00517 | kaliskamila/zadanie-domowe-ci-g-fibo | /03_python/zadanie1.py | 241 | 3.78125 | 4 | for i in range (1,101):
pass
if i % 15 == 0:
print(i, "FizzBuzz")
if i % 3 == 0:
print(i, "Fizz")
if i % 5 == 0:
print(i, "Buzz")
else:
print(i)
for i in range (1,101):
pass
if i % 15 == 0 and i %5 != 0:
|
1dcc63e47abbd9feaf8502493bbe1324f67579fa | nikitauday/EXERCISM_WORKSPACE | /python/robot-name/robot-name.py | 472 | 4.1875 | 4 | import string
import random
unique=set()
X=input("Generate name? Y/N ")
while True :
if(X=='Y'or X=='y'):
while True:
A=(''.join(random.choice(string.ascii_uppercase) for _ in range(2)))+(''.join(random.choice(string.digits) for _ in range(3)))
if A not in unique:
unique.add(A)
break
print(A)
X=input("Generate name? Y/N ")
elif(X=='N' or X=='n'):
print(unique)
break
else:
print("Wrong input press Y to continue and N for exit")
X=input()
|
edd994acb8281c11f430d85244a8d773315f7ca4 | Ekultek/codecademy | /Introduction To Classes/02 Classes/4.py | 497 | 4.375 | 4 | """
Description:
Calling class member variables
Each class object we create has its own set of member variables. Since we've created an object my_car that is an
instance of the Car class, my_car should already have a member variable named condition. This attribute gets assigned
a value as soon as my_car is created.
Challenge:
At the end of your code, use a print statement to display the condition of my_car.
"""
class Car(object):
condition = "new"
my_car = Car()
print my_car.condition |
089b9fe56c2706b3ea52bf782b27d976e763ffb5 | buptxiaomiao/python | /study_program/guess_num.py | 296 | 3.984375 | 4 | #!/usr/bin/env python2.7
true_num = 88
guess_num = int(raw_input("\nInput the number:"))
if guess_num > true_num:
print "Sorry,It's lower than that... \n"
elif guess_num < true_num:
print "Sorry,It's higher than that...\n"
else:
print "Amazing, You guessed it.\n"
print "Game will exit:)"
|
8109140783f2fed266b5dcccf8b56f3df7fbdbe5 | vijayjag-repo/LeetCode | /Python/LC_Binary_Tree_Level_Order_Traversal.py | 2,574 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Two solutions to this problem
# Solution 1:
# if the length of the list is equal to the level, then create a new [] and append this value and store it at index=level
# Example: If root.val==3, level=0, len(levels)==0, then, levels=[[3]]
# Simlarly, if root.val has a left and right, then their level is 1 greater than root's level.
# Therefore, level=1,len(levels)=1 (since root was added), root.left.val is added at index=1=level
# Since this is a recursive process, all left node values are added to their respective indexes.
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
levels = []
if not root:
return(levels)
def helper(root,level):
if(len(levels)==level):
levels.append([])
levels[level].append(root.val)
if(root.left):
helper(root.left,level+1)
if(root.right):
helper(root.right,level+1)
helper(root,0)
return(levels)
- - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - -
# Solution 2:
# level = [root] ----> initialise level with root
# while(level exists):
# current level = [], child_level = []
# for each item in level:
# append its value to the current level. If the current item has a child, append it to the child level.
# append all values in the current level to the ans.
# now, since this level is done, we proceed to the next level which is the child level.
# This can be done by setting level = child and the same process continues.
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return(None)
ans = []
level = [root]
while(level):
current = []
child = []
for node in level:
current.append(node.val)
if(node.left):
child.append(node.left)
if(node.right):
child.append(node.right)
ans.append(current)
level = child
return(ans)
|
16b1cac1abfe5919ba290dca0fc87e5ff931d408 | zabojnikp/study | /Python_Projects/hackathon_Brno/warm-up/6_souhlasky_samohlasky.py | 388 | 3.78125 | 4 | user_input = 'a speech sound that is produced by comparatively open configuration of the vocal tract'
raw_text = user_input.replace(" ", '')
vowels = []
consonants = []
sentence = {}
for i in raw_text:
if i.lower() in "aeiouy":
vowels.append(i)
else:
consonants.append(i)
sentence["vowels"] = len(vowels)
sentence['consonants'] = len(consonants)
print(sentence) |
4e9c215ebbb4bfd02859d3e888e307d980b444dc | NMOT/PycharmProjects1 | /python_desafios/ex_14_62.py | 402 | 3.96875 | 4 |
# Permita que o usuário escolha quantos termos da progressão quer mostrar
#saia do programa quando o usuário disser que quer calcular mais 0 termos
i = 1
n = int(input('Introduza o 1º termo da progressão aritmética.'))
r = int(input('Introduza a razão da progressão '))
f = int(input('Quantos termos da progressão quer calcular?'))
while i < f+1:
print(n + (i - 1) * r)
i += 1
|
e9ffc4b98b05ce7ef499e9c42ec22bc892576f4b | KataBedn/AutomatedTestingExercise | /utilities/dataGenerator.py | 404 | 3.625 | 4 | import random, string
class DataGenerator:
@staticmethod
def generate_random_number_with_n_digits(n) -> int:
lower = 10 ** (n - 1)
upper = 10 ** n - 1
return random.randint(lower, upper)
@staticmethod
def generate_random_string(length=10, chars=string.ascii_uppercase + string.digits) -> str:
return ''.join(random.choice(chars) for _ in range(length)) |
c70140b109ebcebb11e256a0d57196d5ae015258 | luiscristerna/PruebaTravis | /Calculadora.py | 1,693 | 3.53125 | 4 | # Luis Manuel Cristerna Gallegos 05/09/2017
# Implementando CI con travis
#pruebas
import math
class Calculadora():
def __init__(self):
self.resultado = 0
def obtener_resultado(self):
return self.resultado
def suma(self, num1, num2):
try:
self.resultado = num1 + num2
except:
self.resultado = "Datos Incorrectos"
def resta(self, num1, num2):
try:
self.resultado = num1 - num2
except:
self.resultado = "Datos Incorrectos"
def multiplicacion(self, num1, num2):
self.resultado = num1 * num2
try:
self.resultado = num1 * num2
except:
self.resultado = "Datos Incorrectos"
def division(self, num1, num2):
try:
if(num2 == 0):
self.resultado = 'No se puede divir entre cero'
else:
self.resultado = num1 / num2
except:
self.resultado = 'Datos Incorrectos'
def potencia(self, num1, num2):
try:
if(num2 == 0):
self.resultado = 'Numero elevado a la potencia cero es uno'
else:
self.resultado = num1 ** num2
except:
self.resultado = 'Datos Incorrectos'
def raiz(self, num1):
if(num1 < 0):
self.resultado = 'Error'
else:
self.resultado = math.sqrt(num1)
try:
if(num1 < 0):
self.resultado = 'Error'
else:
self.resultado = math.sqrt(num1)
except:
self.resultado = 'Datos incorrectos' |
3374d6414eec6480a8803b54ea0b35dd7c2c2b85 | ramonvaleriano/python- | /Livros/Introdução à Programação - 500 Algoritmos resolvidos/Capitulo 6/Exercicios 6a/Algoritmo479_fun21.py | 377 | 4 | 4 | # Program: Algoritmo479_fun21.py
# Author: Ramon R. Valeriano
# Description:
# Developed: 09/06/2020 - 16:48
# Updated:
from arranjo import *
number1 = int(input("Entre com o primeiro número: "))
number2 = int(input("Entre com o segundo número: "))
number3 = int(input("Entre com o terceiro número: "))
print(formula2(numerador, denominador, number1, number2, number3, test, test2))
|
7c0e1edabfe7f36f17df0a35b16edbd87c5e7024 | Seungjin22/TIL | /00_StartCamp/02_Day/00_string_format.py | 805 | 3.671875 | 4 | #1. pyformat
# name = '홍길동'
# english_name = 'hong'
# print('안녕하세요, {}입니다. My name is {}'.format(name, english_name))
# print('안녕하세요, {1}입니다. My name is {0}'.format(name, english_name))
# print('안녕하세요, {1}입니다. My name is {1}'.format(name, english_name))
#2. f-strings
# name = '홍길동'
# print(f'안녕하세요, {name}입니다.')
# print('안녕하세요,', name, '입니다.')
# import random
# menu = ['김밥천구', '별별벅스', '흥부부대찌개']
# lunch = random.choice(menu)
# print('오늘의 점신은 {}입니다.'.format(lunch))
# print(f'오늘의 점심은 {lunch}입니다.')
import random
numbers = list(range(1, 46))
lotto = random.sample(numbers, 6)
print(f'오늘의 행운 번호는 {sorted(lotto)}입니다.') |
df512b58cf9ab2da0e597aebafe4ab4e616a5487 | pony-ai/PythonDaily | /1.4/list_1.py | 663 | 4.1875 | 4 | #遍历列表
# magicians = ['liu','xue','xiao']
# for magician in magicians:
# # print(magician)
# print(f"{magician.title()},that was a great trick.")
#创建数值列表
# numbers = list(range(1,6))
# print(numbers)
#打印1-10的平方数
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
# 简单运算
# print('最大值为',max(squares))
# print('最小值为',min(squares))
# print('数组和为',sum(squares))
# 立方解析
# squares = [value**3 for value in range(1,11)]
# print(squares)
# 切片
# print(squares[0:2])
# print(squares[-3:])
# 遍历切片
# for value in squares[3:]:
# print(value) |
95273e87935d258d72b52bf7ade08a69fd719779 | dreamer-1996/learning-python-total-novice | /hello.py | 251 | 3.9375 | 4 | # My first python program
print ("Welcome to the world of programming")
print ("Please enter your name")
myName = input()
print ('Hello ' + myName)
print ("What is your age?")
myAge = input()
print ("You will be " + str(int(myAge)+1) + " next year")
|
4c666cbb5e26d9faf04e78427dd64e2fa60dfcc3 | nolan-gutierrez/ReinforcementLearning | /MAB/GridVisual.py | 1,574 | 3.640625 | 4 | class GridVisual:
def __init__(self,
gridWorld,
):
self.gridWorld = gridWorld
def getAgentVisual(self):
_,_,o = self.gridWorld.getAgentPose()
if o == 'up': return 'u'
elif o == 'down':return 'd'
elif o == 'left': return 'l'
elif o == 'right': return 'r'
else: return 'y'
def showWorld(self):
obstacles = self.gridWorld.getObstacles()
agentPose = self.gridWorld.getAgentPose()
x1,y1,_ = agentPose
goal = self.gridWorld.getGoal()
h,w = self.gridWorld.getHW()
agent = self.getAgentVisual()
for y in range(h,0, -1):
for x in range(1,w + 1):
if (x,y) == (x1,y1) :
print("", agent, end = " ")
elif (x,y) == goal:
print("",'g', end = " ")
elif (x,y) in obstacles:
print("",'o', end = " ")
elif x <= 1 or x >= w:
print(" b", end = " ")
elif y <= 1 or y >= h:
print(" b", end = " ")
else: print(" ", end = " ")
print("")
def getActionMenu(self):
return "\nw: forward \n d: turn right \n s: backward \n a: turn left \n "
def getAction(self, action):
if action == 'w': return 'f'
elif action == 's': return 'b'
elif action == 'd': return 'r'
elif action == 'a': return 'l'
else:
print("Invalid Action, going Forward")
return 'f'
|
ac1c2b9fb9e8aab19a8a2c1b300799da420df6c3 | Kamilet/learning-coding | /simple-program/check-io-solutions/digits-multiplication.py | 986 | 4.03125 | 4 | '''
You are given a positive integer. Your function should calculate the product of the digits excluding any zeroes.
For example: The number given is 123405. The result will be 1*2*3*4*5=120 (don't forget to exclude zeroes).
'''
from functools import reduce # for method 2
def checkio(number):
#method 1
number = str(number)
result = 1
for i in range(len(number)):
if number[i] != '0':
result *= int(number[i])
return result
#method 2 like this
#forget it
#reduce(lambda x,y:x+y,l)
'''
number = list(str(number))
print(reduce(lambda x,y: int(x)*int(y), number))
return 120
'''
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(123405) == 120
assert checkio(999) == 729
assert checkio(1000) == 1
assert checkio(1111) == 1
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
|
454622761e238faca0e199f728d3642192ca36dc | ShaneRich5/fti-programming-training | /solutions/labs/lab8.1/dealership/vehicle.py | 288 | 4 | 4 |
class Vehicle(object):
""" A vehicle for passenger transport """
wheels = 4
def __init__(self, year, make, model):
self.year = year
self.make = make
self.model = model
print("Vehicle: " + str(self.year) + " " + self.make + " " + self.model) |
e6c07258a419f1aec9ef74a063e47aa248d8568a | vanessalb08/learnignPython | /desafio063.py | 216 | 3.9375 | 4 | num = int(input('Quantos elementos quer ver? '))
termo = 0
soma = 1
cont = 1
fib = 0
while cont <= num:
fib = termo + soma
print(termo, end='➔ ')
soma = termo
termo = fib
cont += 1
print('Fim')
|
d8355b4a792a7dfa1638d6d327d560ad955580ca | mrmyothet/ipnd | /ProgrammingBasicWithPython-KCL/Chapter-6/Delete_Dictionary.py | 153 | 3.78125 | 4 | dict = {"Name":"Aung Ko","Age":7}
dict["Age"] = 9
del dict["Name"]
print("NAME:" + dict["Name"]) # you will get error...
print("Age:" + str(dict["Age"]))
|
b01bd3133de9b45e7a619f2ece581e08c01040e9 | fridriks98/Forritunarverkefni | /Python_projects1/Mímir verkefni/mimir_verkefni/strings and/verkefni4.py | 110 | 3.5 | 4 | s = input("Input a float: ")
s_float = float(s)
s_justified = "{:>12.2f}".format(s_float)
print(s_justified) |
db67bd319aee9e36817270c39de8457291a06585 | romanus77/python-course | /03_examples/00_file_read.py | 1,014 | 3.90625 | 4 | # -*- encoding: utf-8 -*-
# Открыть файл на чтение:
f = open("input_file.txt", "rt") #можно также открывать в бинарном режиме: "rb"
# Прочитать первые 10 символов из файла, `first10' --- строка:
first10 = f.read(10)
print "First 10 chars: '{0}'".format(first10)
# all_file = f.read() --- прочитает файл до конца в строку `all_file'
# Прочитать строку:
str2 = f.readline()
print "String: '{0}'".format(str2)
# all_strings = f.readlines() --- прочитает все строки и вернёт список строк
for line in f:
# Пройтись по всем оставшимся строкам файла.
# На каждой итерации в `line' будет очередная строка файла
print "Line: '{0}'".format(line)
# После окончания работы с файлом его необходимо закрыть:
f.close()
|
112f3f9d411caed6afea25fe75680fdad584fc59 | cmj123/MultiThreading_in_Python | /multithreading22.py | 1,145 | 3.75 | 4 | """
Name: Esuabom Dijemeni
Date: 22/03/2020
Purpose: Create a program where two consumer threads wait on the producer thread to notify them
"""
# Import key libraries
import threading
import logging
# Logging message for status tracking
logging.basicConfig( level=logging.DEBUG,
format='(%(threadName) -10s) %(message)s'
)
def consumer_thread(cond):
"""wait for the condition and use the resources"""
logging.debug('Starting consumer_thread thread')
t = threading.currentThread()
with cond:
cond.wait()
logging.debug('Resources is avaliable to consumer_thread')
def producer_thread(cond):
"""set up the resources """
logging.debug('Starting producer_thread thread')
with cond:
logging.debug('Making resources avaliable')
cond.notifyAll()
# Initialise threading condition
condition = threading.Condition()
c1 = threading.Thread(name='c1', target=consumer_thread, args=(condition, ))
c2 = threading.Thread(name='c2', target=consumer_thread, args=(condition, ))
p = threading.Thread(name='p', target=producer_thread, args=(condition, ))
c1.start()
c2.start()
p.start()
|
317df6c3cc587636f61450d331d343ca61278163 | pbednarski/programowanie-obiektowe-1 | /lab2_06.py | 361 | 4.15625 | 4 | def fiboncciGenerator(n):
numberslist = list(range(0, n))
for (i, number) in enumerate(numberslist):
if number > 1:
number = numberslist[i - 1] + numberslist[i - 2]
numberslist[i] = number
yield number
print('Set Fibonacci length:')
obj = fiboncciGenerator(int(input()))
seq = list(obj)
print(seq)
|
1a225d15a873c9038e9a037d8165877ac9e069a8 | nestoregon/learn | /advent_code/2020/day9.py | 2,329 | 3.609375 | 4 | import os
import sys
from collections import namedtuple
def part_1():
raw_input = []
with open('input9.txt') as fp:
for line in fp:
line.strip()
number = int(line)
raw_input.append(number)
for i in range(len(raw_input) - 25):
pack_25 = raw_input[i:i+25]
pack_25.sort()
target = raw_input[i+25]
# find if it can be the sum of two numbers
found = False
for number in pack_25:
to_find = target - number
if to_find in pack_25:
found = True
if found:
break
if found:
continue
print("hit")
print(target)
def part_2():
raw_input = []
invalid_n = 0
with open('input9.txt') as fp:
for line in fp:
line.strip()
number = int(line)
raw_input.append(number)
for i in range(len(raw_input) - 25):
pack_25 = raw_input[i:i+25]
pack_25.sort()
target = raw_input[i+25]
# find if it can be the sum of two numbers
found = False
for number in pack_25:
to_find = target - number
if to_find in pack_25:
found = True
if found:
break
if found:
continue
invalid_n = target
num1, num2 = 0, 0
final_pack = []
# find sum of invalid
for i in range(len(raw_input)):
# for every number
for j in range(len(raw_input)-i-1):
pack = raw_input[i:i+j+1]
s = 0
s = sum(pack)
if s == invalid_n:
pack.sort()
num1 = pack[0]
num2 = pack[-1]
final_pack = pack.copy()
if s > invalid_n:
break
if num1 > 0:
break
print("- num1:", num1)
print("- num2:", num2)
print("solution:", num1+num2)
if __name__ == "__main__":
try:
which_part = sys.argv[1]
if which_part == '1':
part_1()
elif which_part == '2':
part_2()
else:
print("arguments can only be 1 or 2")
except IndexError:
print("specify a part")
print("example:")
print("python3 dayX.py 2")
|
501f20e642042df9c2183603fc46b4f43170227e | dtobin02/assignments | /readwrite-csv.py | 406 | 3.578125 | 4 | import csv
# write csv
with open('testwrite.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(['col1', 'col2'])
writer.writerow(['val1', 'val2'])
writer.writerow(['val1', 'val2'])
writer.writerow(['val1', 'val2'])
# read csv
from pprint import pprint
with open('testwrite.csv', 'r') as f:
reader = csv.DictReader(f)
rows = list(reader)
for row in rows:
pprint(row) |
e43eae51777627410307326bdb8bd4518c21ee77 | vinay279/pythonLearningclasses | /AutomationPython/SortingAutomation.py | 4,287 | 3.78125 | 4 | '''Class for the Sorting Automation'''
import random
from SortingTypes import Bubble, Quick, Selection, Insertion, Radix, Merge
class SortingAutomation:
def __init__(self):
self.elements = []
# Inserting Elements in List
def inserting(self):
for value in range(10):
self.elements.append(random.randrange(1, 101))
print("Elements list for Sorting =", self.elements)
# Check the values in list and the length of list
def checkValuesAndLength(self, elements, sample):
if len(self.elements) == len(sample):
for i in range(len(self.elements)):
if self.elements[i] == sample[i]:
print("value are Equal in two list", self.elements[i], '=', sample[i])
else:
print("Elements are not equal sorting fail")
# for checking the total element list
if len(self.elements) == len(sample):
print("length of two sorted list is aso equal ")
print("Test case of Soring passed", '\n')
# for Clearing list
def clearlist(self):
self.elements.clear()
# checking the Bubble sorting
def checkBubbleSort(self):
print("****Test case for Checking Bubble Sort****")
self.clearlist()
self.inserting()
sample2 = self.elements
bObj = Bubble.BubbleSort()
bObj.BubbleSort(sample2)
# check bubble sort after comaparing with selection sort
csObj = Selection.Selection()
csObj.selectionSort(self.elements)
self.checkValuesAndLength(self.elements, sample2)
print('*' * 70)
def CheckSelectionSort(self):
print("****Test case for Checking Selection Sort****")
self.clearlist()
self.inserting()
sample2 = self.elements
bObje = Selection.Selection()
bObje.selectionSort(sample2)
# check bubble sort after comaparing with selection sort
buobj = Bubble.BubbleSort()
buobj.BubbleSort(self.elements)
self.checkValuesAndLength(self.elements,sample2)
print('*' * 70)
# for checking Quick sort is running
def checkQuickSort(self):
print("****Test case for Checking Quick Sort****")
self.clearlist()
self.inserting()
sample2 = self.elements
bobje = Selection.Selection()
bobje.selectionSort(sample2)
# check Quick sort after comaparing with selection sort
Qobj = Quick.QuickS()
Qobj.quickSort(self.elements)
self.checkValuesAndLength(self.elements, sample2)
print('*' * 70)
# for Radix sort
def checkRadixSort(self):
print("****Test case for Checking Radix Sort****")
self.clearlist()
self.inserting()
sample2 = self.elements
Qsobj = Quick.QuickS()
Qsobj.quickSort(self.elements)
# check Quick sort after comaparing with selection sort
Qobj = Radix.Radix()
Qobj.radixSort(self.elements)
self.checkValuesAndLength(self.elements, sample2)
# checking insertion sort
def checkingInsertionSort(self):
print("****Test case for Insertion Sort****")
self.clearlist()
self.inserting()
sample2 = self.elements
Robj = Radix.Radix()
Robj.radixSort(self.elements)
# check radix sort after comaparing with insertion sort
Qobj = Insertion.Insertion()
Qobj.insertionSort(self.elements)
self.checkValuesAndLength(self.elements, sample2)
print('*' * 70)
# checking the merge Sorting
def checkMergeSorting(self):
print("****Test case for Checking Merge Sort****")
self.clearlist()
self.inserting()
sample2 = self.elements
Robj = Radix.Radix()
Robj.radixSort(self.elements)
# check radix sort after comaparing with merge sort
Qobj = Merge.Merge()
Qobj.mergesort(self.elements)
print("Merge Sorted list = ", self.elements)
self.checkValuesAndLength(self.elements, sample2)
print('*' * 70)
obj = SortingAutomation()
obj.checkBubbleSort()
obj.CheckSelectionSort()
obj.checkQuickSort()
obj.checkRadixSort()
obj.checkingInsertionSort()
obj.checkMergeSorting() |
e552e5b34ef13214380152ee00db7edbbde6013a | MoritzWillig/GenieInAGanzzahlAddierer | /src/datatypes/CreationInfo.py | 881 | 3.546875 | 4 | from enum import Enum
class CreationInfo(Enum):
EXISTING = 0
RESERVE = 1
CREATE = 2
@staticmethod
def from_string(value_str):
value_str = value_str.lower()
if value_str == "existing":
return CreationInfo.EXISTING
elif value_str == "reserve":
return CreationInfo.RESERVE
elif value_str == "create":
return CreationInfo.CREATE
else:
raise ValueError("string does not represent an enum element")
@staticmethod
def to_string(creation_info):
if creation_info == CreationInfo.EXISTING:
return "existing"
elif creation_info == CreationInfo.RESERVE:
return "reserve"
elif creation_info == CreationInfo.CREATE:
return "create"
else:
raise ValueError("recived value is not an enum element") |
494dda9707c3e2b07c59db1b85e8c6a7757c754d | pvanh80/intro-to-programming | /round01/Smileys.py | 545 | 4.09375 | 4 | smiley = int(input('How do you feel? (1-10) '))
if smiley >= 1 and smiley <= 10:
if smiley == 10: print ("A suitable smiley would be :-D")
else:
if smiley >=8 and smiley<=9 : print("A suitable smiley would be :-)")
else:
if smiley >=3 and smiley <=7: print("A suitable smiley would be :-|")
else:
if smiley ==2: print("A suitable smiley would be :-(")
else :
if smiley ==1: print("A suitable smiley would be :'(")
else :
print("Bad input!")
|
d85680620a26c9e54b71f13342654cba4f40e597 | bpbpublications/Advance-Core-Python-Programming | /Chapter 08/Examples_Code/Example1_6.py | 950 | 4.4375 | 4 | #Example 14.6
#Write a program for two buttons one on the left and the other on the right. Try it out and match your results with the output given in the book.
#import Statements
from tkinter import*
import tkinter.messagebox
# Create a function for right button
def message_display_right():
tkinter.messagebox.showinfo("Next Topic","Welcome to Canvas")
# Create a function for right button
def message_display_left():
tkinter.messagebox.showinfo("Previous Topic","Welcome to Widgets")
#Create instance of window
mw = Tk()
mw.title("Select Topic")
#Create instance of a button
my_first_button = Button(mw,text="Next",fg="Green", command = message_display_right)
my_second_button = Button(mw,text="Previous",fg="Red", command = message_display_left)
#Adjust the position of buttons
my_first_button.pack(side = tkinter.RIGHT)
my_second_button.pack(side = tkinter.LEFT)
#call the mainloop()
mw.mainloop()
|
90628d2a5a1e90bf99cf779d5c5a542f523c402b | hongyesuifeng/python-algorithm | /python-offer/question4.py | 708 | 4.03125 | 4 | def find_in_matrix(matrix,number):
"""二维数组中的查找"""
if matrix:
rows = len(matrix)
columns = len(matrix[0])
row = 0
while(matrix and row<rows and columns>0):
if matrix[row][columns-1] == number:
return number
elif matrix[row][columns-1] > number:
columns = columns - 1
elif matrix[row][columns-1] < number:
row = row + 1
return False
if __name__ == "__main__":
matrix1 = [[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
matrix2 = None
print(find_in_matrix(matrix1,7))
print(find_in_matrix(matrix1,5))
print(find_in_matrix(matrix2,5))
|
f30b5662175b3aaec872237a7fbd9cf92ab80b8b | HarryChen1995/data_structure_algorithm | /3Sum.py | 896 | 3.640625 | 4 | def threeSum(nums):
nums.sort()
arr = []
for i in range(0, len(nums)-2):
if (i == 0 or (i> 0 and nums[i] != nums[i-1])):
low = i+1
high = len(nums)-1
sum = 0 - nums[i]
while low < high:
if nums[low]+nums[high] == sum :
arr.append([nums[i], nums[low], nums[high]])
while(low<high and nums[low] == nums[low+1]):
low +=1
while (low< high and nums[high] == nums[high-1]):
high -=1
low +=1
high -=1
elif nums[low] + nums[high] > sum:
high -=1
else:
low +=1
|
1aaea78327f56b2bb7707f19a42fa77159ff0090 | RoiSadon/python | /06_Class & instance & constructors/09_oop subclass.py | 394 | 3.890625 | 4 |
class schoolMember:
def __init__(self,name):
self.name=name
def tell(self):
print('hi school member:', self.name,end=" ")
# If subclass does not contain a constructor
# The subclass will have a default call to the base constructor
class Teacher(schoolMember):
def tell(self):
schoolMember.tell(self)
print('and teacher')
m=Teacher('Raya')
m.tell() |
60d8467b566ad3c2c760242125d7383a0e8eb156 | bermmie1000/lselectric_dtc | /Lotto generator/ball.py | 651 | 3.734375 | 4 | # 로또 번호 제조기 입니다 ㅎㅎ
# 자, 부자가 되어 봅시다.
import random
class ball:
def __init__(self):
number = random.randint(1, 45)
self.number = number
if __name__ == "__main__":
games = 5
for game in enumerate(range(games)):
container = []
first_ball = ball().number
container.append(first_ball)
while len(container) != 6:
next_ball = ball().number
if next_ball not in container:
container.append(next_ball)
else:
pass
print(sorted(container))
|
6e98a09967265031b4b8355868a5883613592236 | Chaitanya-NK/ML-MINOT-JUNE | /ML-MINOR-JUNE.py | 8,430 | 3.703125 | 4 | #!/usr/bin/env python
# coding: utf-8
# Problem Statement:
#
# gender : Gender of the student.....
# race/ethnicity : Race of the Student As Group A/B/C......
# parental level of education : What is the education Qualification of Students Parent.......
# lunch : Whether the lunch is Standard type/Free lunch or Some discounted lunch.....
# test preparation course : Whether Student has Taken or not and Completed.....
# math score : Scores in Maths....
# reading score : Scores in Reading.....
# writing score : Scores in Writing.....
#
# Objective of this Analysis:
# To understand the how the student's performance (test scores) is affected by the other variables (Gender, Ethnicity, Parental level of education, Lunch, Test preparation course).
# What to do in Exploratory Data Analysis:
# To Analyse insights in the dataset.
# To understand the connection between the variables and to uncover the underlying structure
# To extract the important Variables.
# To test the underlying assumptions.
# Provide Insights with Suitable Graphs and Visualizations.
# Write all your inferences with supporting Analysis and Visualizations.
# In[47]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
for dirname, _, filenames in os.walk('//input'):
for filename in filenames:
print(os.path.join(dirname, filename))
# In[48]:
df=pd.read_csv('StudentsPerformance (1).csv')
# In[49]:
df.describe()
# In[50]:
df.shape
# In[51]:
df.isnull().sum()
# In[52]:
plt.rcParams['figure.figsize'] = {20, 30}
sns.countplot(df['math score'], palette = 'dark')
plt.title('Math Score',fontsize = 20)
plt.show()
# In[39]:
plt.rcParams['figure.figsize'] = {20, 30}
sns.countplot(df['reading score'], palette = 'Set3')
plt.title('Reading Score',fontsize = 20)
plt.show()
# In[40]:
plt.rcParams['figure.figsize'] = {20, 30}
sns.countplot(df['writing score'], palette = 'prism')
plt.title('Writing Score',fontsize = 20)
plt.show()
# In[9]:
plt.figure(figsize=(15,5))
plt.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=0.5, hspace=0.2)
plt.subplot(141)
plt.title('Math Scores')
sns.violinplot(y='math score',data=df,color='m',linewidth=2)
plt.subplot(142)
plt.title('Reading Scores')
sns.violinplot(y='reading score',data=df,color='g',linewidth=2)
plt.subplot(143)
plt.title('Writing Scores')
sns.violinplot(y='writing score',data=df,color='r',linewidth=2)
plt.show()
# In[10]:
plt.figure(figsize=(20,10))
plt.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=0.5, hspace=0.2)
plt.subplot(141)
plt.title('Gender',fontsize =20)
df['gender'].value_counts().plot.pie(autopct='%1.1f%%')
plt.subplot(142)
plt.title('Ethnicity',fontsize =20)
df['race/ethnicity'].value_counts().plot.pie(autopct='%1.1f%%')
plt.subplot(143)
plt.title('Lunch',fontsize =20)
df['lunch'].value_counts().plot.pie(autopct='%1.1f%%')
plt.subplot(144)
plt.title('Test Preparation Course',fontsize =20)
df['test preparation course'].value_counts().plot.pie(autopct='%1.1f%%')
plt.show()
# In[11]:
plt.figure(figsize=(10,5))
plt.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=0.5, hspace=0.2)
plt.subplot(131)
plt.title('Math Scores')
sns.barplot(x='gender', y='math score', data=df)
plt.subplot(132)
plt.title('Reading Scores')
sns.barplot(x='gender', y='reading score', data=df)
plt.subplot(133)
plt.title('Writing Scores')
sns.barplot(x='gender', y='writing score', data=df)
plt.show()
# In[12]:
plt.figure(figsize=(25,20))
plt.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=0.5, hspace=0.2)
plt.subplot(251)
plt.title('Test Preparation Course vs Gender', fontsize = 10)
sns.countplot(hue='test preparation course', x='gender', data=df)
plt.subplot(252)
plt.title('Test Preparation Course vs Ethnicity', fontsize = 10)
sns.countplot(hue='test preparation course', y='race/ethnicity', data=df)
plt.subplot(253)
plt.title('Test Preparation Course vs Lunch', fontsize = 10)
sns.countplot(hue='test preparation course', x='lunch', data=df)
plt.subplot(254)
plt.title('Test Preparation Course vs Parental Level of Education', fontsize = 10)
sns.countplot(hue='test preparation course', y='parental level of education', data=df)
plt.show()
# In[13]:
plt.figure(figsize=(20,10))
plt.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=0.5, hspace=0.2)
plt.subplot(131)
plt.title('Math Scores')
sns.barplot(x='test preparation course', y='math score', data=df)
plt.subplot(132)
plt.title('Reading Scores')
sns.barplot(x='test preparation course', y='reading score', data=df)
plt.subplot(133)
plt.title('Writing Scores')
sns.barplot(x='test preparation course', y='writing score', data=df)
plt.show()
# In[14]:
plt.figure(figsize=(20,10))
plt.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=0.5, hspace=0.2)
plt.subplot(131)
plt.title('Math Scores vs Ethnicity')
sns.barplot(x='race/ethnicity', y='math score', data=df)
plt.subplot(132)
plt.title('Reading Scores vs Ethnicity')
sns.barplot(x='race/ethnicity', y='reading score', data=df)
plt.subplot(133)
plt.title('Writing Scores vs Ethnicity')
sns.barplot(x='race/ethnicity', y='writing score', data=df)
plt.show()
# In[15]:
plt.title('Gender vs Ethnicity',fontsize = 20)
sns.countplot(x='gender', hue='race/ethnicity', data=df)
plt.show()
# In[16]:
pr=pd.crosstab(df['race/ethnicity'],df['parental level of education'],normalize=1)
pr.plot.bar(stacked=True)
plt.title('Ethnicity vs Parental Level of Education',fontsize = 20)
plt.show()
# In[17]:
plt.figure(figsize=(40,10))
plt.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=0.5, hspace=0.2)
plt.subplot(251)
plt.title('Parental Education and Gender', fontsize=15)
sns.countplot(x='gender', hue='parental level of education', data=df)
plt.subplot(252)
plt.title('Parental Education and Lunch', fontsize=15)
sns.countplot(x='lunch', hue='parental level of education', data=df)
plt.show()
# In[18]:
plt.figure(figsize=(40,10))
plt.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=0.5, hspace=0.2)
plt.subplot(251)
plt.title('Lunch and Gender', fontsize=15)
sns.countplot(x='lunch', hue='gender', data=df)
plt.subplot(252)
plt.title('Ethnicity and Lunch', fontsize=15)
sns.countplot(x='race/ethnicity', hue='lunch', data=df)
plt.show()
# In[19]:
df['total_score'] = df['math score'] + df['reading score'] + df['writing score']
# In[20]:
df.append(['total_score'], ignore_index=True, verify_integrity=False, sort=None)
# In[21]:
df['percentage']=df['total_score']/300*100
# In[22]:
df
# In[23]:
per = df['percentage']
# In[24]:
g=[]
def determine_grade():
for i in per:
if int(i) >= 85 and int(i) <= 100:
g.append('A')
elif int(i) >= 70 and int(i) < 85:
g.append('B')
elif int(i) >= 55 and int(i) < 70:
g.append('C')
elif int(i) >= 36 and int(i) < 55:
g.append('D')
elif int(i) >= 0 and int(i) < 35:
g.append('E')
determine_grade()
# In[26]:
df.insert(10,'grade',g,allow_duplicates=False)
# In[27]:
df
# In[29]:
plt.rcParams['figure.figsize'] = {20, 30}
sns.countplot(df['grade'], palette = 'dark')
plt.title('Grades',fontsize = 20)
plt.show()
# In[31]:
plt.title('Grade and Ethnicity',fontsize=20)
sns.countplot(x='race/ethnicity', hue='grade', data=df)
gr=pd.crosstab(df['grade'],df['race/ethnicity'],normalize=0)
gr.plot.bar(stacked=True)
plt.title('Grade and Ethnicity',fontsize=20)
plt.show()
# In[32]:
plt.title('Grade and Parental Level of Education')
sns.countplot(x='parental level of education', hue='grade', data=df)
plt.show()
# In[35]:
plt.figure(figsize=(20,10))
plt.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=0.5, hspace=0.2)
plt.subplot(251)
plt.title('Grade and Gender')
sns.countplot(hue='gender', x='grade', data=df)
plt.subplot(252)
plt.title('Grade and Lunch')
sns.countplot(hue='lunch', x='grade', data=df)
plt.subplot(253)
plt.title('Grade and Test Preparation Course')
sns.countplot(hue='test preparation course', x='grade', data=df)
plt.show()
# In[42]:
plt.figure(figsize=(60,50))
plt.subplot(141)
plt.title('Grade',fontsize =20)
df['grade'].value_counts().plot.pie(autopct='%1.1f%%')
|
24f4ccb92d21b103b3b90447eae91e0494e73d13 | Hiteshsaai/AlgoExpert-CodingProblems-PythonSolution | /Easy/nonConstructibleChange.py | 551 | 3.59375 | 4 | class Solution:
def nonConstructibleChange(self, coins):
## Time O(n) || Space O(1)
if not coins:
return 1
coins.sort()
currChange = 0
for coin in coins:
if coin > currChange + 1:
return currChange + 1
else:
currChange += coin
return currChange + 1
if __name__ == "__main__":
print(Solution().nonConstructibleChange([5, 7, 1, 1, 2, 3, 22]))
print(Solution().nonConstructibleChange([1, 5, 1, 1, 1, 10, 15, 20, 100]))
|
ea1b4f7c1b0f014f78e5177b65e631fa43b2cbe5 | arodan10/Ejercicios10 | /2ejercicio.py | 167 | 3.78125 | 4 | def tabla():
#Datos de entrada
numero=int(input("Digite un número entero:"))
#Proceso
for X in range(1, 11):
print(f"{X} * {numero} = {X*numero}")
tabla() |
ba3d1bb1c2b1822c9bfbef545b0879b2ef07b663 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2748/40186/320689.py | 222 | 3.6875 | 4 | s = input()
if(s=="(a)())()"):
print("['(a)()()', '(a())()']")
elif(s=="()())()"):
print("['()()()', '(())()']")
elif(s==")("):
print("['']")
elif(s=="[\"23:39\",\"00:00\"]"):
print("21")
else:
print(s) |
94ba4e077c30ad23f28ee70041d0ce0c6aa1d7b4 | xXG4briel/CursoPythonGuanabara | /8 - Módulos/Desafio 019.py | 245 | 3.578125 | 4 | import random
a=random.randint(1,4)
if a==1:
print('Vem apagar a lousa noia')
if a==2:
print('Vem apagar a lousa Larissa')
if a==3:
print('cala a boca marcelo\nvem apagar a lousa')
if a==4:
print('Apaga a lousa porfavor Alice')
|
14cf9f06a52d8d7dd310339607cb727a70f43020 | ErdunE/LanguageLearning-MyImprovement | /Python/01_Python基础/hm_07_超市买苹果增强版.py | 469 | 4.15625 | 4 | # 1. 输入苹果的单价
price_str = input("苹果的单价: ")
# 2. 输入苹果的重量
weight_str = input("苹果的重量: ")
# 3. 计算支付的总金额
# 注意:两个字符串变量之间是不能直接用乘法的
# money = price_str * weight_str
# 4. 将价格和重量转换成小数
price = float(price_str)
weight = float(weight_str)
# 5. 用转换后的小数计算总价格
money = price * weight
print("苹果的总价为: ")
print(money)
|
f872c3a93a3163f92d80970b79819e4dd6d79718 | FlintHill/SUAS-Competition | /UpdatedSyntheticDataset/SyntheticDataset2/ElementsCreator/quarter_circle.py | 1,290 | 3.5 | 4 | from PIL import ImageDraw, Image
from SyntheticDataset2.ElementsCreator import Shape
class QuarterCircle(Shape):
def __init__(self, radius, color, rotation):
"""
Initialize a Quarter Circle shape
:param radius: radius in pixels
:type radius: int
:param color: color of shape - RGB
:type color: 3-tuple ints
:param rotation: degrees counterclockwise shape will be rotated
:type rotation: int
"""
super(QuarterCircle, self).__init__(color, rotation)
self.diameter = radius*2
self.coordinates = self.get_coordinates()
def get_coordinates(self):
"""
:param coordinates: drawing coordinates for the shape
:type coordinates: list of 2-tuple xy pixel coordinates
"""
return [(0,0), (self.diameter,self.diameter)]
def draw(self):
new_quarter_circle = Image.new('RGBA', (self.diameter,self.diameter), color=(255,255,255,0))
draw = ImageDraw.Draw(new_quarter_circle)
draw.ellipse(self.coordinates, fill=self.color)
new_quarter_circle = new_quarter_circle.crop((0,0,self.diameter/2,self.diameter/2))
new_quarter_circle = new_quarter_circle.rotate(self.rotation, expand=1)
return new_quarter_circle
|
a67d995efafec9cc253f5d736efb14dea4421879 | daniel-reich/ubiquitous-fiesta | /BxKT4agPnm9ZNpDru_20.py | 121 | 3.8125 | 4 |
def zip_it(women, men):
if len(women) != len(men):
return "sizes don't match"
return list(zip(women,men))
|
7ce9c58970b6194cfda63cf4d616f95fe34961de | tiennynyle/similarities | /helpers.py | 917 | 3.734375 | 4 | from nltk.tokenize import sent_tokenize
def lines(a, b):
"""Return lines in both a and b"""
#take in string inputs a, b, split each string into lines, compute a list of all lines that appear in both a and b
lines_a = set(a.split('\n'))
lines_b = set(b.split('\n'))
#return the list
return lines_a & lines_b
def sentences(a, b):
"""Return sentences in both a and b"""
sentences_a = set(sent_tokenize(a))
sentences_b = set(sent_tokenize(b))
return sentences_a & sentences_b
def substrings(a, b, n):
"""Return substrings of length n in both a and b"""
substrings_a = []
substrings_b = []
for i in range (len(a)-n +1):
substrings_a.append(a[i: i+n])
for j in range (len(b)-n+1):
substrings_b.append(b[j: j+n])
#s[i:j] - return substrings of s from index i to (but not including) j
return (set(substrings_a) & set(substrings_b))
|
b8ebc514508647984c0d9cd19279fa27185e7f48 | Incertam7/Infosys-InfyTQ | /Programming-Fundamentals-using-Python/Day-5/Exercises/Exercise-26.py | 667 | 4.03125 | 4 | #PF-Exer-26
def factorial(number):
fact = 1
while number > 0:
fact *= number
number -= 1
return fact
def find_strong_numbers(num_list):
strong_list = []
for num in num_list:
sum = 0
if num == 0:
sum = 1
temp = num
while temp > 0:
rem = temp % 10
rem_fact = factorial(rem)
sum += rem_fact
temp //= 10
if sum == num:
strong_list.append(num)
return strong_list
num_list=[145, 2, 10, 0]
strong_num_list=find_strong_numbers(num_list)
print(strong_num_list)
|
88b19864056385105bb6cd7cca9db24f0d8a6882 | eternaltc/test | /Test/Basis/mypy14_for_else.py | 434 | 3.828125 | 4 | #测试循环中的else语句
staffNum = 4
salaryNum = 0
salarys = []
for i in range(staffNum):
s = input("请输入员工的薪资(Q或q退出):")
if s=="Q" or s=="q":
break
if float(s)<0:
continue
salarys.append(float(s))
salaryNum += float(s)
else:
print("已录入4个员工的薪资")
print("录入薪资{0}".format(salarys))
print("平均薪资{0}".format(salaryNum/staffNum)) |
48d1a1648f632c34b7c4483657e9607d79729342 | matheusmcz/Pythonaqui | /Mundo2/ex056.py | 833 | 3.5 | 4 | media = 0
homemmaisvelho = 0
nomehomem = 0
mulhermaisnova = 0
quantidademulheres = 0
for c in range(1, 5):
print('--' * 5, '{}ª PESSOA'.format(c), '--' * 5)
pessoa = str(input('Nome: ')).strip().upper()
idade = int(input('Idade: '))
sexo = (input('Sexo [M/F]: ')).strip().upper()
media = media + idade / 4
if c == 1 and sexo in 'Mm':
homemmaisvelho = idade
nomehomem = pessoa
if sexo in 'Mm' and idade > homemmaisvelho:
homemmaisvelho = idade
nomehomem = pessoa
if sexo in 'Ff' and idade < 20:
quantidademulheres = quantidademulheres + 1
print('\nA média de idade é de {} anos.'.format(media))
print('{} é o homem mais velho, com {} anos.'.format(nomehomem, homemmaisvelho))
print('Quantidade de mulheres abaixo dos 20 anos: {}'.format(quantidademulheres))
|
553c367ab7baa6b6a45d5ec3710366f025aad9f3 | terra888/Python_final | /Semana 1/problemas_diversos.py | 699 | 3.734375 | 4 | #Problemas diversos
#Problema 1
ci = float(input("Ingrese la cantidad inicial: "))
for i in range(1,4,1):
ci = ci*104/100
print(f"El monto para el año {i} será: {round(ci,2)}")
#Problema 2
import math
a = float(input("Ingrese el valor de a: "))
b = float(input("Ingrese el valor de b: "))
c = float(input("Ingrese el valor de c: "))
d = b**2 - 4*a*c
while a != 0:
if d <0:
print("No existe solución real")
elif d == 0:
x = -b / (2*a)
print(f"Existe una solución doble: {x}")
else:
x1 = (-b + math.sqrt(d))/2*a
x2 = (-b - math.sqrt(d))/2*a
print(f"Las soluciones son {x1} y {x2}")
break |
b1399cb56fa2760046055af58895659962038856 | ngocphucdo/ngocphucdo-fundamentals-c4e15 | /session_5/homework/ex5.py | 225 | 3.53125 | 4 | pairs = []
for i in range(5):
if i == 0:
pairs.append(1)
elif i == 1:
pairs.append(2)
else:
pairs.append(p[i-1] + p[i-2])
print("Month {0}: {1} pair(s) of rabbits".format(i,pairs[i]))
|
fd36c8d95364c1f74b00526e61654788425c65d6 | sdozier/code_portfolio | /euler_probs.py | 4,477 | 3.609375 | 4 | #Simone Dozier
#Project Euler problems
from helperMethods import *
import math
#==============#
#Problem 52: Permuted multiples
#==============#
def isPermutation(n,x):
#takes 2 lists, assumes n is already sorted
x.sort()
return n==x
def fitsReq(x):
"""Checks if number fits the requirements of problem 52
e.g. x, 2x, ..., 6x all contain the same digits
"""
n = list(str(x))
n.sort()
factor = 2
for factor in range(2,7):
if not isPermutation(n,list(str(x*factor))):
return False
return True
def tryTil(limit):
for i in range(1,limit):
if fitsReq(i):
print i
break
def prob52():
tryTil(10**6)
#==============#
#Problem 55: Lychrel numbers
#==============#
def reverse(s):
"""Takes an integer, expressed as a string, and returns the reverse as an integer
:Example:
>>> reverse('1293')
3921
"""
r=0
for i in range(len(s)):
r+= int(s[i])*(10**i)
return r
def isLychrel(n):
#isPalindrome and reverse both work with strings. Leave as strings except when adding for less conversion.
nxt = str(n+reverse(str(n)))
if isPalindrome(nxt):
return False
n=nxt
for i in range(48):
nxt = str(int(n)+reverse(n))
if isPalindrome(nxt):
return False
n=nxt
return True
def countLychrel():
"""Returns the number of Lychrel numbers less than 10000"""
c = 0
for i in range(1,10000):
if isLychrel(i):
c+=1
return c
def prob55():
print countLychrel()
#==============#
#Problem 67: Maximum path sum ii
#==============#
def readTriangle():
"""Converts triangle data in file to a matrix"""
f = open('p067_triangle.txt','r')
rows=[]
for line in f:
l=line[:-1].split(' ')
rows.append(map(int,l))
return rows
def prob67():
"""Finds the maximum path through the triangle
Dynamic programming solution. Calculates maximum path to each square, starting
with the first two squares and working down the triangle. Only stores the max
path to each square so you don't calculate every path."""
rows=readTriangle()
ws = rows[0] #the working sums
nws = [0,0] #"next working sum"
for i in range(1,len(rows)):
nws[0] = ws[0] + rows[i][0]
nws[-1] = ws[-1] + rows[i][-1]
for j in range(1,len(ws)):
x1 = rows[i][j]+ws[j-1]
x2 = rows[i][j]+ws[j]
nws[j] = max(x1,x2)
ws = nws
nws = [0]*(i+2)
print max(ws)
#==============#
#Problem 74: Digit factorial chains
#==============#
#avoid recalculating chains and factorials--significantly faster. Credit to harplanet for the idea.
knownLens=dict()
fs=dict()
def setUpFactorials():
"""Initializes factorial dictionary fs"""
for i in range(10):
fs[i]=math.factorial(i)
def nextFact(n):
"""Returns the sum of the factorial of the digits of n.
Expects factorial dictionary fs to be set up.
:Example:
>>> nextFact(109)
1! + 0! + 9! = 362882
"""
f=0
while(n>=10):
f+=fs[n%10]
n=n/10
f+=fs[n%10]
return f
def loop60(n):
"""Returns boolean: whether continually applying nextFact(n) creates a chain of 60 non-repeating terms"""
seen=set()
chain=[]
terms=1
#Chain is guaranteed not to EXCEED 60 for n < 1,000,000, so no need to check beyond that
while terms <= 60:
chain.append(n)
if n in seen:
for c in chain:
knownLens[c]=terms
return False
if n in knownLens and terms+knownLens[n]<60:
for c in chain:
knownLens[c]=terms+knownLens[n]
return False
seen.add(n)
terms+=1
n=nextFact(n)
for c in chain:
knownLens[c]=60
return True
def loop60old(n):
"""Returns boolean: whether continually applying nextFact(n) creates a chain of 60 non-repeating terms"""
seen=set()
for i in range(60):
if n in seen:
return False
seen.add(n)
n=nextFact(n)
return True
def prob74():
"""Prints the number of chains, beginning with n < 1,000,000, that contain exactly 60 terms"""
setUpFactorials()
c=0
for i in range(2,1000000):
if(i%50000==0):
print "checking %i..." % i #to track progress
if(loop60(i)):
c+=1
print c
|
1fd842c4b95541096fd160cf26fb6ffac41b527c | WeiyiGeek/Study-Promgram | /Python3/Day3/demo3.0.py | 1,483 | 3.53125 | 4 | #!/usr/bin/python3
#功能:easyGUI简单得功能(更多请看配置文件)
import easygui as g
import sys
import os
# g.msgbox("hello,world")
# g.msgbox("I love study Python")
# while 1:
# msg = "谁是最好得编程语言?"
# title = "语言选择"
# choices = ['PHP','Python','Javascript','node.js']
# choices = g.choicebox(msg,title,choices) #都是字符串,选择Cancel函数返回NONE
# g.msgbox("您选择得是"+str(choices)+"编程语言")
# if g.ccbox("再次游戏好吗?","test",choices=('YES',
# 'NO')):
# pass #contiue
# else:
# sys.exit(0) #cancel
#/****按钮****/
# if g.ynbox('这个使用于ccbox差不多','验证ynbox功能'):
# print("F1按下")
# else:
# print("F2按下")
# g.msgbox("F2按下","测试ynbox功能")
# print("选择上面按钮显示对应得值"+g.buttonbox("选择您喜欢得水果","水果",choices=('Apple','Balana','荔枝'),image="1111.png"))
# print(g.boolbox('测试boolbox功能')) #返回boolean
#**/选项选择/***#
# test = os.listdir()
# choice = g.choicebox("在"+os.getcwd()+"目录下得文件目录有","当前目录下得文件",test)
# print("您选择得目录或者是 " + choice )
# g.multchoicebox("多选选择框","测试multchoicebox",test)
#/****用户输入***/#
input1 = g.enterbox("请输入您心里得话?")
g.msgbox(input1)
g.integerbox("测试intergerbox","输入数值在0-99",default=17,lowerbound=0,upperbound=99)
#/*****/
|
493b1ae51fabbf39b5f7c9aea123643aa50b1d95 | ongbe/hedgeit | /hedgeit/feeds/indicator.py | 840 | 3.640625 | 4 | '''
hedgeit.feeds.indicator
An indicator that can be used in a strategy
'''
from abc import ABCMeta, abstractmethod
class Indicator(object):
'''
Indicator is an abstract base class that defines the interface for
the signals that can be used to form trading strategies
'''
def __init__(self, name):
'''
Constructor
@param name - name used to reference the indicator
'''
self._name = name
def name(self):
return self._name
@abstractmethod
def calc(self, feed):
"""
Produce the data series for the indicator in the input feed.
:param Feed feed: feed that the indicator is for
:returns: indicator data serios
:rtype: numpy array
"""
raise Exception("Not implemented")
|
149469f468f5b3ff948ffc7b63608938795c8290 | Faizah-Binte-Naquib/Program-List | /Loop/11.py | 1,106 | 4.03125 | 4 | # <b>10. Write a program to calculate how many 5 digit numbers can be created if the following terms apply :
# (i) the leftmost digit is even
# (ii) the second digit is odd
# (iii) the third digit is a non even prime
# (iv) the fourth and fifth are two random digits not used before in the number.</b>
#
# * Summary: Determines all possible 5 digit numbers for given conditions
# * Input:
# * Output: total numbers
# In[154]:
flag=1
count=0
for i in range(10000,100000):
num_str=str(i)
if(int(num_str[0])%2==0):
if(int(num_str[1])%2!=0):
for j in range(1,int(num_str[2])):
if(int(num_str[2])%j==0 and int(num_str)!=2):
flag=2
if(flag==1):
if(int(num_str[3])!=int(num_str[0]) and int(num_str[3])!=int(num_str[1]) and int(num_str[3])!=int(num_str[2])):
if(int(num_str[3])!=int(num_str[0]) and int(num_str[3])!=int(num_str[1]) and int(num_str[3])!=int(num_str[2]) and int(num_str[4])!=int(num_str[3])):
count=count+1
flag=1
print(count)
|
30e986b92cfffa5009e40c77dce7f02738c52664 | czhnju161220026/LearnPython | /chapter2/GeneratorDemo.py | 194 | 3.515625 | 4 |
if __name__ == '__main__':
colors = ['black', 'white', 'gray']
size = ['S', 'M', 'L', 'XL']
for (color, s) in ((color, s) for color in colors for s in size):
print(color,s)
|
d25b2e542dfa25af3aaa6bc16a97d9a414181256 | bearkillerPT/App-Or-amentos-Fachada | /fachada/calc.py | 1,565 | 3.546875 | 4 | # -*- coding: utf-8 -*-
class Piso:
def __init__(self, pisoName):
self.name = pisoName
self.divs = {}
def getDivs(self):
return self.divs
def getName(self):
return self.name
#Para o csv construir sem saber ponteciaref e alturaref
def buildDiv(self, divname, area, volume, equipamento):
self.divs[divname] = [area, volume, equipamento]
def addDiv(self, divName, area, potenciaRef, alturaRef):
potenciaDiv = potenciaRef * area
volume = area * potenciaRef
equipamento = ""
if potenciaDiv < 2000:
equipamento = "SL200"
elif potenciaDiv < 4000:
equipamento = "SL400"
elif potenciaDiv < 6000:
equipamento = "SL600"
elif potenciaDiv < 8000:
equipamento = "SL800"
elif potenciaDiv < 10000:
equipamento = "SL1000"
else:
equipamento = "verificar!"
self.divs[divName] = [area, volume, equipamento]
def removeDiv(self, divName):
del self.divs[divName]
def totalArea(self):
total = 0
for (_, info) in self.divs.items():
total += info[0]
return total
def printDivs(self):
for (divname, info) in self.divs.items():
print("Divisão: " + divname + "\n\tArea: " + str(info[0]) + "\n\tVolume: " + str(info[1]) + "\n\tEquipamento: " + info[2])
def totalVolume(self):
total = 0
for (_, info) in self.divs.items():
total += info[1]
return total
|
fc90dceece6c03e5bbe51f2a8ea5ebbf5bcba584 | kevynfg/estudos-geral | /codigofonte-estudos/modulo2/thread3.py | 591 | 3.5625 | 4 | import threading
import time
ls = []
def contador1(n):
for i in range(1, n+1): # valor de 1 até o valor recebido no parâmetro
print(i)
ls.append(i)
time.sleep(0.4)
def contador2(n):
for i in range(6, n+1):
print(i)
ls.append(i)
time.sleep(0.5)
x = threading.Thread(target=contador1, args=(5,))
x.start()
# da prioridade para a primeira thread
x.join()
y = threading.Thread(target=contador2, args=(10,))
y.start()
# da prioridade para a segunda thread
y.join()
# executa o print depois que o JOIN finalizar apenas
print(ls)
|
640a260a0dc8954b63e19af2ca4842e2d43bdbc4 | MikePolinske/PythonForBeginners | /LearnPython/if-statement.py | 227 | 4.09375 | 4 | a,b = 2,2
if a == b:
print(True)
if a != b:
print(True)
if a < b:
print(True)
if a > b:
print(True)
if a <= b:
print("This is true")
if a >= b:
print(True) # not =>
if a == b and b > 1:
print(True) |
6de3473f348bf28e2f5a18468596e523c6168977 | SerGeRybakov/self_made | /таблица_умножения.py | 665 | 3.890625 | 4 | """Multiplication table"""
x1 = int(input('Input lines first number: '))
x2 = int(input('Input lines last number: '))
y1 = int(input('Input columns first number: '))
y2 = int(input('Input columns last number: '))
# Making Y-headers in the first line of table
field = y1 - 1
while field <= y2:
if field < y1:
print(end='\t')
field += 1
else:
print(field, end='\t')
field += 1
else:
print()
# Making lines with results. First row is made of X-headers.
for x in range(x1, x2 + 1):
print(x, end='\t')
for y in range(y1, y2 + 1):
z = x * y
print(z, end='\t')
print()
|
2c6685966a99426fc8642cb33f950d745bfcfc64 | CodingGearsCourses/Python-OO-Programming-Fundamentals | /Module-02-OOPs-Essentials/oops_basics_09.py | 1,362 | 4.15625 | 4 | # https://www.globaletraining.com/
# Changing Class and Object Variables/Attributes
class Car:
# Class Attributes/Variables
no_of_tires = 4
# Class Constructor/Initializer (Method with a special name)
def __init__(self):
# Object Attributes/Variables
self.make = ""
self.model = ""
self.year = ""
self.color = ""
self.moon_roof = ""
self.engine_running = ""
# Methods
def start_the_engine(self):
self.engine_running = True
def stop_the_engine(self):
self.engine_running = False
def main():
print("Hello from the main() method!")
car1 = Car()
car2 = Car()
# Values
car1.make = "Tesla"
car1.model = "Model 3"
car1.color = "Red"
car1.year = 2020
car1.moon_roof = True
# Accessing car1 attributes
print("Printing car1 details:".center(50, "-"))
print("Make : {}".format(car1.make))
print("Model : {}".format(car1.model))
print("Year : {}".format(car1.year))
print("Color : {}".format(car1.color))
print("Moon Roof : {}".format(car1.moon_roof))
# Class Attributes
print("Class Attributes:".center(50, "-"))
print("car1:", car1.no_of_tires)
Car.no_of_tires = 25
print("car1:", car1.no_of_tires)
print("car2:", car2.no_of_tires)
if __name__ == '__main__':
main()
|
1e80d23c7b4ce4d0e78b17f59f5fadf0030d8c9f | dark4igi/atom-python-test | /coursera/Chapter_7.py | 479 | 4.03125 | 4 | ### Data type
##file
# example open file
xfile = open (file.txt)
for line in xfile:
print (line )
## work with strings
#
line.rstrip() # strip whitespaces and newline from the right-hand of the string
line.startswith('some text') # became true if line starts with 'some text'
line.upper() # upper case for line
line.lower() # lower case for line
line[20:] # string after 20 chapter
line[:20] # string before 20 chapter
line [3:8] # string from 3rd to 8th, not include 8th
|
4fc7289ca0da3827e58824be28e8a352e10bb821 | yes99/practice2020 | /codingPractice/python/학교 과제/quiz3.py | 199 | 3.671875 | 4 | print("라인 수?", end="")
num=int(input())
for k in range(num):
for j in range (k):
print(" ", end="")
for l in range(num-k):
print("*", end="")
print()
|
df7dcb9483f4be3016645c4579b245ea35284fed | arthurDz/algorithm-studies | /leetcode/consecutive_characters.py | 1,012 | 4.09375 | 4 | # Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
# Return the power of the string.
# Example 1:
# Input: s = "leetcode"
# Output: 2
# Explanation: The substring "ee" is of length 2 with the character 'e' only.
# Example 2:
# Input: s = "abbcccddddeeeeedcba"
# Output: 5
# Explanation: The substring "eeeee" is of length 5 with the character 'e' only.
# Example 3:
# Input: s = "triplepillooooow"
# Output: 5
# Example 4:
# Input: s = "hooraaaaaaaaaaay"
# Output: 11
# Example 5:
# Input: s = "tourist"
# Output: 1
# Constraints:
# 1 <= s.length <= 500
# s contains only lowercase English letters.
def maxPower(self, s: str) -> int:
prev = ''
prev_count = 0
max_count = 0
for char in s:
if char == prev:
prev_count += 1
else:
prev = char
prev_count = 1
max_count = max(max_count, prev_count)
return max_count |
6138b4b3f0503baecb1d8a61430733d47f60cbe2 | IamConstantine/LeetCodeFiddle | /python/LevelOrderTree.py | 708 | 3.71875 | 4 | import collections
from collections import deque
from typing import Optional, List
from Tree import TreeNode
# https://leetcode.com/problems/binary-tree-level-order-traversal
# Medium - easy for me
# For me, Tree questions seems easier.
# T = O(N) - each node exactly once
# S = O(N) - Width of the tree
def levelOrder(root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
q = deque()
q.append((0, root))
l = collections.defaultdict(lambda: [])
while q:
level, curr = q.popleft()
l[level].append(curr.val)
for node in [curr.left, curr.right]:
if node:
q.append((level + 1, node))
return list(l.values())
|
1a6255f0f73a3e7a99bac9a9afa576878bb25ac0 | sumeyyadede/algorithm-problems | /trees.py | 1,367 | 4.03125 | 4 | class TreeNode(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __repr__(self):
# return "({}, {}, {})".format(self.data, self.left.data if self.left else None, self.right.data if self.right else None)
return "({})".format(self.data)
class Tree(object):
def __init__(self):
self.head = None
def in_order_traversal(self, node):
if node:
self.in_order_traversal(node.left)
print(node)
self.in_order_traversal(node.right)
else:
return None
def pre_order_traversal(self, node):
if node:
print(node)
self.pre_order_traversal(node.left)
self.pre_order_traversal(node.right)
else:
return None
def post_order_traversal(self, node):
if node:
self.post_order_traversal(node.left)
self.post_order_traversal(node.right)
print(node)
else:
return None
def main():
root_node = TreeNode(1)
root_node.left = TreeNode(2)
root_node.right = TreeNode(3)
root_node.left.left = TreeNode(4)
root_node.left.right = TreeNode(5)
print(root_node)
print(root_node.left)
print(root_node.right)
tree_impl = Tree()
print("inorder")
tree_impl.in_order_traversal(root_node)
print("---")
print("preorder")
tree_impl.pre_order_traversal(root_node)
print("---")
print("postorder")
tree_impl.post_order_traversal(root_node)
if __name__ == "__main__":
main()
|
144f427fde92972ee6293331f3e1ae5fc64ba67d | Philfeiran/Calculator | /src/calculatorTest.py | 2,314 | 3.609375 | 4 | from calculator import calculator
import unittest
import csv
def readFile (file):
csvFile = open(file, "r")
reader = csv.reader(csvFile)
IsThreeVar = True
x=[]
y=[]
result=[]
for item in reader:
if reader.line_num==1:
if item[2]==' ':
IsThreeVar=False
continue
x.append(float(item[0]))
if not IsThreeVar:
result.append(float(item[1]))
else:
y.append(float(item[1]))
result.append(float(item[2]))
if IsThreeVar:
return x,y,result
else:
return x,result
class testCalculator(unittest.TestCase):
cal = calculator()
def testAddition(self):
self.assertEqual(self.cal.add(2,2),4)
def testSubtraction(self):
self.assertEqual(self.cal.minus(2,2),0)
def testMultiplication(self):
self.assertEqual(self.cal.multply(2,2),4)
def testDivision(self):
self.assertEqual(self.cal.divide(2,4),2)
def testSquare(self):
self.assertEqual(self.cal.square(4),16)
def testSquareRoot(self):
self.assertEqual(self.cal.squareRoot(4),2)
def testCSVfiles(self):
#test given CSV files
xADD,yADD,resultADD = readFile("./src/Unit Test Addition.csv")
xSUB,ySUB,resultSUB= readFile("./src/Unit Test Subtraction.csv")
xMUL,yMUL,resultMUL=readFile("./src/Unit Test Multiplication.csv")
xDIV, yDIV, resultDIV = readFile("./src/Unit Test Division.csv")
xSQU, resultSQU = readFile("./src/Unit Test Square.csv")
xSQR, resultSQR = readFile("./src/Unit Test Square Root.csv")
#every CSV file has 18 cases
for i in range (18):
self.assertEqual(self.cal.add(xADD[i],yADD[i]),resultADD[i])
self.assertEqual(self.cal.minus(xSUB[i],ySUB[i]),resultSUB[i])
self.assertEqual(self.cal.multply(xMUL[i],yMUL[i]),resultMUL[i])
#for divison and square root, I only compare results in 6 demicial places
self.assertEqual(round(self.cal.divide(xDIV[i],yDIV[i]),6),round(resultDIV[i],6))
self.assertEqual(self.cal.square(xSQU[i]),resultSQU[i])
self.assertEqual(round(self.cal.squareRoot(xSQR[i]),6),round(resultSQR[i],6))
if __name__ == '__main__':
unittest.main()
|
57906cf3bfb4412639715e525e301763411cd9d9 | pwang867/LeetCode-Solutions-Python | /0024. Swap Nodes in Pairs.py | 1,416 | 4.0625 | 4 | # time O(n), space O(1)
class Solution(object):
def swapPairs(self, head):
dummy = ListNode(0)
dummy.next = head
p1 = dummy # we swap the pair after p1
while p1 and p1.next and p1.next.next:
p2 = p1.next
p3 = p2.next
p4 = p3.next
# swap middle two pointers: p2 and p3
p1.next = p3
p3.next = p2
p2.next = p4
p1 = p2
return dummy.next
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# method 1, same as method 2, but use a single variable
class Solution1(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
cur = dummy
while cur and cur.next and cur.next.next:
copy = cur.next.next.next
cur.next.next.next = cur.next
cur.next = cur.next.next
cur.next.next.next = copy
cur = cur.next.next
return dummy.next
"""
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
"""
|
f13eb28b6d856d4911986e016eff09f6524559bf | phil-harmston/hangman | /hangman.py | 8,132 | 3.921875 | 4 | # Imports needed to code the project
from curses import wrapper
import curses
import random
import string
import json
import functools
stdscr = curses.initscr()
"""Use this function to input a custom word then choose option "C" When playing the game"""
def custom_word():
my_word = "UTAH"
return my_word
# Used to ease the menu at the beginning of the game.
def erase_menu(stdscr, menu_y):
stdscr.clear()
stdscr.border()
# Displays the menu at the beginning of the game.
def display_menu(stdscr, menu_y):
try:
erase_menu(stdscr, menu_y)
stdscr.addstr(menu_y +0, 30, '1.) "E" -- EASY MODE')
stdscr.addstr(menu_y +1, 30, '2.) "A" -- AVERAGE MODE')
stdscr.addstr(menu_y +2, 30, '3.) "H" -- HARD MODE')
stdscr.addstr(menu_y +3, 30, '4.) "C" -- CUSTOM WORD')
stdscr.addstr(menu_y +4, 30, '5.) "Q" -- PRESS "Q" TO QUIT')
except:
pass
# Draws the hangman tree in ascii
def draw_game(stdscr):
stdscr.move(2, 5)
stdscr.addstr('===============')
for y in range(3,15):
stdscr.move(y, 5)
stdscr.addstr('|')
stdscr.move(y,2 )
stdscr.addstr('=======')
stdscr.refresh()
# Draw the fat head using o
def draw_head(stdscr):
stdscr.move(2, 19)
stdscr.addstr('oo')
stdscr.move(3, 18)
stdscr.addstr('o o')
stdscr.move(4, 17)
stdscr.addstr('o o')
stdscr.move(5, 18)
stdscr.addstr('o o')
stdscr.move(6, 19)
stdscr.addstr('o o')
stdscr.refresh()
# Draw the body of the person
def draw_body(stdscr):
stdscr.move(7, 20)
for y in range(7,12):
stdscr.move(y, 20)
stdscr.addstr('|')
stdscr.refresh()
# Draw the arms and legs of the person
def draw_right_arm(stdscr):
stdscr.move(8, 20)
stdscr.addstr('_______')
def draw_left_arm(stdscr):
stdscr.move(8, 14)
stdscr.addstr('_______')
def draw_right_leg(stdscr):
stdscr.move(11, 20)
stdscr.addstr('_______')
for y in range(12,14):
stdscr.move(y, 26)
stdscr.addstr('|')
def draw_left_leg(stdscr):
stdscr.move(11, 14)
stdscr.addstr('_______')
for y in range(12,14):
stdscr.move(y, 14)
stdscr.addstr('|')
#function opens the file to use and returns the list to the level functions.
def open_file():
with open("dict.json", 'r') as file:
words = json.load(file)
return words
# returns words less than 14 and greater than 9 in length
def hard_list():
hard_word = []
words = open_file()
for key in words:
if len(key) < 14 and len(key) > 9:
hard_word.append(key)
my_word = random.choice(hard_word)
return my_word
# returns words less than 9 greater than 5
def med_list():
med_word = []
words = open_file()
for key in words:
if len(key) < 9 and len(key) > 5:
med_word.append(key)
my_word = random.choice(med_word)
return my_word
# returns the words less than 7 and greater than 4
def easy_list():
easy_word = []
words = open_file()
for key in words:
if len(key) < 7 and len(key) > 4:
easy_word.append(key)
my_word = random.choice(easy_word)
return my_word
# Function used to compare the lists if true returns true else false
# this is how we see if the user won the game or not.
def wordfound(word, my_word):
if functools.reduce(lambda i, j : i and j, map(lambda m,k: m==k, word, my_word),True):
return True
else:
return False
# game loop for game play
def gameloop(stdscr, word):
# always start with 6 lives lives are reduce and shown by adding parts to the hangman
lives = 6
# holds the user letter selection
my_word = []
# the game starts off with underscores until a letter is found
for l in word:
my_word.append('_')
while(1):
# Get input from the user
s =''
c = stdscr.getkey(1,1) #get key from the user
# uppercase for comparison
c = c.upper()
word = word.upper()
# special exit charactor for dev purposes exit any time by pressing shift ~
if c == "~":
exit()
if c in word:
# find the letter in the word and show it.
for index, letter in enumerate(word):
if letter == c:
my_word[index] = letter
# if the letter is not in the word reduce lives by one and hang our hangman
# each time the game is redrawn so all parts must be redrawn. This probably needs fixed.
else:
lives = lives -1
if lives == 5:
draw_head(stdscr)
if lives == 4:
draw_head(stdscr)
draw_body(stdscr)
if lives == 3:
draw_head(stdscr)
draw_body(stdscr)
draw_left_arm(stdscr)
if lives == 2:
draw_head(stdscr)
draw_body(stdscr)
draw_left_arm(stdscr)
draw_right_arm(stdscr)
if lives == 1:
draw_head(stdscr)
draw_body(stdscr)
draw_left_arm(stdscr)
draw_right_arm(stdscr)
draw_left_leg(stdscr)
if lives ==0:
draw_head(stdscr)
draw_body(stdscr)
draw_left_arm(stdscr)
draw_right_arm(stdscr)
draw_left_leg(stdscr)
draw_right_leg(stdscr)
# creates a string to show the word on the screen after each selection
stdscr.addstr(20, 15, s.join(my_word))
# checks to see if the game was won
if wordfound(word, my_word):
win_loose(stdscr, word, game_results=1)
# if lives equal 0 the game was lost
if lives == 0:
win_loose(stdscr, word, game_results = 0)
# prints the appropriate results of the game win or loose.
def win_loose(stdscr, word, game_results):
stdscr.move(18,10)
stdscr.clrtoeol()
if game_results == 0:
stdscr.addstr(18, 10, "I'm sorry, better luck on the next one. Press \"N\" to play again")
stdscr.move(19, 10)
answer = 'The word was {} . '.format(word)
stdscr.addstr(19, 10, answer)
else:
stdscr.addstr(18, 10, "Good job, Press \"N\" to play again")
answer = 'The word was {} . '.format(word)
stdscr.addstr(19, 10, answer)
# allows the user to play again if desired.
c = stdscr.getkey(1,1) #get key from the user
c = c.upper()
if c == 'N':
print_board(stdscr)
def print_board(stdscr):
# sets up the game
stdscr.clear() # Clear the screen
stdscr.border()
stdscr_y, stdscr_x = stdscr.getmaxyx()
menu_y = (stdscr_y+5) - 20
# prints the opening menu
display_menu(stdscr, menu_y)
c = stdscr.getkey(1,1) #get key from the user
stdscr.addstr(c)
c = c.upper()
if c =='E': #Easy mode
word = easy_list()
if c == 'A':
word = med_list()
if c == 'H':
word = hard_list()
if c == 'C':
word = custom_word()
if c == 'Q':
exit()
if (c !='E') or (c !='A') or (c !='H') or (c !='C') or (c !='Q'):
c == 'E'
word = easy_list()
# clears the menu on game start
erase_menu(stdscr, menu_y)
# draws the game and prompts for input
draw_game(stdscr)
stdscr.addstr(18, 10, 'Choose a letter in the word')
stdscr.move(20, 15)
stdscr.addstr('_' * len(word))
stdscr.refresh()
gameloop(stdscr, word)
# main function for game play
def main(stdscr):
print_board(stdscr)
# if not a module then play the game.
if __name__=="__main__":
# wraps cursor see cursor doc for more info.
curses.wrapper(main)
|
96f3bb31c887bfd1bae92bb286837bdab36d0579 | AndrewPochapsky/genetic-algorithm | /algorithm.py | 2,442 | 3.671875 | 4 | import random
def generate_population(population_size: int, individual_size: int) -> list:
population = list()
for _ in range(0, population_size):
individual = [0] * individual_size
population.append(individual)
return population
def get_fitness(individual: list) -> int:
fitness = 0
for i in range(len(individual)):
modifier = 2**(len(individual) - i - 1)
fitness += individual[i] * modifier
return fitness
def crossover(parent1: list, parent2: list) -> list:
offspring = list()
parent1_threshold = random.uniform(0, 1)
for i in range(len(parent1)):
chance = random.uniform(0, 1)
if chance <= parent1_threshold:
offspring.append(parent1[i])
else:
offspring.append(parent2[i])
return offspring
def mutate(individual: list, chance=0.05):
for i in range(len(individual)):
if random.uniform(0, 1) <= chance:
individual[i] = 1 - individual[i]
def get_mating_pool(population: list, threshold=0.25) -> list:
# Sort population by fitness score.
population = sorted(population, key=lambda x: get_fitness(x), reverse=True)
slice_index = int(len(population) * threshold)
return population[0:slice_index]
def get_next_population(mating_pool: list, num_crossovers: int) -> list:
new_population = mating_pool.copy()
for _ in range(num_crossovers):
parents = random.choices(mating_pool, k=2)
offspring = crossover(parents[0], parents[1])
mutate(offspring)
new_population.append(offspring)
return new_population
def get_average_fitness(population: list) -> float:
count = 0
for individual in population:
count += get_fitness(individual)
return count / len(population)
def print_stats(generation_num, population):
print("Generation", generation_num)
print("Average: ", get_average_fitness(population))
print()
individual_size = 5
population_size = 1000
population = generate_population(population_size, individual_size)
ideal_fitness = 2**(individual_size) - 1
num_generations = 10
print("Population size:", population_size)
print("Ideal Fitness:", ideal_fitness, "\n")
for i in range(num_generations):
print_stats(i, population)
mating_pool = get_mating_pool(population)
num_crossovers = len(population) - len(mating_pool)
population = get_next_population(mating_pool, num_crossovers)
|
51cb98326912c3c9fdce3a75ceeecbf4ec7fdd5d | pieteradejong/joie-de-code | /strdistanceapp/similarity.py | 1,018 | 3.609375 | 4 | import math
import sys
import unittest
# assumes two points in R^2 (points in 2D-space)
class Similarity():
def euclidian(self, a, b):
return self.minkowski(a, b, 2)
def manhattan(self, a, b):
return self.minkowski(a, b, 1)
def minkowski(self, a, b, p):
p = float(p) # ensure 1/p is accurate when p is int
sum = math.fabs(a[0]-b[0])**p + math.fabs(a[1]-b[1])**p
return sum**(1/p)
def cosine(self, a, b):
dotprod = a[0] * b[0] + a[1] * b[1]
a_Magnitude = math.sqrt(a[0]**2 + a[1]**2)
b_Magnitude = math.sqrt(b[0]**2 + b[1]**2)
res = float(dotprod) / (a_Magnitude * b_Magnitude)
return res
def jaccard(self, a, b):
a_set = set(a)
b_set = set(b)
size_of_intersection = len( a_set.intersection(b_set) )
size_of_union = len( a_set.union(b_set) )
return float(size_of_intersection) / size_of_union
if __name__ == '__main__':
Similarity().main()
class MyTest(unittest.TestCase):
def test(self):
self.assertEqual(fun(3), 4)
|
91616f475693d64af7857fefd456afe6274ae984 | Yashsharma534/Python_Projects | /dice.py | 417 | 3.5625 | 4 | from tkinter import *
import random
root = Tk()
root.geometry('500x500')
root.title("Dice Simulator")
label = Label(root,text ='',font=('Helvetica',260))
def roll_dice():
dice = ['\u2680','\u2681','\u2682','\u2683','\u2684','\u2685']
label.configure(text=f'{random.choice(dice)}')
label.pack()
button = Button(root,text='roll dice',foreground='green',bg='blue',command=roll_dice)
button.pack()
root.mainloop()
|
f96d339a1b20e72591c9bc1e64f32dc752727bed | Seeun-Lim/Codeup | /6078.py | 76 | 3.640625 | 4 | while(True):
n=input()
print(n)
if (n == 'q'):
break |
bff98ff95997d1a267aaedbf9d270f19b0ed5bb7 | blegloannec/CodeProblems | /Rosalind/LEXV.py | 629 | 3.578125 | 4 | #!/usr/bin/env python3
from itertools import product
A = input().split()
n = int(input())
## lazy hack over itertools
def main0():
S0 = ' '
for P in product(A,repeat=n):
S = ''.join(P)
d = 0
while d<n and S[d]==S0[d]:
d += 1
for i in range(d+1,n):
print(S[:i])
print(S)
S0 = S
#main0()
## custom recursion (actually simpler)
def nest(S):
if len(S)<n:
for a in A:
S.append(a)
yield ''.join(S)
yield from nest(S)
S.pop()
def main1():
for S in nest([]):
print(S)
main1()
|
ce91ce16a97dae37a8f86b7a62d7582a5a85d6cd | SmischenkoB/campus_2018_python | /Yehor_Dzhurynskyi/1/task9.py | 378 | 4.125 | 4 | from string_is_24_hour_time import string_is_24_hour_time
time24 = input('Enter 24-hour time string: ')
if string_is_24_hour_time(time24):
time_parts = time24.partition(':')
hours = int(time_parts[0])
minutes = int(time_parts[2])
noon = 'pm' if hours >= 12 else 'am'
print('%.2d:%.2d %s' % (hours % 12, minutes, noon))
else:
print('not a valid time')
|
d2616fb15073b393e522f09f3237253f2cce67a7 | breezeiscool/Python-Learning | /Assignment/3 ways of Fibonacci seq.py | 1,689 | 3.625 | 4 | # Student:Coco
# Assistant:Peter
# Scores:97
# P.S. Done great ! You successfully finish the assignments but three points are deducted because you didn't use an expected function.
# btw, your hard work makes me hang my head in shame.
# Precise:
# As we all know:fibs(0)=0,fibs(1)=1,
# fibs(n)=fibs(n-1)+fibs(n-2)
"""method 1 : using list to present the n-th number in fibs seq."""
fibs = [1, 1]
n = int(input("Q1:How many fibs numbers do you want:"))
for i in range(0, n):
fibs.append(fibs[-2] + fibs[-1])
print(fibs[0:n])
# Thinking:how to use the func.
'''
def fibs(n):
list=[1,1]
if n<=2:
return 1
for i in range(n):
list.append(list[i]+list[i+1])
return list[n-1]
print(fibs(4))
'''
"""method 2 : simple multiple work"""
c, d = 0, 1
t = int(input("Q2:In what rank of number in the fibs seq do you want to know:"))
i = 1
while i <= t:
# print(b, end=",") # if you want the result to print in a row.
c, d = d, c+d
i = i+1
else:
print(c)
# # extra check(failed 5555555555555555555) # Piggy just'cause the list fibs[]'s index start from 0....
if c == fibs[t-1]: # decrease t by 1
print("After inspection,the output is precisely meet your need!")
else:
print("hmm,the answer didn't match successfully.It seems to have sth wrong with my algorithm...")
"""method 3 : recursion"""
def fibs(n): # Pretty! it's quite a masterpiece for u since recursion is such a difficulty for a neophyte.
if n == 1 or n == 2:
return 1
else:
return fibs(n-1) + fibs(n-2)
result = fibs(int(input("Q3:input the rank you want:")))
print(result)
|
624d46d50ed5e6961859cdbe42761d2f693a6a0d | harishsakamuri/python-files | /basic python/ramesh5.py | 195 | 3.9375 | 4 | str1=("welcome")
print(str1)
str2=(" to hyderabad")
print(str2)
print(str1+str2)
str3=(str1+str2)
print(str3[1:10])
print(str3[-5:])
print(str3[:-5])
print(str3[-7:])
print(str3[:-7])
|
65364814ba850712390b9e54af7693bbf85587d4 | minzhou1003/intro-to-programming-using-python | /practice10/12_2.py | 1,005 | 4.03125 | 4 | # minzhou@bu.edu
class Location:
def __init__(self, row, column, maxValue,):
self.row = row
self.column = column
self.maxValue = maxValue
def locateLargest(a):
maxValue = a[0][0]
row = 0
col = 0
for i in range(len(a)):
for j in range(len(a[i])):
if a[i][j] > maxValue:
maxValue = a[i][j]
row = i
col = j
return Location(row, col, maxValue)
def main():
[row, col] = list(map(int, input('Enter the number of rows and columns in the list: ').split(',')))
a = []
for i in range(row):
temp_row = list(map(float, input('Enter row {}: '.format(i)).split()))
if len(temp_row) > col:
raise RuntimeError('Out of Bound Exception: col %d' % col)
a.append(temp_row)
locate = locateLargest(a)
print('The location of the largest element is {} at ({}, {})'.format(locate.maxValue, locate.row, locate.column))
if __name__ == '__main__':
main() |
597034f0609230850f3ec2c130e0c0eb24051355 | mstepovanyy/python-training | /course/lesson05/task05/numbers.py | 662 | 4.1875 | 4 | #!/usr/bin/python3
"""
Print a number of numbers in a file; each number shall count only once (e.g.
``1234`` shall count only once, not 4 times).
"""
import re
def count_numbers(file_name):
"""
Count numbers in provided file, and return total amount of it.
Args:
file_name (str): path to a file
Returns:
int : number of numbers in file.
"""
numbers = 0
with open(file_name, mode='r', encoding='utf-8') as fd:
for line in fd:
numbers += len(re.findall(r'\d+', line))
return numbers
if __name__ == '__main__':
print("Numbers count in file: {}".format(count_numbers('../../alice.txt')))
|
1907fb9ce3f2d374767d12baf72a9be27bd5ca92 | WooWooNursat/Python | /lab7/informatics/5/probB.py | 138 | 3.953125 | 4 | a = int(input())
b = int(input())
def power(a,b):
n = a
for i in range(1, b, 1):
n = n * a
return n
print(power(a, b)) |
51a7e112899216269a9aa15816225fb4064d1854 | lcsm29/edx-harvard-cs50 | /week6/mario/mario.py | 257 | 4.03125 | 4 | height = 0
while not (1 <= height <= 8):
try:
height = int(input("Height: "))
except ValueError:
height = 0
for i, line in enumerate([' ' * (height-i) + '#' * i for i in range(1, height + 1)]):
print(line + ' ' + '#' * (i + 1))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.