blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
7ef5e58cc5853c231f5ab123381e1d1e94d878d2 | bishnoiagrim/Python-practice | /level 1/assignment3/whileloop.py | 11,037 | 4.0625 | 4 | #while loops
#Assignment3 on while loop
#Agrim Rai - 11d
#2/9/2021
'''
ASSIGNMENT 3
WHILE LOOP
Q1)Print SFS 5 times.
Q2)Calculate the factorial of a given number.
Q3)WAP to calculate and print the sums of even and odd integers of the first n natural numbers.
Q3.5) WAP to input integers till user wants.Print the sum of even nos. and sum of odd nos.nt
Q4)Input any two numbers. Calculate ‘a’ to the power’ b ‘without using a**b.
Q5)Input any integer, print its individual digits.
Q6)Print the sum of digits of a given integer.
Q7)Check if the given number is an armstrong number.ex-153,407
Q8)Check if the given number is a palindrome number.
Q9)Check if the given number is a perfect number.ex-6,28
Q10) Input some numbers till the user wants. Total them and print the total.
Q11) WAP to input any no to check if it is a prime no.
Q12) WAP asking the user to guess a no from a given range. Do not allow more than 3 chances.
Q13)Write a menu- driven program to-
1)Calculate sum
2)Calculate product
3)Calculate difference
4)Calculate division
5)Exit
Q14)Print prime numbers in range(2,100).
Q15)Write a menu driven program to-
1)Check if the given number is Armstrong number.
2)Check if the given number is Palindrome number.
3)Check if the given number is a Perfect number.
(eg:- 28=1+2+4+7+14)sum of proper divisors.
4)Check if the given number is a Special number.ex-145=1!+4!+5!
5) Check if the given number is a Prime number
'''
print('''
Q1)Print SFS 5 times.
''')
i = 1
while i <= 5:
print("sfs")
i += 1
print('''
Q2)Calculate the factorial of a given number.
''')
num = int(input("Enter a number : "))
factorial = 1
while (num > 0):
factorial = factorial * num
num = num - 1
print(factorial)
print('''
WAP to input integers till user wants.Print the sum of even nos. and sum of odd nos.
''')
number = int(input("Enter a number : "))
even_Sum = 0
odd_Sum = 0
for num in range(1, number + 1):
if (num % 2 == 0):
even_Sum = even_Sum + num
else:
odd_Sum = odd_Sum + num
print("Odd numbers : ", odd_Sum)
print("Even numbers : ", even_Sum)
print('''
Q5)Input any integer, print its individual digits
''')
number = int(input("enter number : "))
while number != 0:
d = number % 10
print(d)
number = number // 10
#reverse throwing number
print('''
Q10) Input some numbers till the user wants. Total them and print the total.
''')
oddsum = 0
evensum = 0
while True:
ask = input("Enter a number to add or a string to break : ")
if ask.isdigit() == True:
if int(ask) % 2 == 0:
evensum = evensum + int(ask)
else:
oddsum = oddsum + int(ask)
else:
break
print("even sum", evensum)
print("odd sum", oddsum)
print('''
Input any two numbers. Calculate ‘a’ to the power’ b ‘without using a**b.
''')
number = int(input("Enter a number : "))
power = int(input("Enter its power : "))
import math
print(math.pow(number,power))
print('''
Q8)Check if the given number is a palindrome number.
''')
number = int(input("Enter any number :"))
temp = number
reverse_num = 0
while (number > 0):
digit = number % 10
reverse_num = reverse_num * 10 + digit
number = number // 10
if (temp == reverse_num):
print("The number is palindrome")
else:
print("Not a palindrome")
print('''
Q9)Check if the given number is a perfect number.ex-6,28
''')
n = int(input("Enter any number: "))
sum1 = 0
for i in range(1, n):
if (n % i == 0):
sum1 = sum1 + i
if (sum1 == n):
print(" Perfect number")
else:
print("Non Perfect number")
print('''
Input some numbers till the user wants. Total them and print the total.
''')
#while True:
# ask = input("Enter a number : ")
# if ask.isdigit():
# print(ask)
# sum = sum + int(ask)
#print("sum calculated is ", sum)
print('''
Q6)Print the sum of digits of a given integer.
''')
sum = 0
number = int(input("enter number : "))
while number != 0:
d = number % 10
sum = sum + d
number = number // 10
print(sum)
print('''
Q7)Check if the given number is an armstrong number.ex-153,407
''')
num = int(input("Enter a 3 digit number : "))
order = 3
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit**order
temp //= 10
if num == sum:
print(num, "- Armstrong number")
else:
print(num, "-Not an Armstrong number")
print('''
Q8)Check if the given number is a palindrome number.
''')
n = int(input("Enter a number : "))
temp = n
rev = 0
while (n > 0):
dig = n % 10
rev = rev * 10 + dig
n = n // 10
if (temp == rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
print('''
Q12) WAP asking the user to guess a no from a given range. Do not allow more than 3 chances.
''')
secret = 7
chance = 0
guess = int(input("Enter a number : "))
while chance <= 3:
if guess == secret:
print("Correct")
break
else:
chance = chance + 1
print('''
Q13)Write a menu- driven program to-
1)Calculate sum
2)Calculate product
3)Calculate difference
4)Calculate division
5)Exit
''')
print('''
1)Calculate sum
'sum'
2)Calculate product
'product'
3)Calculate difference
'difference'
4)Calculate division
'division'
5)Exit
'exit'
''')
while True:
num1 = int(input("Enter 1st number : "))
num2 = int(input("Enter 2nd number : "))
command = input("Enter a command from syntax : ")
if command == 'sum':
print(num1 + num2)
elif command == 'product':
print(num1 * num2)
elif command == 'difference':
print(num1 - num2)
elif command == 'division':
print(num1 / num2)
elif command == 'exit':
break
else:
break
print('''
Q14)Print prime numbers in range(2,100).
''')
for x in range(2, 100):
print(x)
print('''
15)Write a menu driven program to-
1)Check if the given number is Armstrong number.
'armstrong'
2)Check if the given number is Palindrome number.
'palindrome'
3)Check if the given number is a Perfect number.
(eg:- 28=1+2+4+7+14)sum of proper divisors.
'perfect'
''')
while True:
num1 = int(input("Enter the number : "))
command = input("Enter a command from synrax : ")
if command == 'armstrong':
order = num1.len()
sum = 0
temp = num1
while temp > 0:
digit = temp % 10
sum += digit**order
temp //= 10
if num1 == sum:
print(num1, "- Armstrong number")
else:
print(num1, "-Not an Armstrong number")
elif command == 'palindrome':
temp = num1
reverse_num = 0
while (num1 > 0):
digit = num1 % 10
reverse_num = reverse_num * 10 + digit
num1 = num1 // 10
if (temp == reverse_num):
print("The number is palindrome!")
else:
print("Not a palindrome!")
elif command == 'perfect':
sum1 = 0
for i in range(1, n):
if (num1 % i == 0):
sum1 = sum1 + i
if (sum1 == num1):
print(" Perfect number")
else:
print("Non Perfect number")
elif command == 'exit':
break
else:
break
'''
output:
PS C:\Users\agrimbishnoi\Desktop\STUFF\weekly 2 computer\assignment3> python .\whileloop.py
Q1)Print SFS 5 times.
sfs
sfs
sfs
sfs
sfs
Q2)Calculate the factorial of a given number.
Enter a number : 22
1124000727777607680000
WAP to input integers till user wants.Print the sum of even nos. and sum of odd nos.
Enter a number : 22
Odd numbers : 121
Even numbers : 132
Q5)Input any integer, print its individual digits
enter number : 22
2
2
Q10) Input some numbers till the user wants. Total them and print the total.
Enter a number to add or a string to break : 22
Enter a number to add or a string to break : 22
Enter a number to add or a string to break : 22
Enter a number to add or a string to break : d
even sum 66
odd sum
Input any two numbers. Calculate ‘a’ to the power’ b ‘without using a**b.
Enter a number : 22
Enter its power : 22
3.4142787736421956e+29
Q8)Check if the given number is a palindrome number.
Enter any number :22
The number is palindrome
Q9)Check if the given number is a perfect number.ex-6,28
Enter any number: 22
Non Perfect number
Input some numbers till the user wants. Total them and print the total.
Q6)Print the sum of digits of a given integer.
enter number : 22
4
Q7)Check if the given number is an armstrong number.ex-153,407
Enter a 3 digit number : 407
407 - Armstrong number
Q8)Check if the given number is a palindrome number.
Enter a number : 22
The number is a palindrome!
Q12) WAP asking the user to guess a no from a given range. Do not allow more than 3 chances.
Enter a number : 3
Q13)Write a menu- driven program to-
1)Calculate sum
2)Calculate product
3)Calculate difference
4)Calculate division
5)Exit
1)Calculate sum
'sum'
2)Calculate product
'product'
3)Calculate difference
'difference'
4)Calculate division
'division'
5)Exit
'exit'
Enter 1st number : 2
Enter 2nd number : 3
Enter a command from syntax : sum
5
Enter 1st number : 33
Enter 2nd number : 33
Enter a command from syntax : exit
Q14)Print prime numbers in range(2,100).
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
15)Write a menu driven program to-
1)Check if the given number is Armstrong number.
'armstrong'
2)Check if the given number is Palindrome number.
'palindrome'
3)Check if the given number is a Perfect number.
(eg:- 28=1+2+4+7+14)sum of proper divisors.
'perfect'
Enter the number : 22
Enter a command from synrax : palindrome
The number is palindrome!
Enter the number : 3323
Enter a command from synrax : palindrome
Not a palindrome!
Enter the number : 1221
Enter a command from synrax : exit
PS C:\Users\agrimbishnoi\Desktop\STUFF\weekly 2 computer\assignment3>
''' |
d9677584568315fd0394686442ccd34a87b65cfa | dexterneutron/pybootcamp | /level_3/countstrings.py | 381 | 3.953125 | 4 | """Exercise 1: Write a Python program to count the number of strings
where the string length is 2 or more and the first and last character are the same from a given list of strings.
Sample List : ['abc', 'xyz', 'aba', '1221']
"""
INPUT_LIST = ['abc', 'xyz', 'aba', '1221']
count=0
for el in INPUT_LIST:
if(el[0] == el[-1] and len (el) >= 2):
count += 1
print(count) |
81123ca58739a42f3ced7c8a21dc03bade6605c0 | MaximilianKlein92/Step-Intervall-Trainer | /Command-LineTrainer.py | 3,291 | 4.15625 | 4 | # This Programms runs a Timer for a Pyramid-Intervall training
# where the pause is as long the exercise
#import time for the time.sleep(x) funktion what will pause the code for 1 second
import time
def Duration (a = 0):
# The user can determine the length of the Rounds in minutes. If one does not enter the correct format one gets a second change
Input = True
global Min
while Input == True:
try:
Min = float(input ("How long would you like to train (in minutes): "))
Input = False
except ValueError:
print("No valid input! Try This Format: 1.5 (min)")
txt = "\nYour trining time will be {} minutes or {} seconds.\nLets go:"
print (txt.format(Min, Min * 60))
def StufenInt (Min):
seconds = 0
switch = 0
Set = 0
untill = Min * 60
#start the timer.
while Set < untill:
while switch == 0: # Timer runs forword
try:
print(str(seconds).zfill(3)) #.zfill() determants amount of digits shown
seconds += 1
Set += 1
time.sleep(1)
if Set == untill:
stop # will give NameError since "stop" not defined
except NameError: # catches the name Error and deactivates timer
switch = 3
# Stop the timer with by Kernel interrupt (Cont + c) and sets the switch = 1 which lets the timer count backwords
except KeyboardInterrupt:
switch = 1
seconds = seconds -1
Set += 1
print("\tTake a Breake! \tTime remain:",untill - Set,"sec")
# Starts a loop which counts down and when the counter is at 0 sets a = 0 to start a new round
try:
while switch == 1: # timer runs backwords
print (str(seconds).zfill(3))
seconds = seconds -1
Set += 1
if Set == untill:
stop
time.sleep(1)
if seconds == 0:
print("\tLets go again!\tTime remain:{} sec".format(untill - Set))
switch = 0
except NameError:
switch = 3
print("The exercise is done. Good Job!")
def Again (again = True):
try:
while True:
Again = input ("Would you like to go again? (j/n)")
if Again == "j":
Continue
elif Again == "n":
import notAModule
else:
print ("This is not a valid input. Try again!")
except NameError:
again = True
except ModuleNotFoundError:
again = False
return again
print ("This is a timer for the Step-Intervall traing method.\nWhere your Rest Period is as long as your exercise periode.")
print ("Start your rest periode by interrupting the kernel (control + c)")
print ()
Round = True
s = KeyboardInterrupt
while Round == True:
Duration()
StufenInt(Min)
Round = Again()
print("You have done well. Get a shower and some Rest!")
|
892ebff59dd719ffd214f1d53c99ea4976627bf8 | Inimesh/PythonPracticeExercises | /2 if statement exercises/Ex_57.py | 447 | 4.40625 | 4 | ## A program that determines if a year is a leap year ##
# propmting user input
year = float(input("Please enter a year to find out if it is a leap year: "))
# Checking leap year conditions
if year % 400 == 0:
leap = True
elif year % 100 == 0:
leap = False
elif year % 4 ==0:
leap = True
else:
leap = False
# printing correct input
if leap:
print("%.0f is a leap year" % year)
else:
print("%.0f is not a leap year" % year)
|
4b0b542d1962fcb68060e4f16978058b439e981f | DrakeVorndran/aStar_maze_solving | /Maze.py | 2,081 | 4.1875 | 4 | class Maze:
"""
A class for repersenting mazes
"""
def __init__(self, height=10, width=10, walls=[], start=(0,0), end=None):
"""
walls should be an array of tuples, with the first value being the x coord and the second value being the y coord of a cell (indexed at 0 with the top left corner being 0,0) that you cannot pass through
start and end are tuples as well, with the same indexing as the walls
"""
self.start = start
self.specials = {} # for displaying, key as a tuple of a cell coord, and the value as the character that you would like to be displayed
self.height = height
self.width = width
# if end is undefined, define it as the bottom left corner
if(end):
self.end = end
else:
self.end = (width - 1, height - 1)
# create the grid that represents the maze
self.grid = [[0 for _ in range(height)] for _ in range(width)]
# add the walls, 0 being not a wall, 1 being a wall
for row, col in walls:
self.grid[col][row] = 1
def __repr__(self):
return_string = (self.width + 2) * "░░"
return_string += "\n"
for col in range(len(self.grid)):
return_string += "░░"
for row in range(len(self.grid[col])):
cell = self.grid[col][row]
if((row, col) == self.start):
return_string += "SS"
elif((row, col) == self.end):
return_string += "EE"
elif(cell == 1):
return_string += "██"
elif((row, col) in self.specials):
return_string += self.specials[(row, col)] * 2
elif(cell == 0):
return_string += " "
else:
return_string += str(cell)*2
return_string += "░░"
return_string += "\n"
return_string += (self.width + 2) * "░░"
return return_string
|
9ee0dd3becfc27e093c00769cbdcbdb172ae4445 | pavel-malin/python_work | /hello_admin.py | 2,775 | 4.125 | 4 | # Say hello to all users
user_name = ['adam', 'guest1', 'guest2', 'admin', 'fiz']
if user_name:
for user_names in user_name:
print("Hello user: " + user_names.title() + ".")
else:
print("Adding list users")
if user_name:
for user_names in user_name:
print("Hello user: " + user_names.title() + ".")
else:
print("We need to find some users!")
# Remove user name
user_name = ['adam', 'guest1', 'guest2', 'admin', 'fiz']
users_del = 'guest1'
user_name.remove(users_del)
if user_name:
if 'guest1' in user_name:
print("not delete")
elif 'guest1' not in user_name:
print("\nDelete users names: " + users_del)
user_del = 'guest2'
user_name.remove(user_del)
if 'guest2' in user_name:
print("not delete")
elif 'guest2' not in user_name:
print("Delete users names: " + user_del)
user_del = 'adam'
user_name.remove(user_del)
if 'adam' in user_name:
print("not delete")
elif 'adam' not in user_name:
print("Delete users names: " + user_del)
user_del = 'admin'
user_name.remove(user_del)
if 'admin' in user_name:
print("not delete")
elif 'admin' not in user_name:
print("Delete users names: " + user_del)
user_del = 'fiz'
user_name.remove(user_del)
if 'fiz' in user_name:
print("not delete")
elif 'fiz' not in user_name:
print("Delete users names: " + user_del)
# Check and username does not exist
user_names = ['Adam', 'Guest1', 'Guest2', 'ADMIN', 'Fiz']
for user_name in user_names:
if user_name.lower() in 'adam':
print("Is games names: " + user_name)
if user_name.lower() in 'guest1':
print("Is games names: " + user_name)
if user_name.lower() in 'guest2':
print("Is games names:" + user_name)
if user_name.lower() in 'admin':
print("Is games names: " + user_name)
if user_name.lower() in 'fiz':
print("Is games names: " + user_name)
# Compare two user lists
user_names = ['adam', 'guest1', 'guest2', 'admin', 'fiz']
user_guests = ['adam', 'guest1', 'guest2', 'admin', 'fiz', 'bob']
for user_guest in user_guests:
if user_guest in user_names:
print("User exists " + user_guest.title() + ".")
else:
print("\nSorry, not users, please to register " + user_guest.title() + ".")
print("))))")
# Comparison of two lists of users with different case
# of letters
current_users = ['bob', 'fiz', 'Adam', 'Bib', 'Jon','Bab']
new_users = ['bob', 'fiz', 'adam', 'bib', 'jon', 'bab']
for current_user in current_users:
if current_user.lower() in new_users:
print("Username such alredy exists:" + current_user.title() + "\nPlease register with a different name.")
|
4fbcf8d260db5294fada0a858efc71f25a18a1f4 | coniconon-zz/py4e_2019 | /course_1/assignment_03_01/rateperhour_v2.py | 265 | 4.0625 | 4 | hrs = input("Enter Hours:")
rate = input("Enter Rate:")
h = float(hrs)
r = float(rate)
if h <= 40.0 :
pay = h * r
print(pay)
elif h > 40.0 :
extra_hours = h - 40.0
extra_pay = extra_hours * (r * 1.5)
pay = (40.0 * r) + extra_pay
print(pay)
|
cd44535dcecb619a30090ac78f0bf17dc8acb454 | ximena777/ejercicio1 | /ejercicio1_c.py | 133 | 3.609375 | 4 | #1.c
def suma(numero1,numero2):
print int(numero1)+int(numero2)
N1=raw_input("Ingrese N1:")
N2=raw_input("Ingrese N2:")
suma(N1,N2) |
33702906214d2a29ee565f946a85eaa984c21577 | Hipstha/scrapping | /python/poo.py | 587 | 3.625 | 4 | class Casa:
#Constructor
def __init__(self, color):
self.color = color
self.consumo_de_luz = 0
self.consumo_de_agua = 0
# todas los métodos deben tener self
def pintar(self, color):
self.color = color
def prender_luz(self):
self.consumo_de_luz += 10
def abrir_ducha(self):
self.consumo_de_agua += 10
def tocar_timbre(self):
print("RIIIING")
self.consumo_de_luz += 2
# herencia
class Mansion(Casa):
def prender_luz(self):
self.consumo_de_luz += 50
mansion = Mansion("blanco")
mansion.prender_luz()
print(mansion.consumo_de_luz) |
20a7d698d41662b08767a75fa422c26825c8b48c | haru-256/bandit | /policy/_stochastic_bandits.py | 5,692 | 3.5625 | 4 | """define some policy"""
from abc import ABC, abstractmethod
from typing import Union
import numpy as np
from ._check_input import _check_stochastic_input, _check_update_input
class PolicyInterface(ABC):
"""Abstract Base class for all policies"""
@abstractmethod
def select_arm(self) -> int:
"""Select arms according to the policy for new data.
Returns
-------
result: int
The selected arm.
"""
pass
@abstractmethod
def update(self, chosen_arm: int, reward: Union[int, float]) -> None:
"""Update the reward information about each arm.
Parameters
----------
chosen_arm: int
The chosen arm.
reward: int, float
The observed reward value from the chosen arm.
"""
pass
class BasePolicy(PolicyInterface):
"""Base class for basic policies.
Parameters
----------
n_arms: int
The number of given bandit arms.
"""
def __init__(self, n_arms: int) -> None:
"""Initialize class."""
_check_stochastic_input(n_arms)
self.n_arms = n_arms
self.counts = np.zeros(self.n_arms, dtype=int)
self.cumulative_rewards = np.zeros(self.n_arms)
self.t = 0
def update(self, chosen_arm: int, reward: Union[int, float]) -> None:
"""Update the reward information about each arm.
Parameters
----------
chosen_arm: int
The chosen arm.
reward: int, float
The observed reward value from the chosen arm.
"""
_check_update_input(chosen_arm, reward)
self.t += 1
self.counts[chosen_arm] += 1
self.cumulative_rewards[chosen_arm] += reward
class UCB(BasePolicy):
"""Upper Confidence Bound.
Parameters
----------
n_arms: int
The number of given bandit arms.
"""
def __init__(self, n_arms: int) -> None:
"""Initialize class."""
super().__init__(n_arms)
def select_arm(self) -> int:
"""Select arms according to the policy for new data.
Returns
-------
arm: int
The selected arm.
"""
if 0 in self.counts:
arm = np.argmin(self.counts)
else:
arm = np.argmax(self.mean_rewards + self.correction_factor)
return arm
@property
def mean_rewards(self) -> np.ndarray:
"""
Returns:
numpy.ndarray: mean rewards each arm
"""
return self.cumulative_rewards / self.counts
@property
def correction_factor(self) -> np.ndarray:
"""
Returns:
numpy.ndarray: correction factor each arm
"""
return np.sqrt(np.log(self.t) / (2 * self.counts))
class UCBOffline(BasePolicy):
def __init__(self, n_arms: int) -> None:
"""Initialize class."""
_check_stochastic_input(n_arms)
super().__init__(n_arms)
self.correction_factor_counts = np.zeros(self.n_arms, dtype=int) # correction_factorのためのcounts
def update(self, chosen_arm: int, rewards: np.ndarray) -> None:
"""
Args:
chosen_arm (int): selected arm
rewards (numpy.ndarray): the observed rewards from selected arm. shape = (N, ), N is log size
"""
if not isinstance(chosen_arm, (int, np.int64)):
TypeError("chosen_arm must be int or numpy.int64")
if not isinstance(rewards, np.ndarray):
TypeError("rewards must be numpy.ndarray")
if rewards.ndim != 1:
TypeError("rewards must be 1 dim array")
self.t += rewards.shape[0]
self.counts[chosen_arm] += 1
self.correction_factor_counts[chosen_arm] += rewards.shape[0]
self.cumulative_rewards[chosen_arm] += rewards.mean()
def select_arm(self) -> int:
"""Select arms according to the policy for new data.
Returns
-------
arm: int
The selected arm.
"""
if 0 in self.counts:
arm = np.argmin(self.counts)
else:
arm = np.argmax(self.mean_rewards + self.correction_factor)
return arm
@property
def mean_rewards(self) -> np.ndarray:
"""
Returns:
numpy.ndarray: mean rewards each arm
"""
return self.cumulative_rewards / self.counts
@property
def correction_factor(self) -> np.ndarray:
"""
Returns:
numpy.ndarray: correction factor each arm
"""
return np.sqrt(np.log(self.t) / (2 * self.correction_factor_counts))
class UCB1(BasePolicy):
"""Upper Confidence Bound.
Parameters
----------
n_arms: int
The number of given bandit arms.
"""
def __init__(self, n_arms: int) -> None:
"""Initialize class."""
super().__init__(n_arms)
def select_arm(self) -> int:
"""Select arms according to the policy for new data.
Returns
-------
arm: int
The selected arm.
"""
if 0 in self.counts:
arm = np.argmin(self.counts)
else:
arm = np.argmax(self.mean_rewards + self.correction_factor)
return arm
@property
def mean_rewards(self) -> np.ndarray:
"""
Returns:
numpy.ndarray: mean rewards each arm
"""
return self.cumulative_rewards / self.counts
@property
def correction_factor(self) -> np.ndarray:
"""
Returns:
numpy.ndarray: correction factor each arm
"""
return np.sqrt(2 * np.log(self.t) / self.counts)
|
96adfdfef9aa2143fd6f78289912644eb167d68b | inigopm/text2imageApp | /util/pictures.py | 1,128 | 3.84375 | 4 | from os import listdir, rename
from os.path import isfile, join
import random
def retrieve_pictures_names_in_folder(folder_path: str):
"""
This functions returns a list with the file names of a given folder.
folder_path (str): path of the folder that we are going to check
"""
pictureList = []
# Iterate through all the elements in the folder "folder_path"
for f in listdir(folder_path):
# if its a file then add it to the list
if isfile(join(folder_path, f)):
pictureList.append(f)
return pictureList
def random_pictures(n: int, pictureList: list):
"""
This function returns "n" different numbers
n (Int): quantity of numbers to return
pictureList (list): picture names list
"""
if n >= len(pictureList):
return pictureList
elif n <= 0:
return []
used = set()
while len(used) < n:
r = random.randrange(0, len(pictureList))
# If the picture is not in the list add it
if pictureList[r] not in used:
used.add(pictureList[r])
return list(used)
|
15874f6bc1f1eb758e9728a3de44aa23e90f0de2 | hsiang0107/python | /python101/2017/multipler.py | 303 | 3.921875 | 4 | InputStr = input('Please input an integer:')
num = int(InputStr)
if num <= 0:
raise ValueError('must greater than 0 !')
for first in range(1, num+1):
for second in range(1, num+1):
result = first * second
print('{0} * {1} = {2}'.format(first, second, result))
print('')
|
b6d25d3ebf44030cb11854bbccd227191e6edc03 | omer-ayhan/Python101 | /Alıştırmalar/alıştırma_2.1.py | 596 | 3.953125 | 4 | def computePay(hrs):
if hrs>=0 and hrs<=40:
# pay is 10 TL between 0 and 40 hours
pay = 10
elif hrs>40:
# pay is 15 TL if it's more than 40 hours
pay = 15
else:
print("please enter a valid number")
quit()
# computes the brut pay
return hrs * pay
try:
work_hrs = float(input("Enter hours: "))
# saves the residual value of our "computePay" function to "brut_pay" variable
brut_pay = computePay(work_hrs)
print("Your brut pay:", brut_pay)
except ValueError:
print("Please enter a number ")
quit()
|
ac52a754e13dadc34c4ee80c2e58c655a6d037bf | vivek28111992/Python_100Days | /Day19/generator.py | 831 | 4.28125 | 4 | """
The generator is a simplified version of the iterator
"""
def fib(n):
"""builder"""
a, b = 0, 1
for _ in range(n):
a, b = b, a+b
yield a
"""
The generator evolved into a coroutine.
The generator object can send()send data using methods, and the sent data will become yieldthe value obtained by the expression in the generator function . In this way, the generator can be used as a coroutine, which is simply a subroutine that can cooperate with each other.
"""
def calc_avg():
"""Streaming average"""
total, counter = 0, 0
avg_value = None
while True:
value = yield avg_value
total, counter = total + value, counter+1
avg_value = total/counter
if __name__ == '__main__':
fib(5)
gen = calc_avg()
next(gen)
print(gen.send(10))
print(gen.send(20))
print(gen.send(30))
|
5e5a42db9755e7b76ad8ad842e6c759e480723d9 | pbarton666/PES_Python_examples_and_solutions | /solution_python1_chapter05_function.py | 895 | 4.25 | 4 | #solution_python1_chapter05_function.py
def outer_function(operation, subtract_this):
"takes an operation and a number to subtract"
thing_to_subtract=subtract_this
def add_me(a, b):
"adds two numbers"
return (a + b)
def mult_me(a, b):
"multiplies two numbers"
return a * b
#a dict of possibilities
op_dict={"addition": add_me,
"multiplication": mult_me}
def inner_function(a,b):
"inner-most function"
func=op_dict.get(operation, None)
nonlocal thing_to_subtract
fs= "You asked me to perform {} on {} and {} then subtract {}. I got {}."
if func:
print(fs.format(operation, a, b, subtract_this, func(a,b)-subtract_this))
else:
print("The operation you provided {} is not yet supported")
return inner_function
execute_this_with_two_args=outer_function("addition", 10)
execute_this_with_two_args(2,3)
|
eefe89bd4b1b648369f0a34143bc0397ad686811 | khadak-bogati/Introduction-to-Computer-Science-and-Programming-Using-Python | /Prblomeset2.py | 3,236 | 3.96875 | 4 | Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.
The following variables contain values as described below:
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
monthlyPaymentRate - minimum monthly payment rate as a decimal
For each month, calculate statements on the monthly payment and remaining
balance. At the end of 12 months, print out the remaining balance. Be sure to print out no more than two decimal digits of accuracy - so print
=======================================================
A summary of the required math is found below:
Monthly interest rate= (Annual interest rate) / 12.0
Minimum monthly payment = (Minimum monthly payment rate) x (Previous balance)
Monthly unpaid balance = (Previous balance) - (Minimum monthly payment)
Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
We provide sample test cases below. We suggest you develop your code on your own machine, and make sure your code passes the sample test cases, before you paste it into the box below.
======================================================================================
set1
....................
# Test Case 1:
balance = 42
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
# Result Your Code Should Generate Below:
Remaining balance: 31.38
# To make sure you are doing calculation correctly, this is the
# remaining balance you should be getting at each month for this example
Month 1 Remaining balance: 40.99
Month 2 Remaining balance: 40.01
Month 3 Remaining balance: 39.05
Month 4 Remaining balance: 38.11
Month 5 Remaining balance: 37.2
Month 6 Remaining balance: 36.3
Month 7 Remaining balance: 35.43
Month 8 Remaining balance: 34.58
Month 9 Remaining balance: 33.75
Month 10 Remaining balance: 32.94
Month 11 Remaining balance: 32.15
Month 12 Remaining balance: 31.38
solve
...............................
balance = 42
annualInterestRate=0.2
monthlyInterestRate=0.04
RemainingBalance: 31.38
for i in range(12):
balance = balance - (balance*monthlyInterestRate) + ((balance - (balance* monthlyInterestRate)) * (annualInterestRate/12))
print("RemainingBalance: ", round(balance, 2))
output
...................................
RemainingBalance: 40.99
RemainingBalance: 40.01
RemainingBalance: 39.05
RemainingBalance: 38.11
RemainingBalance: 37.2
RemainingBalance: 36.3
RemainingBalance: 35.43
RemainingBalance: 34.58
RemainingBalance: 33.75
RemainingBalance: 32.94
RemainingBalance: 32.15
RemainingBalance: 31.38
#test case 2
balance = 482
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
for i in range(12):
balance= balance-(balance*monthlyPaymentRate)+((balance-(balance*monthlyPaymentRate))*(annualInterestRate/12))
print("Remaining Balance: ", round(balance,2))
|
63920c7febe60b5bbb68790bec7ed607e53cf47f | QiWang-SJTU/AID1906 | /Part1 Python base/02Object_oriented/03Exercise_code/Day09/assignment01.py | 496 | 3.59375 | 4 | class Cat:
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def play(self):
print("有一只名为%s,%d岁的%s猫在玩耍" % (self.name, self.age, self.sex))
my_cat = Cat("Eva", 2, "母")
my_cat.play()
class Computer:
def __init__(self, brand):
self.brand = brand
def cal(self):
print(self.brand + "能计算")
my_computer = Computer("Lenovo")
my_computer.cal()
|
4290b0544db0ba87e6af6de075b7407681ea30d3 | acidjackcat/codeCampPython | /Training scripts/Cars_p1.py | 163 | 3.65625 | 4 | fname = 'Igor'
lname = 'Awesome'
print(('Hello {0}, your full name is {0} {1}'.format(fname, lname))*5)
geeks = 'Geeks for Geeks'
print(('{0}'.format(geeks))*3)
|
0989915dc33ecb8742d063b957087de16d058abc | CyberAmmo/book-scraping | /menu.py | 942 | 4 | 4 | from app import books
USER_CHOICE = '''Enter one of the following:
- 'b' to look best books
- 'c' to look at the cheapest books
- 'n' to get the next book on the page
- 'q' to exit
Enter your choice: '''
def print_best_books():
best_books = sorted(books, key=lambda x: x.rating * -1)[:5]
for book in best_books:
print(book)
def cheapest_book():
cheap_book = sorted(books, key=lambda x: x.price)[:5]
for book in cheap_book:
print(book)
books_generator = (x for x in books)
def get_next_book():
print(next(books_generator))
user_choices = {
'b': print_best_books,
'c': cheapest_book,
'n': get_next_book
}
def menu():
user_imput = input(USER_CHOICE)
while user_imput != 'q':
if user_imput in ('b', 'c', 'n'):
user_choices[user_imput]()
else:
print('Please enter a valid command!')
user_imput = input(USER_CHOICE)
menu()
|
23735f7b40479d0d73e9fd548c79bf986443a3bd | jaxonL/adventofcode | /2018/5/polymer.py | 6,958 | 3.8125 | 4 | # assuming ascii input
test1 = 'dabAcCaCBAcCcaDA'
test2 = 'aabAAB'
test3 = 'Xxadf'
test4 = 'XxSsdDIijNnJACszZScZfFhHQyYrRqzdXTtxDEeNnGgOaAcCMcCLlMmogQeEqGgFfGyYuUOIiYyhHlLmUulAUKkudDOoDdaLGRrgoDdDdGgRruUhJLljQqdwWDZzHXxppPTwWCcZzDmfFlLPpdDSsgGtFfTEeTOotyYMOGgkJjKZUuQdNnDhHvVntKkTNqTjJeEVkZzttTYyTDdIiRrqQyYYyxbBXLlKHhvtYyzoKMmiIkaAUvVuvEejoOJUuQoOLlLloOxoOXaAqYYXxyzMmZyoOVhHIiIKfFkiIKAaUukRrKQqASsakLgGlGgLxXhHmcCzZxXMWdUulLJjDwnNYkKFfZzpPVuUvHhbQqIiLRrlEeVvBQJjlLGgjYyJoAalxXuUqgGQLQqOqNJjzZnyOusSUeEFfodcLuUlCcCIiNnGgaADVwWGgvZtTewWENnSszBKkDdeEYyt'
expected4 = 'ApTDILBt'
DIFFERENCE = ord('a') - ord('A')
INDEX_SHIFT = ord('A')
# initial code used to logic my way around the problem before involving file input
# def parsePolymerString(source):
# global DIFFERENCE
# # start with simple string
# baseBuffer = ''
# count = 0
# while True: # iter for reading in chars
# if count >= len(source):
# break
# currChar = source[count]
# count += 1
# lastIndex = len(baseBuffer) - 1
# if lastIndex < 0: # nothing to compare to
# baseBuffer += currChar
# count += 1
# continue
# previousChar = baseBuffer[lastIndex]
# # print(count, lastIndex)
# # print('res =', abs(ord(currChar) - ord(previousChar)), '|', currChar, ord(currChar), '-', previousChar, ord(previousChar))
# # print(DIFFERENCE)
# while DIFFERENCE == abs(ord(currChar) - ord(previousChar)): # if equal, update curr and prev
# # print(previousChar, 'and', currChar)
# baseBuffer = baseBuffer[:lastIndex] # remove the thing
#
# # update previous char
# lastIndex = lastIndex - 1
# # print(lastIndex)
# # print(len(baseBuffer))
# if lastIndex < 0:
# break
# previousChar = baseBuffer[lastIndex]
#
# # read in comparison char
# count += 1
# if count >= len(source):
# break
# currChar = source[count]
#
# if lastIndex >= 0:
# baseBuffer += currChar
#
# return baseBuffer
# print(parsePolymerString(test1)) # logic works -- now to parse file
# print('string parse:', parsePolymerString(test4)) # logic works -- now to parse file
# print('expected:', expected4)
def parsePolymer(characterOccurenceCounter, filename):
inputFile = open(filename, 'r')
global DIFFERENCE
global INDEX_SHIFT
# start with simple string
baseBuffer = ''
previousChar = ''
while True: # iter for reading in chars
# print(baseBuffer)
currChar = inputFile.read(1).strip()
if not currChar: # eof
# print('eof')
break
if not previousChar: # nothing to compare to
# print('last ind', lastIndex, 'nothing to compare to')
baseBuffer += currChar
characterOccurences[ord(currChar.upper()) - INDEX_SHIFT] += 1 # incr char occurence in final string
previousChar = currChar
continue
# print(baseBuffer, ' -- read', currChar, '-- comparing to', previousChar)
# print('res =', abs(ord(currChar) - ord(previousChar)), '|', currChar, ord(currChar), '-', previousChar, ord(previousChar))
while DIFFERENCE == abs(ord(currChar) - ord(previousChar)):
# print('\t', previousChar, currChar, 'match') # it's a match!!
characterOccurences[ord(currChar.upper()) - INDEX_SHIFT] -= 1 # decr char occurence in final string
lastIndex = len(baseBuffer) - 1
# case 1 - after comp, baseBuffer is empty -> main loop
if lastIndex == 0:
baseBuffer = '' # pop the char we matched
previousChar = ''
break
# case 2 - after comp, baseBuffer has more chars -> stay in secondary loop
baseBuffer = baseBuffer[:lastIndex] # remove the thing
# update previous char
previousChar = baseBuffer[lastIndex - 1]
# print('\tinner loop; new buffer:', baseBuffer)
# read in comparison char
currChar = inputFile.read(1)
# print('\tinner loop; next char (not comp\'ed yet):', currChar, 'to prevc', previousChar)
if not currChar:
break
# print(lastIndex)
# print(len(baseBuffer))
# if lastIndex < 0:
# break
# previousChar = baseBuffer[lastIndex]
# print('\treverse comparison - read', currChar, '-- comparing to', previousChar, 'at ind', lastIndex)
# # if lastIndex >= 0:
# if not currChar:
# break
# if lastIndex >= 0:
# baseBuffer += currChar
# case 1 (outside of inner loop): should not add anything and just continue the loop
if not previousChar:
continue
# case 3 if currChar and previousChar are different, append it
baseBuffer += currChar
previousChar = currChar
characterOccurences[ord(currChar.upper()) - INDEX_SHIFT] += 1 # incr char occurence in final string
inputFile.close()
return baseBuffer
def replaceAllOf(char, targetString):
# O(n) soln
resultingString = ''
for x in targetString:
if x.lower() != char.lower():
resultingString += x
return resultingString
def getFoldOccurences(reducedPolymer):
occurences = [0] * 26
totalLength = len(reducedPolymer) # try to reduce times calculated
for x in range(totalLength):
currChar = reducedPolymer[x]
distanceFromX = 1
while (x + distanceFromX < totalLength) and (x - distanceFromX > -1): # while these indices still exist
lhsChar = reducedPolymer[x - distanceFromX]
rhsChar = reducedPolymer[x + distanceFromX]
if DIFFERENCE == abs(ord(lhsChar) - ord(rhsChar)):
distanceFromX += 1
else:
break
occurences[ord(currChar.upper()) - INDEX_SHIFT] += distanceFromX - 1 # incr char occurence
# print(currChar, 'contributes', distanceFromX -1, 'folds -- total', occurences[ord(currChar.upper()) - INDEX_SHIFT])
return occurences
characterOccurences = [0] * 26 # for 26 letters in the alphabet
polymer = parsePolymer(characterOccurences, 'd5.in')
foldsDueToChar = getFoldOccurences(polymer)
# print('polymer:', polymer)
print('1st polymer len:', len(polymer))
# for x in range(1,len(polymer)):
# print(x, ':', polymer[x])
maxInd = 0
for x in range(26):
# print(chr(x + INDEX_SHIFT), ':', foldsDueToChar[x], chr(maxInd + INDEX_SHIFT), '(max):', foldsDueToChar[maxInd])
if foldsDueToChar[x] > foldsDueToChar[maxInd]:
# print(chr(x + INDEX_SHIFT), '>', chr(maxInd + INDEX_SHIFT))
maxInd = x
# elif foldsDueToChar[x] == foldsDueToChar[maxInd]:
# print('equality for', chr(x + INDEX_SHIFT), chr(maxInd + INDEX_SHIFT))
# else:
# print(chr(x + INDEX_SHIFT), '<', chr(maxInd + INDEX_SHIFT))
removeChar = chr(maxInd + INDEX_SHIFT)
# print(removeChar)
newPolymer = replaceAllOf(removeChar, polymer)
# print(newPolymer) # used in the console with output directed to a file called secondPart.in
notUseful = [0]*26
finalPolymer = parsePolymer(notUseful, 'secondPart.in')
print('final length:', len(finalPolymer))
|
70dbdf2df86bb5bc27e885a4d688efca99c650c2 | jbrummal/pythonclass | /Alta3DropBox/listcsv-02.py | 632 | 3.765625 | 4 | #!/usr/bin/python3
"""using csv data"""
import csv
def main():
# subscriberdat = open('mockcsv.csv', 'r')
with open(r'C:\Users\Achimedes\Dropbox\2019-05-06 vzw pyans\mockcsv.csv', 'r') as subscriberdat:
subscriberlist = csv.reader(subscriberdat, delimiter=",")
print(subscriberlist)
with open(r'C:\Users\Achimedes\Dropbox\2019-05-06 vzw pyans\users.txt', 'w') as usershss:
for row in subscriberlist:
#print(row[0], row[3], file=usershss)
usershss.write(row[0] + row[3] + "\n")
input()
main() |
0c590e8a3273592e5efdb213ac2d171ca647b580 | yamendrasinganjude/200244525045_ybs | /day9/vehicalRegNumValidOrNot.py | 377 | 3.890625 | 4 | '''
4. Write a python program to check given car registration number is valid Maharashtra state registration number or not?
'''
import re
vehicalNum = input("Enter Vehical Number : ")
matched = re.fullmatch("MH\d{2}[A-Za-z]{2}\d{4}", vehicalNum)
if matched != None:
print(vehicalNum, "is Valid Vehical number..")
else:
print(vehicalNum, "is not Valid Vehical number..") |
9b1b2dc8229db4749f30b1af329ea27b28120206 | shahil-chauhan/python_programs | /Q9.py | 652 | 3.796875 | 4 | '''
Write a program that computes the net amount of a bank account
based a transaction log from console input. The transaction
log format is shown as following:
Suppose the following input is supplied to the program:
D 300
D 300
W 200
D 100
D means deposit while W means withdrawal.
Then, the output should be:
500
'''
total_amt = 0
while True:
tran = input("Enter the transactions: ")
if tran == '':
break
else:
tran = tran.split()
if tran[0].upper() == 'D':
total_amt = total_amt + int(tran[1])
elif tran[0].upper() == 'W':
total_amt = total_amt - int(tran[1])
print(total_amt)
|
472d50778779715026cb861317989330d882418a | kujin521/pythonObject | /第五章/列表/range函数生成列表.py | 584 | 4.3125 | 4 | '''任务:输入一个整数num,用range()函数产生一个从num开始的10个整数组成的列表listx;
将列表listx中的每个元素的值乘以2,形成一个新的列表listy,输出两个列表。
'''
#####请在下面标有序号的注释后面填写程序#####
# (1)输入整数num
num=int(input())
# (2)用range()函数产生列表 listx
listx=list(range(1, 11))
# 输出列表
print(listx)
# (3)将列表listx中的每个元素的值乘以2,形成一个新的列表listy
listy=[x*2 for x in listx]
# 输出列表
print(listy)
##### 程序结束 ##### |
e4e1c66403e0416a9bde8b2610b2a2a809171023 | alona22193/wwc | /conditionals.py | 1,105 | 4.1875 | 4 | #temp = int(raw_input('What is the temperature?'))
#print('You should bring the following items:')
#if temp <= 40:
# print('Coat')
# print('Hat')
# print('Gloves')
#elif temp <= 70:
# print('Coat')
# print('Hat')
#else:
# print('Nothing!')
#meal_price = raw_input('How much was your meal?')
#tip = float(meal_price) * .20
#total = tip + float(meal_price)
#print('You should tip $ ' + str(tip))
#print('Your total cost would be ' + str(tip + float(meal_price)))
meal_price = float(raw_input('How much was your meal? '))
print('How would you rate the service? ')
print('a. Not so good')
print('b. Good')
print('c. Excellent!')
chosen_option = raw_input('Choose an option: ')
# Here's where conditionals come in...
if chosen_option == 'a':
percentage = .15
elif chosen_option == 'b':
percentage = .18
elif chosen_option == 'c':
percentage = .20
else:
print('You did not enter a valid option')
percentage = .20
tip = meal_price * percentage
total_price = meal_price + tip
print('You should tip $' + str(tip))
print('Your total cost would be $' + str(total_price))
|
26b3637b63a007a57d880156dfb1f3b274ba4dc7 | josh-W42/huffman_encoding | /problem_3.py | 10,607 | 4.09375 | 4 | import sys, heapq
def huffman_encoding(data):
'''
Compresses the data given by encoding it into binary by the huffman algorithm.
Args:
data(str): information to be compressed
Returns:
Encoded Data(str) of binary code.
A tree generated from the huffman algorithm used to decode the binary.
'''
if type(data) != str:
raise TypeError('param: data, needs to be of type str')
elif len(data) == 0:
raise ValueError('param: data, cannot be empty string')
frequency = dict({})
# step one, count the frequency
for item in data:
if frequency.get(item):
frequency[item]['frequency'] += 1
else:
frequency[item] = {'frequency': 1, 'huffman_code': None}
# step two, create priority queue
freq_list = list()
for key, value in zip(frequency.keys(), frequency.values()):
new_node = Node(key, value['frequency'])
freq_list.append(new_node)
heapq.heapify(freq_list)
# step three (going to be repeated) pop out two nodes with min freqeuncy (heapq.heappop)
tree = Tree()
# To handle single char inputs
if len(freq_list) == 1:
freq_list[0].huffman_key = '0'
while len(freq_list) >= 1:
if len(freq_list) == 1:
tree.set_root(freq_list[0])
break
else:
left_node = heapq.heappop(freq_list)
right_node = heapq.heappop(freq_list)
# for step 6
left_node.huffman_key = '0'
right_node.huffman_key = '1'
# step four (going to be repeated) create a new node wiht a freq = sum of the two nodes poped out
# This new node -> Huffman tree, and the two nodes would become the children. The lower frequency
# node becomes a left child, and the higher frequency node becomes the right child. Reinsert the
# newly created node back into the priority queue.
new_val = left_node.freq + right_node.freq
new_node = Node(new_val, new_val)
new_node.prev = left_node
new_node.next = right_node
heapq.heappush(freq_list, new_node)
# Phase 2
# traverese the tree,
# use the frequency dictionary to add in the huffman code
# Then finally translate the orginal data into a code
for key in frequency.keys():
frequency[key]['huffman_code'] = tree.huffman_code(key)
final_encoding = ''
for letter in data:
final_encoding += frequency[letter]['huffman_code']
return final_encoding, tree
def huffman_decoding(data, tree):
'''
Decodes the input data generated from the huffman algorithm
Args:
data(str): binary code in str data type form.
tree(Tree): a tree generated from the huffman_encoding function
Returns:
The decoded data.
An empty string if an error occured.
'''
if type(data) != str or type(tree) != Tree:
raise TypeError('Requires data of type str and tree of type Tree')
final_decoding = ''
node = tree.get_root()
index = 0
while True:
# For single character strings, there is only one node
if node == tree.get_root() and (not node.has_left_node() or not node.has_right_node()):
final_decoding += node.char
index += 1
if index == len(data):
break
elif type(node.char) == str:
if final_decoding == '':
final_decoding = node.char
else:
final_decoding += node.char
# Reset the node whenever a character is encountered. Since all char nodes are leafs of the tree.
node = tree.get_root()
elif index == len(data):
break
elif data[index] == "0":
node = node.prev
index += 1
elif data[index] == "1":
node = node.next
index += 1
return final_decoding
class Node(object):
def __init__(self, letter, freq):
self.char = letter
self.freq = freq
self.prev = None
self.next = None
self.huffman_key = None
def has_left_node(self):
'''
Checks if current node has left node
Returns:
True, if there is a left node
False, Otherwise
'''
return not self.prev is None
def has_right_node(self):
'''
Checks if current node has right node
Returns:
True, if there is a right node
False, Otherwise
'''
return not self.next is None
def get_left_node(self):
'''
Gets the left Node of current node
Returns:
Left node(Node) is it exists,
None, otherwise
'''
if self.has_left_node:
return self.prev
else:
return None
def get_right_node(self):
'''
Gets the right Node of current node
Returns:
Right node(Node) is it exists,
None, otherwise
'''
if self.has_right_node:
return self.next
else:
return None
def __lt__(self, other):
return self.freq < other.freq
def __gt__(self, other):
return self.freq > other.freq
class Tree:
def __init__(self):
self.root = None
def set_root(self, node):
'''
Sets the root node of the tree
Args:
node(Node): node
'''
self.root = node
def get_root(self):
'''
Get the root of the Tree
Returns:
A (Node) object.'''
return self.root
def print(self):
'''Prints the current tree to the console'''
print("Printing Tree: \n")
self.print_tree(self.root)
def print_tree(self, root):
'''
Prints the tree to the console from the root.
Args:
root(Node): a root of a tree
'''
print('data:', root.char, root.freq)
if root.has_left_node():
print(root.char, "left")
self.print_tree(root.get_left_node())
if root.has_right_node():
print(root.char, "right")
self.print_tree(root.get_right_node())
def huffman_code(self, key):
'''
Searches the tree for the key specified and generates a Huffman code for the path to the key.
Args:
key(str): A letter to be coded by huffman encoding.
Returns:
(str) string version of the Huffman code for a particular key within the tree.
None if no key is found.
'''
output = self.generate_code(key, self.root)
return output[::-1]
def generate_code(self, key, root):
'''Helper function for the huffman_code method'''
output = None
if root.has_left_node():
output = self.generate_code(key, root.get_left_node())
if root.has_right_node() and output is None:
output = self.generate_code(key, root.get_right_node())
if root.char == key and not root.huffman_key is None:
return root.huffman_key
elif not output is None and not root.huffman_key is None:
return output + root.huffman_key
else:
return output
''' Phase one, count the frequency of each !unique! character use
Ok so we need a doublely linked list queue//// NOPE JUST USE heapq and minheap
We may need a dictionary that contains information on the frequency of letters
We need a tree/node structure!
most likely O(n^2) worst case O(n log k) average case
'''
def test_suite():
'''
Performs a series of tests on the huffman_encoding and huffman_decoding functions
'''
print('\nBasic Function tests \n')
print('Encoding Null Input Test: ', end=' ')
try:
huffman_encoding(None)
except TypeError:
print('pass')
else:
print('Fail')
print('Enocoding Empty Input Test: ', end=' ')
try:
huffman_encoding('')
except ValueError:
print('pass')
else:
print('Fail')
print('Decoding Null Input Test: ', end=' ')
try:
huffman_decoding(None, None)
except TypeError:
print('pass')
else:
print('Fail')
print('\nFull Functionality Test: Single character strings: ')
a_great_sentence = "aaa"
print ("The size of the data is: {}\n".format(sys.getsizeof(a_great_sentence)))
print ("The content of the data is: {}\n".format(a_great_sentence))
encoded_data, tree = huffman_encoding(a_great_sentence)
print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2))))
print ("The content of the encoded data is: {}\n".format(encoded_data))
decoded_data = huffman_decoding(encoded_data, tree)
print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data)))
print ("The content of the encoded data is: {}\n".format(decoded_data))
print('Result: ', end=' ')
if a_great_sentence == decoded_data:
print('pass')
else:
print('Fail')
print('\nFull Functionality Test: w/ Test Sentence: ')
a_great_sentence = "The bird is the word"
print ("The size of the data is: {}\n".format(sys.getsizeof(a_great_sentence)))
print ("The content of the data is: {}\n".format(a_great_sentence))
encoded_data, tree = huffman_encoding(a_great_sentence)
print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2))))
print ("The content of the encoded data is: {}\n".format(encoded_data))
decoded_data = huffman_decoding(encoded_data, tree)
print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data)))
print ("The content of the encoded data is: {}\n".format(decoded_data))
print('Result: ', end=' ')
if a_great_sentence == decoded_data:
print('pass')
else:
print('Fail')
if __name__ == "__main__":
codes = {}
test_suite()
|
06a68e0677fa8a7489a032be611ce5dd0b86e3b7 | shruticode81/GeekforGeek_quiestions | /hackerrank/shape.py | 313 | 3.796875 | 4 | t = int(input())
for _ in range(t):
shape = input().lower()
a = int(input())
b = int(input())
if shape == "rectangle" and a == b:
print(a*b)
elif shape == "square":
print(int((a*b)/2))
elif shape == "triangle" :
print(a*b)
else:
print("0")
|
36eabb29fc258c68e6f0ae60d50df17fd141adb8 | chasegarsee/code-challenges | /Algorithms/BinarySearch.py | 448 | 3.890625 | 4 |
# Eliminate half the numbers every time with binary search.
def binary_search(list, item):
low = 0
high = len(list) - 1
while low <= high:
mid = low + high
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
my_list = list(range(10, 21))
print(my_list)
print(binary_search(my_list, 20))
|
0b6a66b3d565c4d8523e1f2e8e1e8fa2a12adc8e | IvanDimitrov2002/school | /tp/oct_25.py | 1,009 | 3.5625 | 4 | from time import sleep
class Iterable:
def __init__(self, max):
self.max = max
self.numbers = []
def __iter__(self):
if(len(self.numbers) == self.max):
return iter(self.numbers)
self.number = 0
return self
def __next__(self):
if(self.number < self.max):
sleep(0.5)
self.number += 1
self.numbers.append(self.number)
return self.number
raise StopIteration
def generator(self):
D = {}
q = 2
while True:
if q not in D:
yield q
D[q * q] = [q]
else:
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
if __name__ == "__main__":
it = Iterable(5)
# for i in it:
# print(i)
# print("")
# for i in it:
# print(i)
for i in it.generator():
sleep(0.05)
print(i)
|
319a46ca2dfea84d5572e32af20063402713992a | nidhijain1/Testingworld | /prime Number.py | 217 | 4.03125 | 4 | num=int(input())
if num>1:
for i in range(2,num):
if (num%i)==0:
print("number is not prime"+ str(num))
break
else:
print("number prime"+str(num))
#prime number |
3775f7f5e332ff2a68a8db42a1cd37e96b43a650 | Roy-Wells/Python-Code | /算法第四版(python)/第一章 基础/04Stack.py | 446 | 3.984375 | 4 | """
P79.栈
class queue.LifoQueue(maxsize=0)
LIFO即Last in First Out,后进先出。与栈的类似,使用也很简单,maxsize用法同03Queue。
***其实在python中不区分队列以及栈,
只有"queue.Queue"(FIFO先进先出队列)以及"queue.LifoQueue"(LIFO后进先出队列)两种不同的队列方法。
"""
import queue
q = queue.LifoQueue()
for i in range(5):
q.put(i)
while not q.empty():
print(q.get()) |
d7c8fa183d6fdd48047ed136934baa7c3303f85a | ZihengZZH/LeetCode | /py/PalindromePartitioning.py | 822 | 4.09375 | 4 | '''
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
[
["aa","b"],
["a","a","b"]
]
'''
# Divide the string to check whether two parts are palindrome
# Further check if each part contains two palindromes
# Note the default output
class Solution:
def partition(self, s):
result = []
for i in range(1, len(s)+1):
if s[:i] == s[i-1::-1]:
for rest in self.partition(s[i:]):
result.append([s[:i]]+rest)
if not result:
return [[]]
return result
if __name__ == "__main__":
s1 = "aabb"
s2 = "aasssd"
solu = Solution()
print(s1, solu.partition(s1))
print(s2, solu.partition(s2)) |
87dcbac8aca5550f816ef581dc33bdbfcf4f68ce | AceRodrigo/CodingDojoStuffs | /Python_Stack/_python/python_fundamentals/Rodriguez_Austin_VS_Loop_Basic_2.py | 2,545 | 3.734375 | 4 | # #Challenge 1 Biggie Size
# def biggie(arr):
# newArr = []
# for i in range(len(arr)):
# if arr[i] >= 0:
# newArr.append("big")
# else:
# newArr.append(arr[i])
# return newArr
# print(biggie([-1, 2, 5, -5]))
# #Challenge 2 Count Positives
# def myFunc(a):
# count=0
# for i in range(0,len(a)):
# if a[i]>=1:
# count=count+1
# a[len(a) -1] + count
# return a
# print(myFunc([1,6,-4,-2,-7,-2]))
# #Challenge 3 Sum total
# def myFunc(a):
# sum=0
# for i in range(0, len(a)):
# sum=sum+a[i]
# return sum
# print(myFunc([1,2,3,4]))\
# #Challenge 4 average
# def average(a):
# avg=0
# sum=0
# for i in range(0,len(a)):
# sum=sum+a[i]
# avg=sum/len(a)
# return avg
# print(average([1,2,3,4]))
# #Challenge 5
# def length(list):
# newArr=[]
# for i in range(0,len(list)):
# newArr=len(list)
# return newArr
# print(length([5,2,3,5]))
# #Challenge 6 Minimum
# def minimum(a):
# min=0
# for i in range(0,len(a)):
# if a[i]<min:
# return(a[i])
# print(minimum([27,2,1,-9]))
# #Challenge 7 Maximum
# def maximum(a):
# max=0
# for i in range(0, len(a)):
# if a[i]>max:
# return len(a)
# if a[i]!=max:
# return False
# print(maximum([1,2,3,4,5]))
# #Have to change the max in order to falsify this function
# #Challenge 8 Ulitmate Analysis
# my_dict[
# {'sumTotal': 0, 'average': 0, 'minimum': 0, 'maximum':0, 'length':0}
# ]
# def ultimate_analysis(list):
# sumTotal=0
# min=list[0]
# max=list[0]
# for i in range(len(list)):
# sumTotal+=list[i]
# ave=sumTotal/len(list)
# if list[i]>max:
# max=list[i]
# if list[i]<min:
# min=list[i]
# my_dict={
# 'sumTotal': sumTotal,
# 'average': ave,
# 'minimum': min,
# 'maximum': max,
# 'length': len(list)
# }
# return my_dict
# print(ultimate_analysis([27,2,1,-9]))
# 9 Reverse List
# def reverse(lst):
# temp = 0
# for i in range(len(lst)/2):
# temp = lst[i]
# lst[i] = lst[len(lst) - 1 - i]
# lst[len(lst)-1-i] = temp
# return lst
# print(reverse([1, 2, 3, 4]))
def reverse(list):
temp = 0
for i in range(int(len(list)/2)):
temp = list[i]
list[i] = list[len(list) - 1 - i]
list[len(list)-1-i] = temp
return list
print(reverse([1, 2, 3, 4]))
|
027d1c883526bfbc0012997510da979e635ff811 | ivadimn/py-input | /skillbox/basic/module26/module26-3.py | 1,830 | 3.765625 | 4 | import random
"""
class CountIterator:
__count = 0
def __iter__(self):
CountIterator.__count = 0
return self
def __next__(self):
result = CountIterator.__count
CountIterator.__count += 1
return result
my_iter = CountIterator()
for i_elem in my_iter:
print(i_elem)
if i_elem > 1001:
break
class Randomizer:
def __init__(self, limit):
self.__limit = limit
self.__count = 0
self.__prev_value = 0
def __next__(self):
self.__count += 1
if self.__count == 1:
self.__prev_value = random.random()
return self.__prev_value
if self.__count <= self.__limit:
self.__prev_value += random.random()
return self.__prev_value
else:
raise StopIteration
def __iter__(self):
self.__count = 0
self.__prev_value = 0
return self
r5 = Randomizer(6)
for elem in r5:
print(elem)
"""
class Primes:
def __init__(self, number):
if number < 2:
raise ValueError("Параметер не может быть меньше 2")
self.__max_number = number
self.__prev_value = 2
def __next__(self):
for i in range(self.__prev_value, self.__max_number + 1):
is_prime = True
for j in range(2, i):
if i % j == 0:
is_prime = False
break
if is_prime:
self.__prev_value = i + 1
return i
self.__prev_value = i
if self.__prev_value == self.__max_number:
raise StopIteration
def __iter__(self):
self.__prev_value = 2
return self
prime_nums = Primes(50)
for i_elem in prime_nums:
print(i_elem, end=' ')
|
692a526cc2dded414d36932bb6dd43bbf078a222 | Galileo0/security_system_based_on_etherum | /Auth-out/RTQR.py | 2,700 | 3.6875 | 4 | import zbar
from PIL import Image
import cv2
from pyzbar.pyzbar import decode
#import Gate_BC
def main_j():
"""
A simple function that captures webcam video utilizing OpenCV. The video is then broken down into frames which
are constantly displayed. The frame is then converted to grayscale for better contrast. Afterwards, the image
is transformed into a numpy array using PIL. This is needed to create zbar image. This zbar image is then scanned
utilizing zbar's image scanner and will then print the decodeed message of any QR or bar code. To quit the program,
press "q".
:return:
"""
# Begin capturing video. You can modify what video source to use with VideoCapture's argument. It's currently set
# to be your webcam.
capture = cv2.VideoCapture(0)
while True:
# To quit this program press q.
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Breaks down the video into frames
ret, frame = capture.read()
# Displays the current frame
cv2.imshow('Current', frame)
# Converts image to grayscale.
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Uses PIL to convert the grayscale image into a ndary array that ZBar can understand.
image = Image.fromarray(gray)
width, height = image.size
zbar_image = zbar.Image(width, height, 'Y800', image.tobytes())
# Scans the zbar image.
scanner = zbar.ImageScanner()
scanner.scan(zbar_image)
test_decode = decode(image)
# Prints data from image.
for decoded in zbar_image:
tx_hash = decoded.data
print(tx_hash)
print(test_decode[0].data)
break
'''if Gate_BC.validate(tx_hash):
print('O')
#open Gate
else:
print('e')
# rasise Error
print(decoded.data)'''
def capture_qr():
cap = cv2.VideoCapture(1)
token_before = 'Null2'
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
ret, frame = cap.read()
cv2.rectangle(frame, (100, 100), (200, 200), [255, 0, 0], 2)
cv2.imshow('Current',frame)
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
image = Image.fromarray(gray)
#image.tobytes()
qr_decode = decode(image)
token = 'NULL'
if qr_decode:
#time.sleep(3)
token = qr_decode[0].data
token = token.decode('utf-8')
if token != token_before :
token_before = token
print(token)
auth(token)
capture_qr() |
b71fb0836babcf687d42dd234a11e8d68b7944c8 | KimTaesong/Algorithm | /CodingTest_Study1/week20/가운데글자가져오기.py | 172 | 3.53125 | 4 | def solution(s):
n = len(s)
if n % 2 == 0:
return s[n//2-1:n//2+1]
return s[n//2]
s = ["abcde", "qwer"]
for i in range(2):
print(solution(s[i]))
|
2e0875fc7774a1e62af7d6ddfac85e3e9a4f3cec | tsuetsugu/vimrc | /develop/learn_python/rename_files.py | 493 | 3.71875 | 4 | import os
def rename_files():
# (1) get file names from folder
file_list = os.listdir("/Users/toshi/develop/learn_python/prank")
print(file_list)
saved_path = os.getcwd()
print("Current Woking Directry is "+saved_path)
os.chdir("/Users/toshi/develop/learn_python/prank")
# (2) for each file, rename filename
for file_name in file_list:
os.rename(file_name, file_name.translate(str.maketrans("0123456789", "")))
os.chdir(saved_path)
rename_files()
|
507a7ac5f9f7931d7440cb02898b59587bdd3f72 | MaChimal/AdventOfCode2020 | /day3/day3_1.py | 345 | 3.59375 | 4 | ### Day 3: Toboggan Trajectory ###
## Part 1
answer = 0
map_ = []
for _x in open("day3.txt"):
_x = _x.strip()
map_.append(_x)
row = 0
col = 0
m = len(map_)
while row+1 < m:
row += 1
col += 3
position = map_[row][col % len(map_[row])]
if position == "#":
answer += 1
print(answer) |
cf8b2753725788fa9ad8975e8d5cea2d67fa7f7c | h-sdl/projet-npm3d | /src/RANSAC.py | 3,558 | 3.703125 | 4 | # -*- coding: utf-8 -*-
import numpy as np
from utils.ply import write_ply, read_ply
import time
def compute_plane(points):
"""
Computing a plane passing through 3 input points
Parameters
----------
points : 3x3 numpy array (3 points stacked in a row-wise way)
Returns
-------
point : a point in the found plane
normal : a unit normal vector of the found plane
"""
normal = np.cross(points[1] - points[0], points[2] - points[0])
normal = normal / np.sqrt(np.sum(normal**2))
point = points[0]
return point, normal
def in_plane(points, normals, ref_pt, ref_normal, threshold_in=0.1, threshold_normals=0.8):
"""
Checks whether the given points belong to a given plane (with some threshold value)
Parameters
----------
points : Nx3 numpy array
normals : estimation of local normals at each point
ref_pt : 3-numpy array (a point of the plane)
ref_normal : 3-numpy array (unit vector of the plane)
threshold_in : float: maximum distance to the plane for points to belong to it
threshold_normals : float : if normals is provided, the angle between the normals of the plane
should not be greater than this threshold
Returns
-------
indices : N-numpy array of booleans telling which points belong to the plane
"""
dists = np.einsum("i,ji->j", ref_normal, points - ref_pt)
indices = abs(dists) < threshold_in
if normals is not None:
normal_check = abs(np.dot(ref_normal, normals.T)) > threshold_normals
return indices & normal_check
return indices
def RANSAC(points, normals=None, NB_RANDOM_DRAWS=100, threshold_in=0.1, threshold_normals=0.8):
"""
Applies the RANSAC algorithm to find an horizontal plane
Parameters
----------
points : Nx3 numpy array
normals: Nx3 numpy array, optional (estimation of local normals at each point)
NB_RANDOM_DRAWS : number of tries: the biggest plane of all draws will be taken
threshold_in : float : distance threshold telling whether a point belongs to a plane or not
threshold_normals : float : if normals is provided, the angle between the normals of the plane
should not be greater than this threshold, moreover the projection of the
normal of the plane on z axis should be greater than this threshold
Returns
-------
best_ref_pt : 3-numpy array (point belonging to the best found plane)
best_normal : 3-numpy array (unit normal vector of the best found plane)
"""
best_ref_pt = np.zeros((3,1))
best_normal = np.zeros((3,1))
best_nb = -1
for i in range(NB_RANDOM_DRAWS):
# Drawing 3 different point indices at random
rand_indices = np.zeros(3).astype(int)
while len(np.unique(rand_indices)) != 3:
rand_indices = np.random.randint(0, np.shape(points)[0], size=3)
# Extracting the corresponding points
pts = points[rand_indices]
# Finding the associated plane
ref_pt, ref_normal = compute_plane(pts)
# Couting the number of points in this plane
nb = np.sum(in_plane(points, normals, ref_pt, ref_normal, threshold_in))
# Updating the best plane if needed
if nb > best_nb and abs(ref_normal[2]) > threshold_normals:
best_nb = nb
best_ref_pt = ref_pt
best_normal = ref_normal
return best_ref_pt, best_normal |
b781f95699002cdfc89722537cf237b7a5fd2faa | therealiggs/oldpystuff | /test.py | 1,301 | 3.515625 | 4 | with open('smartguy.txt') as file:
text = [line for line in file]
def code(word,key):
ans = []
klst = list(key)
i = 0
for line in word:
k = ord(klst[i%len(klst)])
e=line.encode('cp1251')
s = bytes([(byte + k)%256 for byte in e])
ans+= s.decode('cp1251')
i += 1
return ''.join(i for i in ans)
def decode(word,key):
ans = []
klist = list(key)
i = 0
for line in word:
k = ord(klst[i%len(klst)])
e=line.encode('cp1251')
s = bytes([(byte - k)%256 for byte in e])
ans+= s.decode('cp1251')
i += 1
return ''.join(i for i in ans)
print('Ключ?')
gkey = input()
with open('smartguy.txt','w') as file:
flag = False
while not flag:
print('Что делать?')
command = input()
if 'зашифровать'.startswith(command.lower()):
for char in code(text,gkey):
print(char,file=file,end='')
flag = True
elif 'расшифровать'.startswith(command.lower()):
for char in decode(text,gkey):
print(char,file=file,end='')
flag = True
else:
print('Нет такой команды!')
|
c69c71417cd1719b40e855f0c1e918d24c2190c3 | Juahn1/Ejercicios-curso-de-python | /ejercicio_3_radio_y_longitud.py | 342 | 3.671875 | 4 | import math
try:
r= float(input("Ingrese el radio: "))
def area_y_longitud(r):
area = math.pi*(r**2)
longitud = 2*math.pi*r
print(f"El area es {area:.4f} y la longitud es {longitud:.4f}")
print("")
area_y_longitud(r)
print("")
except:
ValueError
print("Ingrese un numero valido")
|
50255d80b0dcbc597be403f026aca7d04a348043 | gabrielpereirapinheiro/client-server-python | /Server.py | 4,486 | 3.703125 | 4 | from socket import *
#SERVER
#Victor Araujo Vieira
#Gabriel Pereira Pinheiro
#Funcao que mostra na tela o que foi recebido
def show_index(message,aux):
print 'Foi recebido a mensagem-> ',message[len(message)-3]
print 'index -> ',aux[0]
if(len(aux)==3):
print 'flag -> ',aux[2]
if(aux[2]=='0'):
print '------Ultimo pacote recebido------'
if(len(aux)==2):
print 'flag -> ',aux[1]
if(aux[1]=='0'):
print '------Ultumo pacote recebido------'
print ''
#Funcao que ira criar a respostaar(ACK)
#que e a concatenacao do indice + ' ' + validade
def create_resposta(message,list_msg,flag):
#Lista vazia para usar split
new_list = []
#Inicialmente igual a 0
valid = '0'
#new_list com mensagem recebida do cliente
new_list = message.split()
#tamanho da listas com as mensagens ja recebidas
size = len(list_msg)
#Indice recevido
valor = new_list[0]
#Inteiro recebido
valor = int(valor)
#Caracter recebido
retorno = new_list[0]
#Se a lista nao e nula
if(size>0):
aux = int(list_msg[size-1])
if(valor-1 != aux):
valid = '-1'
retorno=aux +1
retorno = str(retorno)
if(flag==0):
print '----- Mensagem do index',valor,'descartada-----'
print ''
ack = retorno+' '+valid
return ack
#This fuction is going to look if the index exists in list
def check_index_recive(message,list):
status = 0
valor = -1
list_aux =[]
list_aux = message.split()
if(len(list)!= 0):
for i in range(0,len(list)):
index=int(list[i])
valor = list_aux[0]
if(valor==index):
status = -1
return status
#This fuction is used to see the valid of index's list
def check_list_index(list,size):
#if dont have problems with the list, status=0
status = 0
# 0 means ok and -1 means erro
return status
def junta_messagem(lista_de_messagens):
string = ' '
for i in range (0,len(lista_de_messagens)):
string = string + str(lista_de_messagens[i])
return string
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))
print '-----O servidor esta pronto para receber -----\n'
list_of_message = []
list_of_index = []
#Create a new list to save the acks that were sent
list_of_ack = []
aux_list = []
while 1:
#Recive the message from cliente
message, clientAddress = serverSocket.recvfrom(2048)
#Show on terminal the index
present_in_list = check_index_recive(message,list_of_index)
aux_list = message.split()
show_index(message,aux_list)
#print aux_list[0]
if(present_in_list==0):
#Create the answer to send to client
resposta = create_resposta(message,list_of_index,0)
status_resposta = resposta[len(resposta)-1]
#Se for um ack
if(status_resposta== '0'):
#Save the index
list_of_index.append(aux_list[0])
#Save the message
#-3 is to find the message in the vector based in the end.
list_of_message.append(message[len(message)-3])
#Save the ack before is send
list_of_ack.append(resposta)
#print 'valor --->'+ message[len(message)-1]
#last_index = message[0]
#If was the last package
if(message[len(message)-1] == '0'):
#Show the complete message
mensagem_completa=junta_messagem(list_of_message)
print '\nA mensagem recebida foi ->',mensagem_completa,' <-'
print '\n----- O servidor esta pronota para receber -----\n'
last = int(message[0])
#Check recive the value of status on fuction
check =check_list_index(list_of_index,last)
#If the value is -1, show error to user
if(check== -1):
print 'Erro, the message is not completed'
#clean_lists(list_of_index,list_of_message,list_of_ack)
#Clean al lists
list_of_message = []
list_of_ack=[]
list_of_index=[]
# Se for um NACK
else:
resposta = create_resposta(message,list_of_index,1)
if(message[len(message)-1] == '0'):
#Show the complete message
last = int(message[0])
#Check recive the value of status on fuction
check =check_list_index(list_of_index,last)
#If the value is -1, show error to user
if(check== -1):
print 'Erro, the message is not completed'
#clean_lists(list_of_index,list_of_message,list_of_ack)
list_of_message = []
list_of_ack=[]
list_of_index=[]
serverSocket.sendto(resposta, clientAddress)
|
47320b36008dcb00c789c0e08ff99db94e2956bb | tongbc/algorithm | /src/justForReal/maxSlidingWindow.py | 635 | 3.515625 | 4 | from collections import deque
class Solution:
def maxSlidingWindow(self, nums, k):
res = []
bigger = deque()
for i, n in enumerate(nums):
# make sure the rightmost one is the smallest
while bigger and nums[bigger[-1]] <= n:
bigger.pop()
# add in
bigger += [i]
# make sure the leftmost one is in-bound
if i - bigger[0] >= k:
bigger.popleft()
# if i + 1 < k, then we are initializing the bigger array
if i + 1 >= k:
res.append(nums[bigger[0]])
return res |
b0c3843186deeea22f9bd41cdccce569b5b0396e | Moejay10/IN4110 | /Assignment5/exercise_5_3/collect_dates.py | 5,638 | 3.84375 | 4 | #!/usr/bin/env python
# importing modules
import argparse
import numpy as np
import requests as req
import os
import sys
import re
import pandas as pd
import datetime
sys.path.append('../')
from exercise_5_1.requesting_urls import get_html
def main():
"""Tests the implementation of the functions find_dates
"""
parser = argparse.ArgumentParser(
description='Tests the implementation of the function find_dates.',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-u", "--url", type=str, help="The URL of a given website.", required=True)
parser.add_argument("-o", "--output", type=str, help="The optional output filename.", default=None)
args = parser.parse_args()
new_url, data = get_html(args.url) # Read html text file
# Finds all dates from the given website
dates = find_dates(data)
find_dates(data, args.output)
def find_dates(data, output=None):
"""Finds the dates in a body of html using regex.
Args:
data (str): A string of html.
Returns:
dates (list): A list of all dates found in the html.
"""
total_dates = []
# Finds all dates on the form YYYY-MM-DD
iso = re.findall(r'([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))',data)
for i in range(len(iso)):
iso[i] = iso[i][0]
iso[i] = ''.join(iso[i]) # Converting into a string
# Converting into format yyyy/mm/dd
iso[i] = re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\\1/\\2/\\3', iso[i])
total_dates.append(iso[i])
month_numbers = {r'Jan(uary)?': '01', r'Feb(ruary)?': '02',
r'Mar(ch)?': '03',
r'Apr(il)?': '04', r'May': '05',
r'Jun(e)?': '06', r'Jul(y)?': '07', r'Aug(ust)?': '08',
r'Sep(tember)?': '09',
r'Oct(ober)?': '10',
r'Nov(ember)?': '11', r'Dec(ember)?': '12'}
# Finds all the dates on the form "Month day, Year" and "Month, Year"
mdy = re.findall(r'((?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(Nov|Dec)(?:ember){2,8}?))(\s\d{2})?,(\s[12][0-9]{3})', data)
for m in range(len(mdy)):
mdy[m] = ''.join(mdy[m])
# Converting into format yyyy/mm/dd
mdy[m] = re.sub(r'([\w]+)\s(\d{1,2})\s?(\d{4})', '\\3/\\1/\\2', mdy[m])
# Substitutes month name with corresponding month number
for k, v in month_numbers.items():
mdy[m] = re.sub(k, v, mdy[m])
total_dates.append(mdy[m])
# Finds all the dates on the form "Day Month Year" and "Month Year"
dmy = re.findall(r'(\d{2}\s)?((?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(Nov|Dec)(?:ember){2,8}?))(\s[12][0-9]{3})', data)
for d in range(len(dmy)):
dmy[d] = ''.join(dmy[d]) # Converting into a string
# Converting into format yyyy/mm/dd
dmy[d] = re.sub(r'(\d{1,2})?\s?([\w]+)\s(\d{4})', '\\3/\\2/\\1', dmy[d])
# Substitutes month name with corresponding month number
for k, v in month_numbers.items():
dmy[d] = re.sub(k, v, dmy[d])
total_dates.append(dmy[d])
# Finds all the dates on the form "Year Month Day"
ymd = re.findall(r'([12][0-9]{3}\s)((?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(Nov|Dec)(?:ember){2,8}?)\s)(\d{2})?', data)
for y in range(len(ymd)):
ymd[y] = ''.join(ymd[y]) # Converting into a string
# Converting into format yyyy/mm/dd
ymd[y] = re.sub(r'(\d{4})\s([\w]+)\s(\d{1,2})', '\\1/\\2/\\3', ymd[y])
# Substitutes month name with corresponding month number
for k, v in month_numbers.items():
ymd[y] = re.sub(k, v, ymd[y])
total_dates.append(ymd[y])
# Sort the list in ascending order of dates
total_dates = sorted(total_dates)
if output == None:
return total_dates
else:
writeToFile(output, total_dates)
def writeToFile(filename, data):
"""Writes a file containing the urls found in a given website.
Args:
filename (str): The filename of the output text file.
data1 (str): Data containing all the urls found in a given website.
data2 (str): Data containing all the wikipedia articles found in the given website.
"""
# Converts the lists into a string, where each list element starts on a new line
data = '\n'.join(data)
e = datetime.datetime.now() # Finds the time
newdir = os.getcwd() + "/filter_dates_regex/"
if not os.path.isdir(newdir):
os.makedirs(newdir)
filename = newdir + filename
else:
filename = os.getcwd() + "/filter_dates_regex/" + filename
if os.path.isfile(filename): # Checking if file exists
os.remove(filename) # Removes the file
f = open(filename, "a")
f.write(f"Last run date was %s/%s/%s at %s:%s:%s \n" % (e.day, e.month, e.year, e.hour, e.minute, e.second ))
f.write("\n")
f.write("\n")
f.write("#--------------------------------------------------------------------------#")
f.write("\n")
f.write("\n")
f.write('All dates in the url\n')
f.write("--------------\n")
f.write(data)
f.write("\n")
f.write("\n")
f.write("#--------------------------------------------------------------------------#")
f.close()
if __name__ == '__main__':
main()
|
011437353074417d751107a03bd7aa973bb25b8b | cubeguerrero/euler-problems | /010/solution.py | 435 | 3.703125 | 4 | import math
def is_prime(n):
for i in range(2, round(math.sqrt(n))):
if n%i == 0:
return False
return True
def solution(n):
total = 0;
for i in range(2, n):
if is_prime(i):
total += i;
return total
if __name__ == "__main__":
import time
start_time = time.time()
print(solution(2000000))
print("Solution took {} seconds".format(time.time() - start_time)) |
1ab73524eae5070af7f7500adc46c88359de4616 | anatdaplanoi/PML-Project-PSIT | /sexrate.py | 1,101 | 3.53125 | 4 | """This program is shows graph about percentage teenage pregnancy of the second period."""
import pylab
def main():
"""The graph shows the sex rate"""
read = open("/Users/porpiraya/Desktop/data_sexrate.txt", "r")
da_lis = []
da_year = []
da_per_a = []
da_per_b = []
count = 0
for i in read:
if count != 0:
da_lis.append(i.split())
count = 1
for i in range(len(da_lis)):
da_year.append(int(da_lis[i][0]))
da_per_a.append(float(da_lis[i][1]))
da_per_b.append(float(da_lis[i][2]))
pylab.plot(da_year, da_per_a,'-bo', linewidth=2)
pylab.plot(da_year, da_per_b,'-ro', linewidth=2)
labelProperty = dict(fontweight='bold', fontsize='12')
pylab.xlabel('Years', labelProperty)
pylab.ylabel('Percentage', labelProperty)
legends = ('Sex rate of second years senior high school',\
'Sex rate of second years vocational', )
pylab.legend(legends, loc='upper left', shadow=True, fancybox=True)
pylab.xlim(2546,2556)
pylab.xticks(da_year)
pylab.grid(True)
pylab.show()
main()
|
598954f677b595b0c90dcd04aef3cc947a60082a | spardok/IFT383 | /IFT383-06py/HO6-1.py | 687 | 3.828125 | 4 | #!/usr/bin/python
varIn1 = raw_input("Please enter the first exam score in the form score/max: ")
varIn1 = eval(varIn1 + str(0.0))
varIn2 = raw_input("Please enter the second exam score in the form score/max: ")
varIn2 = eval(varIn2 + str(0.0))
varIn3 = raw_input("Please enter the third exam score in the form score/max: ")
varIn3 = eval(varIn3 + str(0.0))
if type(varIn1) is float:
totalAverage = (((varIn1 + varIn2 + varIn3) / 3) * 1000)
if totalAverage > 95:
print("Your Average was %0.2f%%") \
% (totalAverage)
print("Great work! Your average was over 95%!!!!")
else:
print("Your Average was %0.2f%%") \
% (totalAverage)
|
e9fd87575633712fede583bb4636ea2b87124775 | kaia-c/RoverClass | /pressureSensor.py | 1,044 | 4.0625 | 4 | import turtle
from Arduino import Arduino
pin=14 #A0
startPressure=295 #the reading we get with no pressure
startSize=10 #which we will equate with drawing a radius of 10px
modifyFactor=10 #modified by a factor of 10
board=Arduino('9600', 'COM6')
board.pinMode(pin, 'INPUT')
#set up turtle pen
turtle.pen(fillcolor="purple", pencolor="black", pensize=10)
turtle.speed(0) #don't delay drawing when called
turtle.penup() #don't draw while we set up
turtle.right(90) #degrees
turtle.forward(modifyFactor*startSize)
turtle.left(90)
turtle.pendown() #start drawing
try:
while True:
pressure=board.analogRead(pin)
adjustedPressure=pressure-(startPressure-startSize)
print("pressure="+str(pressure)+
" - adjustedPressure="+str(adjustedPressure))
turtle.clear()
turtle.begin_fill()
turtle.circle(modifyFactor*adjustedPressure)
turtle.end_fill()
except (KeyboardInterrupt, SystemExit):
print('exiting')
turtle.bye()
exit()
|
10f45dd13a77c3b5888a28af64cf6d6b4de7c13e | archiver/spoj | /histogra.py | 759 | 3.59375 | 4 | from collections import namedtuple
import sys
Info=namedtuple('Info',('start','height'))
def maxarea(hist):
stack=list()
top=lambda : stack[-1]
area=0
for pos,height in enumerate(hist):
start=pos
while True:
if not stack or height>top().height:
stack.append(Info(start,height))
elif stack and height<top().height:
start,h=stack.pop()
area=max(area,h*(pos-start))
continue
break
print area
pos+=1
for start,height in stack:
area=max(area,height*(pos-start))
print area
return area
if __name__=='__main__':
s=sys.stdin
for line in s:
hist=map(lambda x: int(x), line.strip().split())
if hist[0]==0: break
print maxarea(hist[1:])
|
22974e861fc3fef6eafa7e0d78ca01a523729247 | Snoblomma/HackerRank | /Python/Math/Find Angle MBC/FindAngleMBC.py | 240 | 3.578125 | 4 | import math
AB = int(input())
BC = int(input())
AC = math.sqrt(AB**2 + BC**2)
MC = AC/2
BM = MC
s = (BM**2+BC**2-MC**2)/(2*BM*BC)
phi = math.degrees(math.acos(s))
degree_sign= u'\N{DEGREE SIGN}'
print (str(str(round(phi))) + degree_sign)
|
1aa6f9f8e8575ead340cda9cc1eb42e7d0735458 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_2/ronitrex/Beatrix.py | 708 | 3.609375 | 4 | def flip(N):
global i
if '-' not in N:
return
if '+' not in N:
i+=1
return
if N[0]== '-':
x = N.index('+')
NewN = N[:x]
OldN = N[x+1:]
NewN = NewN.replace('-','+')
N = NewN+OldN
# print(NewN, OldN, N, 'Craft')
# print(N)
i += 1
flip(N)
elif N[0]== '+':
x = N.index('-')
NewN = N[:x]
OldN = N[x+1:]
NewN = NewN.replace('+','-')
N = NewN + OldN
# print(NewN, OldN, N, 'Fair')
# print(N)
i+=1
flip(N)
T = int(input())
for _ in range(1, T+1):
N = input()
i=0
flip(N)
print('Case #{}: {}'.format(_, i))
|
4e3d0feafa9b5d36a2c089c64ad0e8a213c0edc5 | xiaoxiae/MO-P-68 | /Teoretické/Úloha 3/uloha3.py | 1,330 | 3.84375 | 4 | from functools import cmp_to_key
def translatePoints(points, x, y):
"""Translates the coordinates of points."""
for point in points:
point[0] += x
point[1] += y
def comparator(p1, p2):
"""The comparator used for the sorting"""
value = p1[0] * p2[1] - p2[0] * p1[1]
if value < 0:
return -1
elif value > 0:
return 1
else:
return 0
# The set of points to check
points = [[-2, 5], [1, 2], [2, 1], [2, -2], [0, 0]]
# Smallest triangle area
smallestArea = float("+inf")
# For every point
for i in range(len(points)):
point = points[i]
x, y = point[0], point[1]
# Translate all points so that our point is origin
translatePoints(points, -x, -y)
comparisonArray = sorted(list(points), key=cmp_to_key(comparator))
del(comparisonArray[i]) # Delete the [0, 0] point
# Check all of the neighbouring points
for j in range(0, len(comparisonArray) - 1):
p1 = comparisonArray[j]
p2 = comparisonArray[j + 1]
# Compute the area and check wheter it isn't smallest
area = 1/2 * abs(p1[0] * p2[1] - p1[1] * p2[0])
if area != 0 and area < smallestArea:
smallestArea = area
# Translate back
translatePoints(points, x, y)
print("The minimum triangle are is "+str(smallestArea)+".")
|
7db4b4cc814c8be54c1e9b786e66f3241ead5b56 | zhaoyufei007/Coursera-Python-for-everybody | /Assignment 7.2.py | 958 | 4.25 | 4 | Write a program that prompts for a file name,
then opens that file and reads through the file,
looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values
and produce an output as shown below.
Do not use the sum() function or a variable named sum in your solution.
You can download the sample data at
http://www.py4e.com/code3/mbox-short.txt
when you are testing below enter mbox-short.txt as the file name.
# Use words.txt as the file name
fname = input("Enter file name: ")
try:
fh = open(fname)
except:
print('Wrong file name')
quit()
count = 0
tol = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"):
continue
else:
number = line[int(line.find(":"))+1:]
tol = tol + float(number)
count = count + 1
average = tol/count
print("Average spam confidence:", average)
|
ff204244ecf4286177f8fb385107e5d9b492cad8 | snowdj/cs_course | /Algorithms/challenges/lc054_spiral_matrix.py | 587 | 4.21875 | 4 | """
Time: O(m*n)
Space: O(min(m,n) * m*n) extra space for recursion, or O(m*n) iteratively.
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
"""
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
return matrix and list(matrix.pop(0)) + self.spiralOrder(zip(*matrix)[::-1]) # list(zip) in Python3
|
42aca9aa6fd8ed60bcb594295c98ef9d48376da0 | JeffreyAsuncion/CodingProblems_Python | /Lambda/alphabeticShift.py | 986 | 4.3125 | 4 | """
Given a string, your task is to replace
each of its characters by the next one in the English alphabet;
i.e. replace a with b, replace b with c, etc (z would be replaced by a).
Example
For inputString = "crazy", the output should be
alphabeticShift(inputString) = "dsbaz".
Input/Output
[execution time limit] 4 seconds (py3)
[input] string inputString
A non-empty string consisting of lowercase English characters.
Guaranteed constraints:
1 ≤ inputString.length ≤ 1000.
[output] string
The resulting string after replacing each of its characters.
"""
def alphabeticShift(inputString):
abc= "abcdefghijklmnopqrstuvwxyz"
new_str = ""
for letter in inputString:
i = abc.index(letter)
# increment to next letter
x = i + 1
# abc 0 - 25
if x == 26:
x = 0
new_letter = abc[x]
new_str += new_letter
return new_str
inputString = "crazy"
print(alphabeticShift(inputString)) # = "dsbaz". |
a87a2d44698a187c6150f47ae02006bb29702271 | audreyemmely/Python-programming | /testExercise1.py | 215 | 4 | 4 | age = int(input("Digite a sua idade: "))
if age >= 18:
print("Parabéns, você já pode ser preso! :)")
elif age > 0 and age < 18:
print("Você ainda é menor de idade.")
else:
print("Idade inválida.") |
4ca71ae53fe20410ab36d4e86e9dec1461f8a619 | haohsun/TQC-Python | /PYD210.py | 267 | 4 | 4 | side1 = eval(input())
side2 = eval(input())
side3 = eval(input())
perimeter = side1 + side2 + side3
#TODO
if side1 + side2 > side3 and side3 + side2 > side1 and side1 + side3 > side2:
print(perimeter)
else:
print("Invalid")
"""
Invalid
""" |
5045d97166a5b439a9f49eb42d008d0b44c0e1bd | VivekaMurali/Python | /py lab exam/p1.py | 222 | 4.34375 | 4 | #1.Write a recursive function to find factorial of a number.
def fact(n):
if n==1:
return 1
else:
return n*fact(n-1)
n=int(input("Enter a number:"))
print('Factorial of',n,'is',fact(n))
|
49c029af3c4396ebc2498257c562b9b7d41e9fe4 | EachenKuang/LeetCode | /code/110#Balanced Binary Tree.py | 1,331 | 3.75 | 4 | # https://leetcode.com/problems/balanced-binary-tree/description/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# 1 使用104中的maxDepth
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# 1 用递归
if root == None:
return True;
flag = abs(self.maxDepth(root.left) - self.maxDepth(root.right)) <= 1
return flag and self.isBalanced(root.left) and self.isBalanced(root.right)
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return max(self.maxDepth(root.left),self.maxDepth(root.right))+1
# 2 一个函数递归
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# 1 用递归
def dfs(root):
if root is None:
return 0
left = dfs(root.left)
right = dfs(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return max(left, right) + 1
return dfs(root) != -1
|
41c0031cf363922f4a0684ff2243f47b7c319b48 | blakegolliher/boxes | /drawabox.py | 470 | 3.75 | 4 | #!/usr/bin/python
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("width", type=int, help="The width of the box.")
parser.add_argument("height", type=int, help="This will be the height of the box.")
args = parser.parse_args()
width = args.width
height = args.height
def box(width,height):
print "*" * width
for middle in range(height - 2):
print "|" + ' ' * (width - 2) + "|"
print "*" * width
box(width,height)
|
292327f8d7600e4d96df958ea7a8b7a237ef4fc4 | harshitpal660/harshitpal660 | /practise set-4.py | 1,335 | 3.90625 | 4 | '''Q1 WAP to store 7 fruits in a list entered by the
user'''
# f1=input("Enter Fruit number 1: ")
# f2=input("Enter Fruit number 2: ")
# f3=input("Enter Fruit number 3: ")
# f4=input("Enter Fruit number 4: ")
# f5=input("Enter Fruit number 5: ")
# f6=input("Enter Fruit number 6: ")
# f7=input("Enter Fruit number 7: ")
# myfruitlist =[f1,f2,f3,f4,f5,f6,f7]
# print(myfruitlist)
'''Q2 WAP to accept marks of 6 studentsand display them in a
sorted manner'''
# m1=int(input("Enter Marks for student number 1: "))
# m2=int(input("Enter Marks for student number 2: "))
# m3=int(input("Enter Marks for student number 3: "))
# m4=int(input("Enter Marks for student number 4: "))
# m5=int(input("Enter Marks for student number 5: "))
# m6=int(input("Enter Marks for student number 6: "))
# mylist =[m1,m2,m3,m4,m5,m6]
# mylist.sort()
# print(mylist)
'''Q3 check tha tuple cannot change in python'''
# a = (3,4,6,37,4)
# a[0] = 23 #throughs error cuz we cannot change
# tuple
'''Q4 WAP to sum a list with 4 numbers'''
# list=[4,5,1,6,9,7]
# print(list[0]+list[1]+list[2]+list[3]+list[4]+list[5])
# print(sum(list))
'''Q5 WAP to count the number of zeroes in following table'''
# a=(7,0,8,0,0,9)
# a=(7,0,8,0,0,9)
# c=a.count(0)
# print(c)
|
894aa72d87fbbd6829b96364bcb5a26ddbd38f58 | vulmoss/practice | /0610/2.py | 482 | 3.578125 | 4 | #!/usr/bin/env python
# coding=utf-8
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self,value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 = 100')
self._score = value
#m = Student
#m.score = 10
#print(m.score)
s = Student()
s.score = 200
print(s.score)
|
a54fad0fe57dfacfb125203156aac5064856b539 | RedL0tus/CSClassworks | /2017-11-PythonTasksII/semordnilap.py | 718 | 4.34375 | 4 | #!/usr/bin/env python3
#-*- encoding:utf-8 -*-
"""Computer Science P classword finding semordnilap words"""
def get_semordnilap(filename):
"""Find semordnilap words inside the given file"""
semordnilap_list = []
wordlist = []
file = open(filename)
for line in file:
wordlist.append(line.strip())
for line in wordlist:
if is_semordnilap(line, wordlist):
semordnilap_list.append(line.strip())
return semordnilap_list
def is_semordnilap(word, wordlist):
"""Determine whether the word is a semordnilap or not."""
word_reversed = word.strip()[::-1]
if word_reversed in wordlist:
return True
return False
print(get_semordnilap('words.txt'))
|
73426fb529d95a506d390ad388f4c30b2375cabf | yuthreestone/LanQiao-Learning | /第十届蓝桥杯大赛c++大学C组/年号子串.py | 90 | 3.609375 | 4 | num=2019
s=''
while num:
s+=chr(ord('a')+num%26-1).upper()
num//=26
print(s[::-1]) |
94bfeceb46937903fb45e9de651f5c7d82aeef13 | Taoge123/OptimizedLeetcode | /LeetcodeNew/python/LC_391.py | 2,911 | 3.984375 | 4 |
"""
Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region.
Each rectangle is represented as a bottom-left point and a top-right point. For example,
a unit square is represented as [1,1,2,2]. (coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)).
Example 1:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[3,2,4,4],
[1,3,2,4],
[2,3,3,4]
]
Return true. All 5 rectangles together form an exact cover of a rectangular region.
Example 2:
rectangles = [
[1,1,2,3],
[1,3,2,4],
[3,1,4,2],
[3,2,4,4]
]
Return false. Because there is a gap between the two rectangular regions.
Example 3:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[3,2,4,4]
]
Return false. Because there is a gap in the top center.
Example 4:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[2,2,4,4]
]
Return false. Because two of the rectangles overlap with each other.
"""
class Solution:
def isRectangleCover(self, rectangles) -> bool:
area = 0
corners = set()
for p0, p1, p2, p3 in rectangles:
fours = [(p0, p1), (p0, p3), (p2, p1), (p2, p3)]
for point in fours:
if point not in corners:
corners.add(point)
else:
corners.remove(point)
area += (p3 - p1) * (p2 - p0)
if len(corners) != 4:
return False
corners = sorted(corners, key=lambda x: (x[0], x[1]))
if (corners[3][0] - corners[1][0]) * (corners[3][1] - corners[2][1]) != area:
return False
return True
class Solution2:
def isRectangleCover(self, rectangles):
if len(rectangles) == 0 or len(rectangles[0]) == 0:
return False
x1 = float("inf")
y1 = float("inf")
x2 = float("-inf")
y2 = float("-inf")
corners = set()
area = 0
for p0, p1, p2, p3 in rectangles:
x1 = min(p0, x1)
y1 = min(p1, y1)
x2 = max(p2, x2)
y2 = max(p3, y2)
area += (p3 - p1) * (p2 - p0)
corners.remove((p0, p3)) if (p0, p3) in corners else corners.add((p0, p3))
corners.remove((p0, p1)) if (p0, p1) in corners else corners.add((p0, p1))
corners.remove((p2, p3)) if (p2, p3) in corners else corners.add((p2, p3))
corners.remove((p2, p1)) if (p2, p1) in corners else corners.add((p2, p1))
if (x1, y2) not in corners or (x2, y1) not in corners or (x1, y1) not in corners \
or (x2, y2) not in corners or len(corners) != 4:
return False
return area == (y2 - y1) * (x2 - x1)
rectangles = [[1,1,3,3],
[3,1,4,2],
[3,2,4,4],
[1,3,2,4],
[2,3,3,4]]
a = Solution()
print(a.isRectangleCover(rectangles))
|
0c910491b386a0c3966b77e24c2d1b8ffb50d296 | chicocheco/checkio | /elementary/digits_multiplication.py | 876 | 4.15625 | 4 | # done in 2 hours
# next time: to iterate over digits, convert to string. After variable 'last' gets a value it can be merged with
# the variable 'product' because I'm interested only in the product of the last two number in next iterations.
def checkio(number: int) -> int:
new_list = [num for num in str(number)]
last = None
product = int(new_list[0])
for num in new_list:
if not last:
last = int(num)
continue
elif num != '0':
product = last = last * int(num)
return product
# 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!")
|
865befb4b9b9df2dc2fdae262270f526cd550217 | LeslieWilson/python_playground | /Chapt10.py/elevenProblem.py | 2,079 | 4.125 | 4 |
"""
Leslie Wilson
April 12 2018
elevenProblem.py
"""
from random import *
class Card(object):
"""creates card object with a rank and suit"""
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def getrank(self):
"""deliniates the rank of a card depending on what number is randomly chosen """
if self.rank == 1:
return "ace"
elif self.rank == 11:
return "joker"
elif self.rank == 12:
return "queen"
elif self.rank == 13:
return "king"
else:
return " %d" % (self.rank)
def getSuit(self):
"""deliniates the suit of a card depending on what letter is randomly chosen """
if self.suit == "d":
return "diamonds"
elif self.suit == "c":
return "clubs"
elif self.suit == "h":
return "hearts"
elif self.suit == "s":
return "spades"
def BJValue(self):
"""describes bj value depending on what number is randomly chosen"""
if self.rank == 1:
return "bj value 1"
elif self.rank == 11:
return "bj value 10"
elif self.rank == 12:
return "bj value 10"
elif self.rank == 13:
return "bj value 10"
else:
return "your bj val is %d" % (self.rank)
def __str__(self):
return "%s of %s |" % (self.getrank() , self.getSuit())
card = Card(randrange(1,13), choice(["s","d","c","h"]))
def randomCard():
"""makes array of randomly selected cards and their values denoted above. also lets user choose how many cards to draw."""
array = []
input = raw_input("how many cards do you want to use: ")
for i in range(int(input)):
card = Card(randrange(1,13),
choice(["s","d","c","h"]))
array.append(card)
return array
def main():
x = randomCard()
for card in x:
print(card)
print(card.BJValue())
card.BJValue()
card.getrank()
card.getSuit()
main()
|
6efd439875102c004205f2200834c0315d8c2b56 | Akhileshbhagat1/All-prectice-of-python | /mergingTWOlistItemsINTOaSingleLIST.py | 501 | 4.0625 | 4 | # merging two list's values into a single list
# list1 = [1, 2, 3, 4]
# list2 = ['a', 'b', 'c', 'd']
# list1.extend(list2)
# print(list1)
# or
# list3 = [1, 2, 3, 4]
# list4 = ['q', 'e', 'w', 't']
#
# list5 = []
# for i in list3:
# list5.append(i)
# for j in list4:
# list5.append(j)
# print(list5)
# or
# list1 = [1, 2, 3, 4]
# list2 = ['a', 'b', 'c', 'd']
# list3 = list1 + list2
# print(list3)
# 0r
#
from itertools import chain
print(list(chain([1, 2, 3, 4], ['a', 'b', 'c', 'd'])))
|
9f887a30ec14e4eff437c4e0a031ef2c61cc59b8 | Brandon-Martinez27/python-exercises | /control_structures_exercises.py | 11,965 | 4.375 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### 1. Conditional Basics
# #### a. prompt the user for a day of the week, print out whether the day is Monday or not
# In[1]:
valu = input("Enter day of the week: ")
print(valu)
# In[2]:
if valu.lower() == 'monday':
print("Today is Monday")
else:
print("Today is not Monday")
# #### b. prompt the user for a day of the week, print out whether the day is a weekday or a weekend
# In[3]:
valu2 = input("Enter day of the week: ")
print(valu2)
# In[4]:
if valu2.lower() == 'saturday' or valu2.lower() == 'sunday':
print("It's the freakin weekend!")
else:
print("Back to work...")
# #### c. create variables and make up values for
# - the number of hours worked in one week
# - the hourly rate
# - how much the week's paycheck will be
# #### write the python code that calculates the weekly paycheck. You get paid time and a half if you work more than 40 hours
# In[11]:
hours_per_week = 55
hourly_rate = 44
time_and_a_half = (hours_per_week - 40) * (hourly_rate * 1.5)
if hours_per_week > 40:
paycheck = (hourly_rate * 40) + time_and_a_half
else:
paycheck = hourly_rate * hours_per_week
print(paycheck)
# ### 2. Loop Basics
# a. While
#
# - Create an integer variable i with a value of 5.
# - Create a while loop that runs so long as i is less than or equal to 15
# - Each loop iteration, output the current value of i, then increment i by one.
# In[13]:
i = 5
while i <= 15:
print(i)
i += 1
# - Create a while loop that will count by 2's starting with 0 and ending at 100. Follow each number with a new line.
# - Alter your loop to count backwards by 5's from 100 to -10.
# - Create a while loop that starts at 2, and displays the number squared on each line while the number is less than 1,000,000. Output should equal:
# In[14]:
i = 0
while i <= 100:
print(i)
i += 2
print("________________________")
i = 100
while i >= -5:
print(i)
i -= 5
print("________________________")
i = 2
while i < 1_000_000:
print(i)
i = i**2
# - Write a loop that uses print to create the output shown below.
# In[15]:
i = 100
while i >= 5:
print(i)
i -= 5
# b. For Loops
#
# i. Write some code that prompts the user for a number, then shows a multiplication table up through 10 for that number
# In[18]:
inp = int(input("Enter a number: "))
for number in range(1,11):
print(inp, "x", number, "=", inp * number)
# ii. Create a for loop that uses print to create the output shown below.
# In[19]:
one_to_nine = list(range(1,10))
for n in one_to_nine:
print(str(n)*n)
# I spent way too long on this problem!
# I didn't know you could multiply a string by an integer.
# c. break and continue
#
# i. Prompt the user for an odd number between 1 and 50. Use a loop and a break statement to continue prompting the user if they enter invalid input. (Hint: use the isdigit method on strings to determine this). Use a loop and the continue statement to output all the odd numbers between 1 and 50, except for the number the user entered
# ###### ALL conditions must be True (and)
# - i <= 50 # input is less than/ equal to 50
# - i >= 1 # input is greater than/equal to 1
# - i.isdigit() # input is has digits
# - i % 2 != 0 # input must be odd
#
# ##### process
# - if all true then 'break' the loop
# - loop(while) the input command if one of conditons returns false
# - a while loop will stop when until condition is false
# - all true conditions must be reversed to keep running
# ###### step 1(failed): first try (didn't account for invalid info)
inp = int(input("Enter an odd number between 1 and 50: "))
while inp > 50 or inp < 1 or inp % 2 == 0:
inp = int(input("Enter an odd number between 1 and 50: "))
continue
# ###### step 2: Use a loop and the continue statement to output all the odd numbers between 1 and 50, except for the number the user entered
for n in range (1,51):
if n == inp:
print('Skipped', inp)
continue
if n % 2 != 0:
print(n)
# In[82]:
# final code
while True:
try:
inp = int(input("Enter an odd number between 1 and 50: "))
if inp <= 50 and inp >= 1 and inp % 2 != 0:
break
print('Read the prompt')
except ValueError:
print('Number please')
for n in range (1,51):
if n == inp:
print('Skipped', inp)
continue
if n % 2 != 0:
print(n)
# d. The input function can be used to prompt for input and use that input in your python code. Prompt the user to enter a positive number and write a loop that counts from 0 to that number. (Hints: first make sure that the value the user entered is a valid number, also note that the input function returns a string, so you'll need to convert this to a numeric type.)
# In[85]:
while True:
try:
inp = int(input("Enter a positive integer: "))
if inp > 0 :
break
print('Read the prompt')
except ValueError:
print('Integer please')
# In[86]:
for n in range (inp+1):
print(n)
# e. Write a program that prompts the user for a positive integer. Next write a loop that prints out the numbers from the number the user entered down to 1.
# In[92]:
while True:
try:
inp = int(input("Enter a positive integer: "))
if inp > 0 :
break
print('Read the prompt')
except ValueError:
print('Integer please')
# In[93]:
while inp > 0:
print(inp)
inp -= 1
# ### 3. Fizzbuzz
#
# One of the most common interview questions for entry-level programmers is the FizzBuzz test. Developed by Imran Ghory, the test is designed to test basic looping and conditional logic skills.
# - Write a program that prints the numbers from 1 to 100.
# In[94]:
for n in range(1,101):
print(n)
# - For multiples of three print "Fizz" instead of the number
# In[97]:
for n in range(1,101):
if n % 3 ==0:
print('Fizz')
continue
print(n)
# - For the multiples of five print "Buzz".
# In[98]:
for n in range(1,101):
if n % 5 == 0:
print('Buzz')
continue
print(n)
# - For numbers which are multiples of both three and five print "FizzBuzz".
# In[100]:
for n in range(1,101):
if n % 5 == 0 and n % 3 == 0:
print('FizzBuzz')
continue
print(n)
# ### 4. Display a table of powers.
# - Prompt the user to enter an integer.
# - Display a table of squares and cubes from 1 to the value entered
# - Ask if the user wants to continue.
# - Assume that the user will enter valid data.
# - Only continue if the user agrees to.
# ###### step 1: prompt user to enter integer
while True:
try:
inp = int(input("Enter an integer: "))
break
except ValueError:
print('Integer please')
# ###### step 2: display a table of squares & cubes from 1 to entered number
for x in range(1,inp+1):
print(x, x*2, x*3)
# ###### step 3: ask if user wants to continue (assume valid data)
inp = input("Would you like to continue: ")
if inp.lower() == 'yes':
continue
elif inp.lower() == 'no':
break
# In[32]:
# final code
while True:
try:
inp = int(input("Enter an integer: "))
except ValueError:
print('Integer please')
for x in range(1,inp+1):
print(x, x*2, x*3)
inp = input("Would you like to continue: ")
if inp.lower() == 'yes':
continue
elif inp.lower() == 'no':
break
# ### 5. Convert given number grades into letter grades.
#
# - Prompt the user for a numerical grade from 0 to 100.
# - Display the corresponding letter grade.
# - Prompt the user to continue.
# - Assume that the user will enter valid integers for the grades.
# - The application should only continue if the user agrees to.
# ###### step 1: prompt user for grade from 1 to 100
while True:
try:
inp = int(input("Enter your grade: "))
if inp >= 100 and inp <= 0: #swap for step 2
#insert step 3
break
print('Read the prompt')
except ValueError:
print('Number please')
# ###### step 2: Displays letter grade (based on response)
if inp <= 100 and inp >= 88:
print('A')
elif inp <= 87 and inp >= 80:
print('B')
elif inp <= 79 and inp >= 67:
print('C')
elif inp <= 66 and inp >= 60:
print('D')
elif inp <= 59 and inp >= 0:
print('F')
# ###### step 3: prompts user to continue
inp = input("Would you like to continue: ")
if inp.lower() == 'yes':
continue
elif inp.lower() == 'no':
break
# In[ ]:
# final code
while True:
try:
inp = int(input("Enter your grade: "))
if inp <= 100 and inp >= 88:
print('A')
elif inp <= 87 and inp >= 80:
print('B')
elif inp <= 79 and inp >= 67:
print('C')
elif inp <= 66 and inp >= 60:
print('D')
elif inp <= 59 and inp >= 0:
print('F')
inp = input("Would you like to continue: ")
if inp.lower() == 'yes':
continue
elif inp.lower() == 'no':
break
print('What was that?')
except ValueError:
print('Number please')
# #### Bonus
#
# - Edit your grade ranges to include pluses and minuses (ex: 99-100 = A+).
# In[ ]:
while True:
try:
inp = int(input("Enter your grade: "))
if inp <= 100 and inp >= 97:
print('A+')
elif inp <= 96 and inp >= 92:
print('A')
elif inp <= 91 and inp >= 88:
print('A-')
elif inp <= 87 and inp >= 85:
print('B+')
elif inp <= 84 and inp >= 83:
print('B')
elif inp <= 82 and inp >= 80:
print('B-')
elif inp <= 79 and inp >= 76:
print('C+')
elif inp <= 75 and inp >= 71:
print('C')
elif inp <= 70 and inp >= 67:
print('C-')
elif inp <= 66 and inp >= 65:
print('D+')
elif inp <= 64 and inp >= 62:
print('D')
elif inp <= 61 and inp >= 60:
print('D-')
elif inp <= 59 and inp >= 0:
print('F')
inp = input("Would you like to continue: ")
if inp.lower() == 'yes':
continue
elif inp.lower() == 'no':
break
print('What was that?')
except ValueError:
print('Number please')
# ### 6. Create a list of dictionaries where each dictionary represents a book that you have read. Each dictionary in the list should have the keys title, author, and genre. Loop through the list and print out information about each book.
#
# a. Prompt the user to enter a genre, then loop through your books list and print out the titles of all the books in that genre.
# In[71]:
# list of dictionaries, books I've read
books = [
{
"title": "The Power of Now",
"author": "Eckhart Tolle",
"genre": "Spiritual"
},
{
"title": "Waking Up",
"author": "Sam Harris",
"genre": "Spiritual"
},
{
"title": "Total Money Makeover",
"author": "Dave Ramsey",
"genre": "Finance"
},
{
"title": "I Will Teach You to be Rich",
"author": "Ramit Sethi",
"genre": "Finance" ,
},
{
"title": "The House of the Scorpion",
"author": "Nancy Farmer",
"genre": "Fiction"
},
{
"title": "Ender's Game",
"author": "Orson Scott Card",
"genre": "Fiction"
},
{
"title": "Essentialism",
"author": "Greg Mckeown",
"genre": "Self-help"
},
{
"title": "The Four Agreements",
"author": "Eckhart Tolle",
"genre": "Self-Help"
}
]
# In[79]:
inp = input("Enter a genre: ")
for book in books:
if inp.lower() == book["genre"].lower():
print(book["title"])
# In[ ]:
|
5df896df051c8ce0ff5cc2f76d2476ee10283f8e | navnoorsingh13/GW2019PA2 | /venv/Session20B.py | 433 | 4.125 | 4 | import pandas as pd
numbers = [10, 20, 30, 40, 50]
ages = {"John":30, "Jennie":26, "Jim":12, "Jack":22, "Joe":33}
S1 = pd.Series(numbers)
S2 = pd.Series(ages)
print(S1)
print()
print(S2)
print("----------")
# Access Elements in Series by indexing
print(S1[1])
print(S2["John"])
# Slicing in Series
print(S1[1:])
print(S1[:3])
print(S1[2:4])
print("----------")
print(S2["Jennie":])
print(S2[:"Jim"])
print(S2["Jennie":"Joe"]) |
8c4559a5e60bf4d40e20b6ffcb027234962c828e | Silentsoul04/FTSP_2020 | /CodeBasics_Pandas/Reshape_dataframe_using_melt()_Pandas.py | 3,133 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 13 11:11:49 2020
@author: Rajesh
"""
import pandas as pd
df = pd.read_csv('E:\CodeBasics_Pandas\Pandas_CSV_CB\weather4.csv')
df.head()
-------------
day chicago chennai berlin
0 Monday 32 75 41
1 Tuesday 30 77 43
2 Wednesday 28 75 45
3 Thursday 22 82 38
4 Friday 30 83 30
df1 = pd.melt(df,id_vars=['day'])
df1.head(10)
-----------------
day variable value
0 Monday chicago 32
1 Tuesday chicago 30
2 Wednesday chicago 28
3 Thursday chicago 22
4 Friday chicago 30
5 Saturday chicago 20
6 Sunday chicago 25
7 Monday chennai 75
8 Tuesday chennai 77
9 Wednesday chennai 75
df1[df1['variable']=='chicago']
---------
day variable value
0 Monday chicago 32
1 Tuesday chicago 30
2 Wednesday chicago 28
3 Thursday chicago 22
4 Friday chicago 30
5 Saturday chicago 20
6 Sunday chicago 25
# Now we want to change the column Name like variable & Value.
df1 = pd.melt(df,id_vars=['day'],var_name='city',value_name='temperature')
df1.head()
----------------
day city temperature
0 Monday chicago 32
1 Tuesday chicago 30
2 Wednesday chicago 28
3 Thursday chicago 22
4 Friday chicago 30
-------------------------------------------------------------------------------------------------
# Create a simple dataframe
# importing pandas as pd
import pandas as pd
# creating a dataframe
df = pd.DataFrame({'Name': {0: 'John', 1: 'Bob', 2: 'Shiela'},
'Course': {0: 'Masters', 1: 'Graduate', 2: 'Graduate'},
'Age': {0: 27, 1: 23, 2: 21}})
print(df)
------------
Name Course Age
0 John Masters 27
1 Bob Graduate 23
2 Shiela Graduate 21
# Name is id_vars and Course is value_vars
pd.melt(df, id_vars =['Name'], value_vars =['Course'])
--------------
Name variable value
0 John Course Masters
1 Bob Course Graduate
2 Shiela Course Graduate
pd.melt(df, id_vars =['Name'], value_vars =['Course','Age'])
-------------
Name variable value
0 John Course Masters
1 Bob Course Graduate
2 Shiela Course Graduate
3 John Age 27
4 Bob Age 23
5 Shiela Age 21
pd.melt(df, id_vars =['Name']) # value_vars is the default parameters.
------
Name variable value
0 John Course Masters
1 Bob Course Graduate
2 Shiela Course Graduate
3 John Age 27
4 Bob Age 23
5 Shiela Age 21
df1 = pd.melt(df,id_vars=['Name'],var_name='New_Courese',value_name='New_Degree')
print(df1)
---------------
Name New_Courese New_Degree
0 John Course Masters
1 Bob Course Graduate
2 Shiela Course Graduate
3 John Age 27
4 Bob Age 23
5 Shiela Age 21
|
272594cf74dc71f9ddf702062cc8e429cfcfb255 | poojithayadavalli/Graph | /detectCycle.py | 1,329 | 3.546875 | 4 | """
Pandu is interested in solving problems on Graph data structure and while he is solving those problems he noticed a problem statement as follows:
Given a directed graph with V vertices and E edges. You need to detect whether the graph contains any cycle formation of vertices or not.
If it is cyclic graph print "yes" else print "no"
Input:
First line consists of V vertices and E edges
Next E lines consists of edges connecting two vertices
Output:
print whether the contains cycle or not
Example 1:
Input:
5 7
1 2
2 3
1 3
3 4
1 4
2 5
3 5
Output:
no
Example 2:
Input:
4 5
1 2
2 3
3 4
4 3
3 1
Output:
yes
"""
def addEdge(s,d,graph):
graph[s].append(d)
def detectCycle(v,s,visit):
visit[v]=True
s[v]=True
for i in range(len(graph[v])):
if visit[graph[v][i]]==False:
if detectCycle(graph[v][i],s,visit):
return True
else:
return True
s[v]=False
return False
v,e=map(int,input().split())
graph=[[]for i in range(v+1)]
visit=[False]*(v+1)
stack=[False]*(v+1)
for i in range(e):
s,d=map(int,input().split())
addEdge(s,d,graph)
flag=False
for i in range(1,len(graph)):
if visit[i]==False:
if detectCycle(i,stack,visit)==True:
flag=True
break
if flag:
print("yes")
else:
print("no")
|
f0bdf58a9957eafcf68ab1f4094929d561b5a6b3 | loveiset/corePythonExercises | /13-20.py | 1,203 | 3.75 | 4 | class Time60(object):
# def __init__(self,hr=0,min=0):
# self.hr=hr
# self.min=min
def __str__(self):
return '%02d:%02d' % (self.hr,self.min)
def __repr__(self):
return '%s("%02d:%02d")' % self.__class__,self.hr,self.min
def __init__(self,*val):
if type(val[0]) is tuple:
self.hr=val[0][0]
self.min=val[0][1]
elif type(val[0]) is str:
self.hr=int(val[0].split(':')[0])
self.min=int(val[0].split(':')[1])
elif type(val[0]) is dict:
self.hr=val[0]['hr']
self.min=val[0]['min']
elif type(val) is tuple:
self.hr=val[0]
self.min=val[1]
def __add__(self,other):
hour=self.hr+other.hr
min=self.min+other.min
if min>=60:
min-=60
hour+=1
return self.__class__(hour,min)
def __iadd__(self,other):
self.hr+=other.hr
self.min+=other.min
if self.min>=60:
self.min-=60
self.hr+=1
return self
if __name__=='__main__':
time1=Time60(10,30)
time2=Time60({'hr':10,'min':30})
time3=Time60('10:30')
time4=Time60('12:5')
time5=Time60(8,45)
print time1
print time2
print time3
print time4
print time5
print time1+time5
time1+=time5
print time1
|
24ec1f5b3116f3817ed69f952f018d7206c7d990 | anjolinea/Python-for-Everybody | /ch10ex2.py | 400 | 3.546875 | 4 | fname = input("Enter file name>> ")
if len(fname) < 1:
fname = "mbox-short.txt"
fhand = open(fname)
hours_dict = dict()
for line in fhand:
if line.startswith("From "):
words = line.split()
hour = words[5].split(":")[0]
hours_dict[hour] = hours_dict.get(hour, 0) + 1
for hours_address, hours_count in sorted(hours_dict.items()):
print(hours_address, hours_count)
|
0b6982fc578b598e8ddf7c0010ba5b23f2fa5fd1 | clarkkentzh/python | /class/fa_son.py | 713 | 3.71875 | 4 | #coding=utf-8
# 父类的方法和变量都会被子类继承,__init__也会被继承
class Father(object):
def __init__(self,name):
self.name = name
door = 4
def fun(self):
print "这是父类的方法"
class Son(Father):
pass
# 子类在父类的基础上改变变量
class Son1(Father):
door = 2
# 子类在父类的基础上增加方法,也可以改变父类的方法
class Son2(Father):
def fun(self):
print "我在子类里面改变了这个方法"
def fun1(self):
print "这是子类的方法"
a = Son("first")
print "a = ",a.door
a.fun()
b = Son1("two")
print "b = ",b.door
b.fun()
c = Son2("three")
print "c = ",c.door
c.fun()
c.fun1()
|
c2cdf683a1e49be60236ac180495a67455024e3c | nekapoor7/Python-and-Django | /PythonNEW/Practice/StringVowels.py | 163 | 3.984375 | 4 | """Python | Program to accept the strings which contains all vowels"""
import re
s = input()
s1 = s.lower()
ss = re.findall(r'[aeiou]',s1)
print(len(ss))
print(ss) |
800f1dacfb7aa116b363286f562d003fad274de1 | yiguming/python | /15_29.py | 425 | 3.5625 | 4 | #!/usr/bin/env python
import re
#800-555-1212
#patt = '(\(\d{3}-?\)?\d{3}-\d{4}'
patt = r'(\d{3}-|\(\d{3}\))?\d{3}-\d{4}'
phonenumber1 = "800-555-1212"
phonenumber2 = "555-1212"
phonenumber3 = "(800)555-1212"
m1 = re.match(patt,phonenumber1)
m2 = re.match(patt,phonenumber2)
m3 = re.match(patt,phonenumber3)
if m1 is not None:print m1.group()
if m2 is not None:print m2.group()
if m3 is not None:print m3.group()
print "Done" |
64c7f810bdb85e7c40be429ea30163a9e30b2b53 | lukeolson/cs450-f20-demos | /demos/upload/nonlinear/Newton's Method.py | 701 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Newton's Method
# In[85]:
import numpy as np
import matplotlib.pyplot as pt
# Here's a function:
# In[86]:
def f(x):
return x**3 - x +1
def df(x):
return 3*x**2 - 1
xmesh = np.linspace(-2, 2, 100)
pt.ylim([-3, 10])
pt.plot(xmesh, f(xmesh))
# In[87]:
guesses = [2]
# Evaluate this cell many times in-place (using Ctrl-Enter)
# In[84]:
x = guesses[-1] # grab last guess
slope = df(x)
# plot approximate function
pt.plot(xmesh, f(xmesh))
pt.plot(xmesh, f(x) + slope*(xmesh-x))
pt.plot(x, f(x), "o")
pt.ylim([-3, 10])
pt.axhline(0, color="black")
# Compute approximate root
xnew = x - f(x) / slope
guesses.append(xnew)
print(xnew)
|
792831fa222f22b4cf36de5ccb02cb651f0fc3d0 | joaocbjr/EXERCICIOS_curso_intensivo_de_python | /exe6.7.py | 737 | 3.78125 | 4 | print('\n6.7 – Pessoas:\n'
' Comece com o programa que você escreveu no Exercício '
'6.1(página 147). Crie dois novos dicionários que representem'
' pessoas diferentes e armazene os três dicionários em uma '
'lista chamada people. Percorra sua lista de pessoas com '
'um laço. À medida que percorrer a lista, apresente tudo '
'que você sabe sobre cada pessoa.\n')
pessoa_0 = {'name': 'Ester', 'last_name': 'Francisca', 'age': 32, 'city': 'Aracaju'}
pessoa_1 = {'name': 'João', 'last_name': 'Correia', 'age': 38, 'city': 'Aracaju'}
pessoa_2 = {'name': 'Bernardo', 'last_name': 'Sandes', 'age': 3, 'city': 'Aracaju'}
people = [pessoa_0, pessoa_1, pessoa_2]
for people in people:
print(people)
|
aef2854cd60157967dbac9fe2792ace0dc56f764 | amkelso1/Module11 | /inheritance/Employee.py | 720 | 3.53125 | 4 | """
Author: Alex Kelso
Date:10/4/2020
program: employee.py
purpose: constructor and method for employee info
"""
from datetime import date
class Employee:
"""Employee Class"""
# Constructor
def __init__(self, lname, fname):
self.last_name = lname
self.first_name = fname
@property
def last_name(self):
return self._last_name
@last_name.setter
def last_name(self, value):
self._last_name = value
@property
def first_name(self):
return self._first_name
@first_name.setter
def first_name(self, value):
self._first_name = value
def display(self):
return '{}, {}'.format(self.last_name, self.first_name)
#driver |
9a044a6fbe03e13716778c0ade33ff9f5e743ac3 | code-learner37/Think-Python | /chapter6.py | 1,320 | 3.9375 | 4 | # 4 - 6 - 2017
# Chapter 6
# 6-1
''' The program prints 9 90 8100
it sums the values of all arugments in function c and then times it by 10,
and finally return the sqaure of it.
'''
# 6-2 Ackermann function
def ack(m, n):
if m == 0:
return n + 1
if m > 0 and n == 0:
return ack(m - 1, 1)
if m > 0 and n > 0:
return ack(m - 1, ack(m, n - 1))
# 6-3
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def is_palindrome(s):
if len(s) <= 1: # didn't think of this! I thought of modifying the middle function to accept odd number digits
return True
if first(s) == last(s):
return is_palindrome(middle(s))
else:
return False
'''
Q1: They all return empty string '' when the middle function is called with
a string with 2 letters, 1 letter, or an empty string.
'''
# 6-4
def is_power(a, b):
if a == b:
return True
if a % b == 0:
return is_power(a/b, b) # once again, I forgot to add "return" at the front
else:
return False
# 6-5
def gcd(a, b):
if a % b == 0:
return b
else:
return gcd(b, a%b)
|
76d23754a4e1ae9fa09325cdbd766899ce87f857 | yuyurun/nlp100-2020 | /src/ch01/ans09.py | 608 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import random
def shuffle_word_str(text):
ans = ''
for word in text.split():
if len(word) > 4:
l_word = list(word)
create_word = l_word[0] + ''.join(random.sample(
l_word[1:len(word)-1], len(l_word)-2)) + l_word[len(word)-1]
ans += create_word
else:
ans += word
ans += ' '
return ans
if __name__ == '__main__':
print('英文を入力してください.')
input_text = input()
print('== ランダム ==')
print(shuffle_word_str(input_text))
|
0d3f33e045f6b86fcedd06f1331650a4989b3d28 | rzhang1654/pyco | /4a.py | 327 | 3.59375 | 4 | #!/usr/bin/env python
def iterable(obj):
try:
iter(obj)
return True
except TypeError:
return False
# Driver Code
for element in [34, [4, 5], (4, 5),{4,5},
{"a":4}, "dfsdf", 4.5]:
print(element, " is iterable : ", iterable(element))
|
09b1ed79fe8c5d2dc4269789b4759e3bc353eb2e | rahul0124/Guvi_programs | /p50.py | 168 | 3.796875 | 4 | num=int(input())
while(1):
if num%2==0:
num=num//2
if num==1:
print("yes")
break
else:
print("no")
break |
f2f6896ca5dbd303a5bcfebb3859a7fd3bf16d15 | jeff-cangialosi/learn_python | /ex5.py | 857 | 4.125 | 4 | # Exercise 5
# This was coded while listening to the Hamilton soundtrack
mb_name = 'Giannis'
mb_age = 25 # I think this is correct
mb_height = 84 # Also a guess but probably close
mb_weight = 260 # Hopefully close
mb_eyes = 'Brown'
mb_teeth = 'White'
mb_hair = 'Black'
print(f"Let's talk about {mb_name}.")
print(f"He's {mb_height} inches tall.")
print(f"He's {mb_weight} pounds heavy.")
print("Actually that's not too heavy.")
print(f"He's got {mb_eyes} eyes and {mb_hair} hair.")
print(f"His teeth are usually {mb_teeth} depending on the coffee.")
# this line is tricky, try to get it exactly right
total = mb_age + mb_height + mb_weight
print(f"If I add {mb_age}, {mb_height}, and {mb_weight} I get {total}.")
centi_converter = 2.54
mb_height_cm = mb_height * centi_converter
print(f"Converting the height into centimeters, we get {mb_height_cm}.")
|
a495d3279d9ad169d6168b2a3cb149355f0d75b7 | jangjichang/Today-I-Learn | /Algorithm/Programmers/H-Index/test_h_index.py | 724 | 3.515625 | 4 | citations = [4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6]
result = 6
def test_simple():
assert solution(citations) == result
def solution(citations):
# citations = sorted(citations, reverse=True)
# answer = 0
for value in range(max(citations), 0, -1):
up = 0
for i in citations:
if value <= i:
up += 1
if value == up:
answer = value
return answer
def solution(citations):
answer = 0
length = len(citations)
h = 0
k = 0
citations.sort()
for i in range(0, length):
h = citations[i]
k = length - i
if k <= h:
answer = k
break
return answer
|
41b026b1fd9ea77f1a5fcdd82c2bf3dc203673c9 | balajisomasale/Udacity_Data-Structures-and-algorithms | /P0/Task2.py | 1,492 | 4.125 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 2: Which telephone number spent the longest time on the phone
during the period? Don't forget that time spent answering a call is
also time spent on the phone.
Print a message:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
"""
def longest_dur(data):
# Creating a new dictionary as it has key value pairs and is best for this use case
my_dictionary = {}
# Iterating through and appending the values to my newly added dictionary
for i in data:
if i[0] not in my_dictionary:
my_dictionary[i[0]] = int(i[3])
if i[1] not in my_dictionary:
my_dictionary[i[1]] = int(i[3])
else:
my_dictionary[i[0]] += int(i[3])
my_dictionary[i[1]] += int(i[3])
number_max = None
number_dur = 0
# Find the number with the maximum duration
for k,v in my_dictionary.items():
if v > number_dur:
number_dur = v
number_max = k
return [number_max, str(number_dur)]
number, time = longest_dur(calls)
print("{} spent the longest time, {} seconds, on the phone during September 2016.".format(number, time))
|
68b6376e2bf444eb23b81be18899b82397761590 | devdattachore/selenium-python-practice | /src/1_python/5_fileHandling/writeFile.py | 343 | 4.5 | 4 | # read a file and
# reverse its contents and
# write reversed contents in file
with open("test.txt", "r") as reader:
lines = reader.readlines()
print(lines)
with open("test.txt", "w") as writer:
reversedLines = reversed(lines)
print(reversedLines)
for line in reversedLines:
writer.write(line)
|
c125b76f8cf43a78219a886c740a6a44b0c2d985 | DamonMok/PythonLearning | /MySQL数据库_MySQL与Python交互_2.增加、删除、修改数据.py | 1,396 | 3.71875 | 4 | from pymysql import *
def main():
# 1.创建数据库连接
conn = connect(host="localhost", port=3306, user="root", password="damonmok", database="python_db")
# 2.获取游标对象
cursor = conn.cursor()
# 3.1 新增数据并返回受影响的函数
# count = cursor.execute('insert into student values (default,"张小猪", 22, "保密", 3, "1998-01-01", 0)')
# 3.2 修改数据并返回受影响的函数
# count = cursor.execute('update student set name="张大猪" where id=3')
# 3.3 删除数据并返回受影响的函数
count = cursor.execute('delete from student where id=4')
print(count)
# 4 增删改后,commit之后才会真正的起作用
conn.commit()
# 5 执行查询,并返回受影响的函数
count = cursor.execute('select * from student')
print("查询到%d条数据" % count)
# 6.获取查询到的数据
# 6.1 cursor.fetchone() 一条一条地取结果
# for i in range(count):
# rst = cursor.fetchone()
# print(rst)
# 6.2 fetchmany() # 默认一条条取,有指定参数就按照参数的数量取
# rst = cursor.fetchmany(3)
# print(rst)
# 6.3 fetchall() # 全部取出
rst = cursor.fetchall()
print(rst)
# 7.关闭游标对象、关闭数据库连接
cursor.close()
conn.close()
if __name__ == '__main__':
main()
|
442e0e475eeb79e5a2a3899dbf6d77e0b8a1d09f | charlottetan/Algorithms-2 | /Sorting/selection_sort.py | 374 | 3.875 | 4 | def selection_sort(array):
start = 0
while start < len(array) - 1:
lowest = start
for i in range(start + 1, len(array)):
if array[lowest] > array[i]:
lowest = i
swap(array, start, lowest)
start += 1
return array
def swap(array, idx1, idx2):
array[idx1], array[idx2] = array[idx2], array[idx1]
|
39cdfa13db87b5ba5040555acc2b70c337c8c029 | Byung-moon/AI_Hulnno_Academy_HighClass | /2020_0805_day3/kerasFunc.py | 1,265 | 3.53125 | 4 | import keras
import numpy as np
x_train = np.array([0, 1])
y_train = x_train * 2 + 1
print(x_train)
print(y_train)
x_test = np.array([2, 3])
y_test = x_test * 2 + 1
print(x_test)
print(y_test)
# 입력을 받는 입력 layer 만듦
# 입력 데이터의 모양을 알려주기 위해 shape 지정
x = keras.layers.Input(shape=(1,))
print(type(x))
# 이전 layer의 유닛과 모두 연결되는 Dense layer 만듦
# 유닛의 개수는 1
# 전의 layer. 즉, 입력 layer와 연결되지 않은 상태
d = keras.layers.Dense(1)
print(type(d))
y = d(x)
print(type(d))
print(type(y))
# 입력과 출력을 지정하여 Model 생성. 첫 번째 인자 : 입력, 두번째 : 출력
model = keras.models.Model(x,y)
# 모델 개요 출력
model.summary()
# 학습 전의 예측값 출력
y_predict = model.predict( x_test )
print( y_predict.flatten() )
print( y_test )
# compile 후 학습을 준비하고 fit을 사용하여 모델을 학습
model.compile('SGD', 'mse')
model.fit(x_train, y_train, epochs=1000, verbose=0)
# Functional 모델을 사용하여 학습한 결과 출력
# flatten() : data를 1차원으로 만들어줌
y_predict = model.predict(x_test)
print(y_predict.flatten())
print(y_test)
|
9d4d0f7eb52a1ec180a221318528e1214a3b95f0 | Heejeloper/-edwith-Python- | /2/boolean_index.py | 254 | 3.5625 | 4 | import numpy as np
def boolean_index(X, condition):
return X[eval(str("X")+condition)]
X = np.arange(32, dtype=np.float32).reshape(4, -1)
print(boolean_index(X, "== 3"))
X = np.arange(32, dtype=np.float32)
print(boolean_index(X, "> 6"))
|
bce9bfc3bd973ce93f247da50de4394025d71e48 | daniel-reich/turbo-robot | /x5o7jTvzXjujvrh6t_16.py | 632 | 4.5625 | 5 | """
The iterated square root of a number is the number of times the square root
function must be applied to bring the number **strictly under 2**.
Given an integer, return its iterated square root. Return `"invalid"` if it is
negative.
### Examples
i_sqrt(1) ➞ 0
i_sqrt(2) ➞ 1
i_sqrt(7) ➞ 2
i_sqrt(27) ➞ 3
i_sqrt(256) ➞ 4
i_sqrt(-1) ➞ "invalid"
### Notes
Idea for iterated square root by Richard Spence.
"""
import math
def i_sqrt(n):
if n < 0:
return "invalid"
else:
count = 0
while (n >= 2):
n = math.sqrt(n)
count += 1
return count
|
116c0b50644d7674c1d6674bc8c4fad9fb71d1bd | EricSchles/learn_python | /intro/data_structures.py | 503 | 4.21875 | 4 | # A data structure is just a structure for your data
party_list = ["dip","chips","wine","beer","hats"]
print("1st element of party list is",party_list[0])
print("2nd element of party list is",party_list[1])
print("5th element of party list is",party_list[4])
print("let's look at the party list, in it's entirety", ", ".join(party_list))
print("let's look at the party list, in it's entirety, a different way")
for element in party_list:
print(element)
if element == "wine":
break
|
2f5b9047455441aa0075ac28572d1c0780b89d93 | jananee009/Project_Euler | /SieveOfEratosthenes.py | 1,501 | 4.03125 | 4 |
import math
class SieveOfEratosthenes:
def __init__(self):
self.listOfNumbers = []
# checks if a given number is prime or non prime.
def isPrime(self,num):
sqrtNum = int(math.sqrt(num))
for i in range(2,sqrtNum+1):
if num % i == 0:
return False
return True
# Returns a list of all prime numbers under a certain number.
def implementSieveOfEratosthenes(self,limit):
listOfPrimes = []
self.listOfNumbers = [True]*(limit+1)
# create a list of booleans. Initially we assume that all numbers are prime. Hence their values are set to True.
self.listOfNumbers[0:2] = [False,False] # Since 0 and 1 are not prime numbers, set the flag for them as False in the list of booleans.
index = 2
sumOfPrimes = 0
while (index < limit**0.5+1):
if(self.isPrime(index)): # if index is prime, generate all the multiples of the index below limit and set their corresponding values to False.
# i.e. once we have found a prime number, we find all its multiples(composite numbers) and cross them off our list.
for i in range(index,limit/index+1):
self.listOfNumbers[index*i] = False
# Get the next highest value of index from the list whose value is True.
for j in range(index+1,limit+1):
if(self.listOfNumbers[j]):
index = j
break
# find the sum of all indices that have been marked as True on the list.
for ind,val in enumerate(self.listOfNumbers):
if(val):
listOfPrimes.append(ind)
return listOfPrimes
|
e97072115cfd22ea3f699e8c2a6cea6421be1ae2 | wubek/ProjectEuler | /euler/euler020.py | 534 | 4.125 | 4 | """n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
def factorial(number):
starter = 1
for i in range(2,number+1):
starter *= i
return starter
def sum_of_digits(number):
lst = str(number)
msum = 0
for i in lst:
msum += int(i)
return msum
print(factorial(100))
print(sum_of_digits(factorial(100))) |
9f2c3269f527db098a08c0b70e17bc7a3a31c611 | Neguentropie67/NSI_2021_2022 | /NSI_terminale/chapitre1_modularité_et_mise_au_point/mathematiques/fonctions.py | 815 | 4.0625 | 4 |
# n! = n * (n-1) * (n-2) * ... * 3 * 2 * 1
# 5! = 5 * 4 * 3 * 2 * 1 = 120
# Les standars de docstring : https://stackoverflow.com/questions/3898572/what-is-the-standard-python-docstring-format
def factorielle(n: int) -> int:
"""
Fonctions factorielles qui retourne la factorielle de l'entrée
n! = n * (n-1) * (n-2) * ... * 3 * 2 * 1
:param n: un nombre entier
:return: la factorielle de l'entrée
>>> factorielle(5)
120
"""
response = 1
for i in range(2, n+1):
response = response * i
return response
if __name__ == "__main__":
# execute only if run as a script
assert factorielle(5) == 120, "Il y a un problème !"
assert factorielle(0) == 1, "problème avec 0 !"
print(factorielle(5))
print("coucou tu executes directement ce fichier")
|
7002ff89feb14b83f52b32491fb304f8892ae1a9 | ZiUNO/CodeCraft | /utils/graph.py | 8,012 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
* @Author: ziuno
* @Software: PyCharm
* @Time: 2019/3/27 20:39
"""
class Graph(object):
def __init__(self):
self.__roads = []
self.__crosses = []
self.__graDic = {}
self.__roadDic = {}
self.__crossDic = {}
@property
def graDic(self):
return self.__graDic
@property
def roadDic(self):
return self.__roadDic
@property
def crossDic(self):
return self.__crossDic
def set_road(self, road):
self.__roads.append(road)
self.roadDic[road.id] = road
def set_cross(self, cross):
self.__crosses.append(cross)
# print(cross.id)
# print(cross.road_id_up)
# print(cross.road_id_right)
# print(cross.road_id_down)
# print(cross.road_id_left)
self.graDic[cross.id] = [cross.road_id_up, cross.road_id_right, cross.road_id_down, cross.road_id_left]
self.crossDic[cross.id] = cross
# print(self.__graDic)
def get_cross(self):
return self.__crosses
def get_road(self):
return self.__roads
def update(self):
for i in self.get_road():
i.update()
def get_roads(self, cross):
temp = []
for i in self.graDic[cross.id]:
if i in self.roadDic.keys():
temp.append(self.roadDic[i])
else:
temp.append(None)
return temp
def get_car_start_pos(self, car):
# 通过车的信息结合图的信息得知车的初始位置
return self.crossDic[car.start].xy
def get_car_end_pos(self, car):
# 通过车的信息结合图的信息得知车的终点的位置
return self.crossDic[car.end].xy
def get_end_direction(self, car, cross):
endcross = self.crossDic[car.end]
return [(1 if endcross.xy[1] > cross.xy[1] else 0), (1 if endcross.xy[0] > cross.xy[0] else 0),
(1 if endcross.xy[1] < cross.xy[1] else 0), (1 if endcross.xy[0] < cross.xy[0] else 0)]
def updatexy(self):
self.__crosses[0].xy = (0, 0)
crosjl = {self.__crosses[0].id: 0}
crossjl = {self.__crosses[0].id: (0, 0)}
t = True
while t:
t = False
for i in self.__crosses:
if (i.id not in crosjl or crosjl[i.id] != 0) and i.road_id_up >= 0 and self.roadDic[
i.road_id_up].end == i.id and self.roadDic[i.road_id_up].start in crosjl and crosjl[
self.roadDic[i.road_id_up].start] == 0:
if i.id in crosjl:
if crosjl[i.id] == 2 or crosjl[i.id] == 4:
i.xy = (self.crossDic[self.roadDic[i.road_id_up].start].xy[0], i.xy[1])
crosjl[i.id] = 0
crossjl[i.id] = i.xy
elif crosjl[i.id] == 1:
i.xy = ((self.crossDic[self.roadDic[i.road_id_up].start].xy[0] + i.xy[0]) / 2,
(self.crossDic[self.roadDic[i.road_id_up].start].xy[1] - 1 + i.xy[1]) / 2)
else:
i.xy = (self.crossDic[self.roadDic[i.road_id_up].start].xy[0],
self.crossDic[self.roadDic[i.road_id_up].start].xy[1] - 1)
crosjl[i.id] = 3
crossjl[i.id] = i.xy
t = True
if (i.id not in crosjl or crosjl[i.id] != 0) and i.road_id_right >= 0 and self.roadDic[
i.road_id_right].end == i.id and self.roadDic[i.road_id_right].start in crosjl and crosjl[
self.roadDic[i.road_id_right].start] == 0:
if i.id in crosjl:
if crosjl[i.id] == 1 or crosjl[i.id] == 3:
i.xy = (i.xy[0], self.crossDic[self.roadDic[i.road_id_right].start].xy[1])
crossjl[i.id] = i.xy
crosjl[i.id] = 0
elif crosjl[i.id] == 2:
i.xy = ((self.crossDic[self.roadDic[i.road_id_right].start].xy[0] - 1 + i.xy[0]) / 2,
(self.crossDic[self.roadDic[i.road_id_right].start].xy[1] + i.xy[1]) / 2)
else:
i.xy = (self.crossDic[self.roadDic[i.road_id_right].start].xy[0] - 1,
self.crossDic[self.roadDic[i.road_id_right].start].xy[1])
crosjl[i.id] = 4
crossjl[i.id] = i.xy
t = True
if (i.id not in crosjl or crosjl[i.id] != 0) and i.road_id_down >= 0 and self.roadDic[
i.road_id_down].end == i.id and self.roadDic[i.road_id_down].start in crosjl and crosjl[
self.roadDic[i.road_id_down].start] == 0:
if i.id in crosjl:
if crosjl[i.id] == 1 or crosjl[i.id] == 3:
i.xy = (self.crossDic[self.roadDic[i.road_id_down].start].xy[0], i.xy[1])
crosjl[i.id] = 0
crossjl[i.id] = i.xy
elif crosjl[i.id] == 3:
i.xy = ((self.crossDic[self.roadDic[i.road_id_down].start].xy[0] + i.xy[0]) / 2,
(self.crossDic[self.roadDic[i.road_id_down].start].xy[1] + 1 + i.xy[1]) / 2)
else:
i.xy = (self.crossDic[self.roadDic[i.road_id_down].start].xy[0],
self.crossDic[self.roadDic[i.road_id_down].start].xy[1] + 1)
crosjl[i.id] = 1
crossjl[i.id] = i.xy
t = True
if (i.id not in crosjl or crosjl[i.id] != 0) and i.road_id_left >= 0 and self.roadDic[
i.road_id_left].end == i.id and self.roadDic[i.road_id_left].start in crosjl and crosjl[
self.roadDic[i.road_id_left].start] == 0:
if i.id in crosjl:
if crosjl[i.id] == 2 or crosjl[i.id] == 4:
i.xy = (self.crossDic[self.roadDic[i.road_id_left].start].xy[0], i.xy[1])
crosjl[i.id] = 0
crossjl[i.id] = i.xy
elif crosjl[i.id] == 4:
i.xy = ((self.crossDic[self.roadDic[i.road_id_left].start].xy[0] + 1 + i.xy[0]) / 2,
(self.crossDic[self.roadDic[i.road_id_left].start].xy[1] + i.xy[1]) / 2)
else:
i.xy = (self.crossDic[self.roadDic[i.road_id_left].start].xy[0] + 1,
self.crossDic[self.roadDic[i.road_id_left].start].xy[1])
crosjl[i.id] = 2
crossjl[i.id] = i.xy
t = True
for i in crosjl.items():
crosjl[i[0]] = 0
return crossjl
# def init(self, road_path, cross_path):
# # road_path = u'../road.txt'
# # cross_path = u'../cross.txt'
# cross = read_txt.read_txt(cross_path)
# road = read_txt.read_txt(road_path)
# for i in road:
# temp = Road(i[0], i[1], i[2], i[3], i[4], i[5], i[6])
# self.set_road(temp)
# for i in cross:
# temp = Cross(i[0], i[1], i[2], i[3], i[4])
# self.set_cross(temp)
# if __name__ == '__main__':
# g = Graph()
# from cross import Cross
# from road import Road
# import read_txt
# g.init('../road.txt','../cross.txt')
# print (g.updatexy())
# print (g.crosses(0))
# # temp = Cross(4, 5003, 5010, 5002, -1)
# # road = Road(5003, 20, 4, 2, 4, 5, 1)
# # g.set_cross(temp)
# # g.set_road(road)
# # print(g.get_roads(temp))
# # print(g.get_road())
# # print(g.get_cross())
# # print(g.get_roads(temp))
|
56af8acd09e1a45d8091a3844a3e2c0e331f7517 | frclasso/turma3_Python1_2018 | /Cap14_Funcoes/testeFunc.py | 435 | 3.953125 | 4 | #!/usr/bin/env python3
# definindo uma funcao - def
# def my_func(parametros):
# return parametros
#
# # chamada de funcao
# print(my_func('Argumentos'))
def Func(this, that, other, *args, **kwargs):
print()
print('This is a test function',
kwargs['one'], kwargs['two'], kwargs['tree'],
kwargs['four'], this, that, other, args
)
print()
Func(5,6,7,8,9,10, one=1, two=2, tree=3,four=4)
|
2eb9fddea1fe9d5c1cde3d90f0e8832eaa8f7006 | LRBeaver/Eduonix | /db_testing_trwo.py | 954 | 3.578125 | 4 | __author__ = 'lyndsay.beaver'
import sqlite3 as sql
def create_market():
#market= {'ABC':rnd.randint(10,20), 'DEF': rnd.randint(10,20), 'XYZ': rnd.randint(10,20)}
stocks = ['ABC', 'DEF', 'HGI', 'LMK', 'OMN', 'PQR', 'STU', 'XYZ']
#prices = []
#for x in range(len(stocks)):
#prices.append(rnd.randint(10,20))
#market = dict(zip(stocks,prices))
return stocks
def populate_db_w_tickers():
db1_cursor.execute('CREATE TABLE stocks(ticker TEXT)')
connection = sql.connect('tickers.db')
with connection:
ticker_names = create_market()
cursor = connection.cursor()
for ticker in ticker_names[1:-1]:
if ticker == ['']:
print('\n Empty tuple found; skipping.\n')
continue
cursor.execute(
'''INSERT INTO ticker VALUES''' +
str(tuple(ticker_names)))
populate_db_w_tickers() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.