blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
07999243a551f3948b311e36ed14d6c5129076d9 | v0rs4/project_euler_solutions | /python/p004_1.py | 212 | 3.609375 | 4 | def isPalindrome(n):
return str(n) == str(n)[::-1]
def solve():
return max(x * y for x in range(100, 1000) for y in range(100, 1000) if isPalindrome(x * y))
if __name__ == "__main__":
print(solve()) |
6230fd200e52ea05cb0fc8bb59b14621431607ac | 06Prakash/python-training-codes | /iterablesCommon.py | 705 | 4.03125 | 4 | import itertools
def sprint(x):
'''
Special Print
:param x: Any iterable or not will be printed
'''
for c in x :
try :
for v in c :
print (v, end=" " )
except :
print(c)
print("")
if __name__ == "__main__" :
list1 = [ 1, 2, 3, 4, 5]
list2 = [ 'a', 'b', 'c', 'd']
print("Zip")
sprint(zip(list1,list2))
print("Product")
sprint(itertools.product(list1,list2))
print("Combination")
sprint(itertools.combinations(list2,3))
print("Permutations")
sprint(itertools.permutations(list2,3))
print("PowerSets")
#sprint(itertools.powerset(list1)) |
143f8ea31c7f3a3255098a375f1b2a2f853902f0 | Andross78/Kaizer | /min_max.py | 8,361 | 3.546875 | 4 | def minmax_1(array):
if not array:
return (None,None)
n = len(array)
min_int = array[0]
for i in range(1,n):
next_int = array[i]
if min_int > next_int:
min_int = next_int
max_int = array[0]
for i in range(1,n):
next_int = array[i]
if max_int < next_int:
max_int = next_int
return(min_int, max_int)
def minmax_2(array):
n = len(array)
area_list = []
for i in array:
area_list.append(i[0]*i[1])
min_area = area_list[0]
for i in range(1,n):
next_area = area_list[i]
if min_area > next_area:
min_area = next_area
return area_list, min_area
def minmax_3(array):
n = len(array)
p_list = []
for i in array:
p_list.append(2*(i[0]+i[1]))
max_p = p_list[0]
for i in range(1,n):
next_p = p_list[i]
if max_p < next_p:
max_p = next_p
return p_list, max_p
def minmax_4(array):
n = len(array)
min_int = array[0]
i_int = 0
for i in range(1,n):
if array[i] < min_int:
min_int = array[i]
i_int = i
return array, i_int
def minmax_5(array)
'''prosto'''
...
def minmax_6(array):
n = len(array)
min_int = array[0]
max_int = array[0]
for i in range(1,n):
if array[i] < min_int:
min_int = array[i]
min_i = i
elif array[i] > max_int:
max_int = array[i]
max_i = i
return min_i, min_int, max_i, max_int
def minmax_8(array):
n = len(array)
_min = array[0]
int_1 = 0
int_2 = 0
for i in range(1,n):
if array[i] < _min:
_min = array[i]
int_1 = i
int_2 = i
if array[i] == _min:
int_2 = i
return int_1, int_2
def minmax_12(array):
n = len(array)
max_int = array[0]
for i in range(1,n):
if max_int < array[i]:
max_int = array[i]
if max_int <= 0:
return 0
else:
return max_int
def minmax_13(array):
n = len(array)
max_int = None
max_i = 0
for i in range(1,n):
if array[i] % 2 != 0:
if max_int is None or max_int < array[i]:
max_int = array[i]
max_i = i
return max_i
def minmax_16(array):
min_int = min(array)
index_i = array.index(min_int)
for i in range(0, index_i):
print(array[i])
def minmax_22(array):
n = len(array)
min_1 = array[0]
min_2 = array[0]
for i in range(1,n):
if min_1 >= array[i]:
min_1,min_2 = array[i], min_1
return min_1,min_2
def minmax_24(array):
n = len(array)
max_sum = array[0]+ array[1]
for i in range(2,n):
sum = array[i-1] + array[i]
if sum > max_sum:
max_sum = sum
return max_sum
# *****************************************************
def minmax_7(array):
n = len(array)
max_digit = array[0]
min_digit = array[0]
max_i = 0
min_i = 0
for i in range(1,n):
if max_digit <= array[-i]:
max_digit = array[-i]
max_i = n-i
if min_digit >= array[i]:
min_digit = array[i]
min_i = i
return max_i, min_i
def minmax_8(array):
n = len(array)
f_i = 0
l_i = 0
min_el = array[0]
for i in range(1,n):
if min_el > array[i]:
min_el = array[i]
l_i = i
if array[i] == min_el:
l_i = i
return f_i, l_i
def minmax_9(array):
n = len(array)
f_i = 0
l_i = 0
max_el = array[0]
for i in range(1,n):
if max_el < array[i]:
max_el = array[i]
f_i = i
if array[i] == max_el:
l_i = i
return f_i, l_i
def minmax_10(array):
n = len(array)
_min = array[0]
_max = array[0]
min_i = 0
max_i = 0
for i in range(1,n):
if _min > array[i]:
_min = array[i]
min_i = i
if _max < array[i]:
_max = array[i]
max_i = i
if min_i < max_i:
return min_i
else:
return max_i
def minmax_11(array):
n = len(array)
_min = array[0]
_max = array[0]
min_i = 0
max_i = 0
for i in range(1,n):
if _min >= array[i]:
_min = array[i]
min_i = i
if _max <= array[i]:
_max = array[i]
max_i = i
if min_i > max_i:
return min_i
else:
return max_i
def minmax_12(array):
n = len(array)
new_arr = []
for i in array:
if array[i] >= 0:
new_arr.append(array[i])
if new_arr == []:
return 0
n = len(new_arr)
_min = new_arr[0]
for i in range(1,n):
if _min > new_arr[i]:
_min = new_arr[i]
return _min
def minmax_13(array):
n = len(array)
max_i = 0
max_int = None
for i in range(n):
if array[i] % 2 != 0:
if max_int is None or max_int < array[i]:
max_int = array[i]
max_i = i
if max_i == None:
return 0
return max_i
def minmax_14(array,b):
_min = None
n = len(array)
min_i = 00
for i in range(n):
if array[i] > b:
if _min is None or _min > array[i]:
_min = array[i]
min_i = i
return min_i
def minmax_15(array,b,c):
_max = None
n = len(array)
max_i = 0
for i in range(n):
if array[i] > n and array[i] < c:
if _max is None or _max < array[i]:
_max = array[i]
max_i = i
return max_i
def minmax_16(array):
n = len(array)
_min = array[0]
min_i = 0
for i in range(1,n):
if _min > array[i]:
_min = array[i]
min_i = i
return len(array[:min_i])
def minmax_17(array):
n = len(array)
_max = array[0]
max_i = 0
for i in range(1,n):
if _max <= array[i]:
_max = array[i]
max_i = i
return len(array[max_i:])
def minmax_18(array):
n = len(array)
_max = array[0]
m_1 = None
m_2 = None
for i in range(1,n):
if _max < array[i]:
_max = array[i]
m_1 = i
if array[i] == _max:
m_2 = i
return len(array[m_1+1:m_2])
def minmax_19(array):
n = len(array)
_min = array[0]
counter = 1
for i in range(1,n):
if _min > array[i]:
_min = array[i]
counter = 0
if array[i] == _min:
counter += 1
return counter
#/////////////////////
def minmax_20(array):
n = len(array)
_min = array[0]
_max = array[0]
c_min = 1
c_max = 1
for i in range(1,n):
if _min > array[i]:
_min = array[i]
c_min = 0
if _max < array[i]:
_max = array[i]
c_max = 0
if array[i] == _max:
c_max += 1
if array[i] == _min:
c_min += 1
return c_min+c_max
# def minmax_21(array):
# n = len(array)
# summ = 0
# counter = 0
# _min = array[0]
# _max = array[0]
# for i in range(1,n):
# if _min > array[i]:
# counter += 1
# summ += _min
# _min = array[i]
# if _max < array[i]:
# counter += 1
# summ += _max
# _max = array[i]
# else:
# counter +=1
# summ += array[i]
def minmax_22(array):
n = len(array)
min_1 = array[0]
min_2 = array[0]
for i in range(1,n):
if min_1 > array[i]:
min_2 = min_1
min_1 = array[i]
return min_1, min_2
def minmax_23(array):
n = len(array)
max_1 = array[0]
max_2 = array[0]
max_3 = array[0]
for i in range(1,n):
if max_1 < array[i]:
max_3,max_2,max_1 = max_2,max_1,array[i]
elif max_1 > array[i] and max_2 < array[i]:
max_3, max_2 = max_2, array[i]
return max_1, max_2, max_3
def minmax_25(array):
n = len(array)
prod = array[0]*array[1]
i_1 = 0
i_2 = 0
for i in range(2,n):
if prod > array[i-1]*array[i]:
prod = array[i-1]*array[i]
i_1 = i-1
i_2 = i
return i_1, i_2
|
2e38b50b436eb0352955cbc69f589bd43f5c25c0 | toxa1711/helper | /Input_Audio.py | 510 | 3.515625 | 4 | import speech_recognition as sr
def input_audio():
r = sr.Recognizer(language="ru")
with sr.Microphone() as source: # use the default microphone as the audio source
audio = r.listen(source) # listen for the first phrase and extract it into audio data
try:
return r.recognize(audio) # recognize speech using Google Speech Recognition
except LookupError: # speech is unintelligible
return " "
|
6e3314329a350e7b716b6332fddc713fc464482b | vengadam2001/iot | /hello.py | 151 | 3.890625 | 4 | l = int(input("enter a number"))
def oe(n=1):
if (n % 2 == 0):
return "even"
else:
return "odd"
print(f"{l} is a ", oe(l))
|
8b0e52b691e3fe832804bbe32847eb97577b1b6b | jguarni/Python-Labs-Project | /Lab 2/testme1.py | 82 | 3.65625 | 4 | def divide_by_5(number):
hello = (number/5)
print(hello)
divide_by_5(3)
|
2dd5c760bf9cf7b41a808cae47a621981dbb9997 | jguarni/Python-Labs-Project | /Lab 6/testclass.py | 1,186 | 4.0625 | 4 | from cisc106 import *
class Employee:
"""
An employee is a person who works for a company.
position -- string
salary -- integer
"""
def __init__(self,position,salary,age):
self.position = position
self.salary = salary
self.age = age
"""
def employee_function(aEmployee,...):
return aEmployee.position
aEmployee.salary
"""
def employee_status(self):
"""
Gives you the positon and salary of the employee
Employee -- Employee
return -- string
"""
print(self.position)
print("The Salary of the employee is", self.salary)
print("The age of the employee is", self.age)
return(self.position)
def change_salary(self,change):
"""
Changes the position of the employee
Position - Position
return - String
"""
self.salary = self.salary + (self.salary * change)
aEmployee1 = Employee("CEO",500000,24)
aEmployee2 = Employee("Programmer",100000,19)
aEmployee1.employee_status
aEmployee2.change_salary(.50)
assertEqual(aEmployee1.employee_status(),'CEO')
|
075463a7832a8638a6cb22fad6258a401432b9e3 | jguarni/Python-Labs-Project | /Lab 4/lab4.py | 5,585 | 4.28125 | 4 | # Lab 4
# CISC 106 6/24/13
# Joe Guarni
from cisc106 import *
from random import *
#Problem 1
def rand(num):
"""
This function will first set a range from 0 to an input parameter,
then prompt the user to guess a number in that range. It will then
notify the user weather their input was correct, too high, or too low
compared to the random number.
num -- number
return - nothing as this function prints its output
"""
randvar = randrange(0,num+1)
number = int(input("Please enter a number between 0 and " + str(num ) +": "))
if (number == randvar):
print("Congratulations! You guessed the number!")
elif (number > randvar):
print("Your guess was too high")
elif (number < randvar):
print("Your guess was too low")
rand(10)
rand(100)
rand(1000)
# Problem 2
def hort():
"""
This function will ask the user for heads or tails and compare
thier answer to a randomly generated true or false, and return
weather their guess was correct.
return -- boolean
"""
randvar = randrange(0,2)
guess = int(input("Heads[Press 0] or Tails[Press 1] ?: "))
if (guess == 1) and (randvar == 1) or (guess == 0) and (randvar == 0):
return True
else:
return False
def hort2():
"""
This function will determine the winner of the best of 5 game. If the user
or computer wins 3 times the loop will stop as one of the players has won.
"""
time = 0
user = 0
computer = 0
while(time < 5):
if hort():
user = user + 1
else:
computer = computer + 1
if (user >= 3):
print('The user has beaten the computer!')
return
if (computer >= 3):
print('The computer has beaten the user!')
return
time = time + 1
hort2()
#Problem 3
def addition(x):
"""
This function will take a numerical input and return the sum
of all the numbers from 0 until the input number.
x -- number
return -- number
"""
total = 0
while(x > 0):
total = total + x
x = x - 1
return total
assertEqual(addition(3),(6))
assertEqual(addition(4),(10))
assertEqual(addition(6),(21))
#Problem 4
def randsum(n):
"""
This function will generate n amount of numbers between 0 and 100
and print the random numbers and their sum total.
n -- number
return -- number
"""
endval = 0
print("Numbers: ")
while (n > 0):
randomv = randrange(0,101)
print(randomv)
endval = endval + randomv
n = n - 1
print("Total Sum: ", endval)
randsum(10)
randsum(15)
randsum(20)
#Problem 5
def practice(x):
"""
This function will generate a number between 0-10, and then ask the user
for the answer of that random number multiplied against the input x value.
If the user is correct, the function will return true, and if incorrect,
return false.
x -- Number
return -- Boolean
"""
randvar = randrange(0,11)
uinput = int(input("What is " + str(randvar ) + " times " + str(x ) + "? "))
answer = randvar * x
if (answer == uinput):
print("Correct")
return True
else:
print("Incorrect")
return False
practice(5)
practice(7)
#Problem 6
numbers1 = [2, 4, 6, 8, 1, 5, 7, 9, 10, 12, 14]
def square(valuelist):
"""
This function will take input as a list and print the square of each
number in that list.
valuelist -- number
print -- number
"""
for num in valuelist:
sq = num ** 2
print(sq)
square(numbers1)
#Problem 7
def blackjack():
"""
This function will emulate a game of blackjack. It will hand random card
numbers to the user and ask them each time if they want another card. It
will then test the users hand against the randomly generated computers
hand to see who won the game according to the rules of blackjack.
"""
print('Welcome to Wacky BlackJack!')
ans = 'yes'
uhand = 0
while (ans == 'yes'):
unumber = randrange(1,12)
print('Your card is',unumber)
uhand = uhand + unumber
print('Your hand total is',uhand)
if (uhand > 21):
print('You went over 21!')
ans = input('Would you like to try again? ')
uhand = 0
else:
ans = input('Do you wish to continue? ')
if (ans == 'no'):
dhand = randrange(11,31)
print('The dealers score is',dhand)
if (dhand > 21):
print('The user has won the game!')
elif (dhand <= 21) and (uhand > 21):
print('The computer has won the game!')
elif (dhand <= 21) and (dhand > uhand):
print('The computer has won the game!')
elif (uhand <= 21) and (uhand >= dhand):
print('The user has won the game!')
blackjack()
#Problem 8
def random_list(maxval,amount):
"""
This function will produce a input value(amount) list of random numbers between 0 and
specified maxvaule input with legnth N
maxval -- number
amount -- number
return -- list with numbers
"""
rlist = []
for i in range(amount):
rlist.append(randrange(0,maxval+1))
return rlist
assertEqual(len(random_list(100, 1000)), 1000)
assertEqual(min(random_list(100, 1000)) >= 0, True)
assertEqual(max(random_list(1, 1000)) <= 1, True)
|
bd7938eb01d3dc51b4c5a29b68d9f4518163cc92 | jguarni/Python-Labs-Project | /Lab 5/prob2test.py | 721 | 4.125 | 4 | from cisc106 import *
def tuple_avg_rec(aList,index):
"""
This function will take a list of non-empty tuples with integers
as elements and return a list with the averages of the elements
in each tuple using recursion.
aList - List of Numbers
return - List with Floating Numbers
"""
newList = []
if len(aList) == 0:
return 0
if (len(aList) != index):
newList.append((sum(aList[index])/len(aList[index])))
newList.extend((sum(aList[index])/len(aList[index])))
print(aList[index])
tuple_avg_rec(aList, index+1)
return newList
assertEqual(tuple_avg_rec(([(4,5,6),(1,2,3),(7,8,9)]),0),[5.0, 2.0, 8.0])
|
e63dc201a8e29e4227ff4ce0871c3e50377b529e | yveslym/Herd_Immunity_Project | /person.py | 3,259 | 3.703125 | 4 | import random
# TODO: Import the virus clase
import uuid
from randomUser import Create_user
import pdb
'''
Person objects will populate the simulation.
_____Attributes______:
_id: Int. A unique ID assigned to each person.
is_vaccinated: Bool. Determines whether the person object is vaccinated against
the disease in the simulation.
is_alive: Bool. All person objects begin alive (value set to true). Changed
to false if person object dies from an infection.
infection: None/Virus object. Set to None for people that are not infected.
If a person is infected, will instead be set to the virus object the person
is infected with.
_____Methods_____:
__init__(self, _id, is_vaccinated, infected=False):
- self.alive should be automatically set to true during instantiation.
- all other attributes for self should be set to their corresponding parameter
passed during instantiation.
- If person is chosen to be infected for first round of simulation, then
the object should create a Virus object and set it as the value for
self.infection. Otherwise, self.infection should be set to None.
did_survive_infection(self):
- Only called if infection attribute is not None.
- Takes no inputs.
- Generates a random number between 0 and 1.
- Compares random number to mortality_rate attribute stored in person's infection
attribute.
- If random number is smaller, person has died from disease.
is_alive is changed to false.
- If random number is larger, person has survived disease. Person's
is_vaccinated attribute is changed to True, and set self.infected to None.
'''
class Person(object):
def __init__(self, is_vaccinated=False, infected=False, virus = None):
# TODO: Finish this method. Follow the instructions in the class documentation
# to set the corret values for the following attributes.
self._id = uuid.uuid4().hex[:10]
self.is_vaccinated = is_vaccinated
self.is_alive = True
self.survive = False
self.infected = infected #virus type object
self.virus = virus
self.interacted = False
user_obj = Create_user()
user = user_obj.create()
self.name = ('%s %s' %(user.first_name,user.last_name))
#pdb.set_trace()
def did_survive_infection(self):
# TODO: Finish this method. Follow the instructions in the class documentation
# for resolve_infection. If person dies, set is_alive to False and return False.
# If person lives, set is_vaccinated = True, infected = None, return True.
if self.infected is not None:
chance_to_survive = random.uniform(0.0,1.0)
if chance_to_survive > self.virus.mortality_rate:
self.is_alive = True
self.is_vaccinated = True
self.infected = False
return True
else:
self.is_alive = False
self.infected = False
return False
pass
#def resolve_infection():
#chance_to_survice
|
bc189bd3a9ffce0d504d932c4a0ff4a2199323a4 | donw385/DS-Unit-3-Sprint-2-SQL-and-Databases | /demo_data.py | 833 | 3.984375 | 4 | import sqlite3
conn = sqlite3.connect('demo_data.sqlite3')
curs = conn.cursor()
curs.execute(
"""
CREATE TABLE demo (
s str,
x int,
y int
);
"""
)
conn.commit()
curs.execute(
"""
INSERT INTO demo
VALUES
('g',3,9),
('v',5,7),
('f',8,7);
""")
conn.commit()
# Count how many rows you have - it should be 3!
query = 'SELECT count(*) FROM demo;'
print ('Rows:',conn.cursor().execute(query).fetchone()[0], '\n')
# How many rows are there where both x and y are at least 5?
query2 = 'SELECT count(s) FROM demo WHERE x >= 5 AND y >= 5;'
print ('Rows X and Y at least 5:',conn.cursor().execute(query2).fetchone()[0], '\n')
# How many unique values of y are there?
query3 = 'SELECT COUNT(DISTINCT y) FROM demo;'
print ('Unique Y Values:',conn.cursor().execute(query3).fetchone()[0], '\n')
|
3e561974952579ce8c2a42e263927912f9e87a53 | Sakshi-16-01/CBAP_13DEC | /03PythonBasics.py | 4,693 | 4.03125 | 4 |
#Topic : Basic Programming
#Numbers: Integers and floats work as you would expect from other languages:
x = 3
print(x)
print(type(x)) # Prints "3"
print(x + 1) # Addition; prints "4"
print(x - 1) # Subtraction; prints "2"
print(x * 2) # Multiplication; prints "6"
print(x ** 2) # Exponentiation; prints "9"
x=5
x += 1
x
x=x+1
print(x) # Prints "4"
x=5
x *= 2
print(x) # Prints "8"
x=5
x **= 2
print(x) # Prints "8"
y = 2.5
print(type(y)) # Prints "<class 'float'>"
print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"
#Python does not have unary increment (x++) or decrement (x--) operators
#%%
#Booleans: Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols (&&, ||, etc.):
t = True
f = False
print(type(f)) # Prints "<class 'bool'>"
AND
0 0 0
0 1 0
1 0 0
1 1 1
OR
0 0 0
0 1 1
1 0 1
1 1 1
Not
0 1
1 0
Ex OR
0 0 0
0 1 1
1 0 1
1 1 0
t=1
f=0
print(t and f) # Logical AND; prints "False"
print(t or f) # Logical OR; prints "True"
print(not t) # Logical NOT; prints "False"
t=1
f=1
print(t != f) # Logical XOR; prints "True"
#%%
#Strings: Python has great support for strings:
Fname='vikas'
type(Fname)
Lname='khullar'
name = Fname +' ' + Lname
print(name)
h = 'hello' # String literals can use single quotes
w = "world" # or double quotes; it does not matter.
print(h) # Prints "hello"
print(len(h)) # String length; prints "5"
hw = h + ' ' + w # String concatenation
print(hw) # prints "hello world"
hw12 = '%s %s %s' % ('hello', 'world', 12)
hw12
# sprintf style string formatting
print(hw12) # prints "hello world 12"
#String objects have a bunch of useful methods; for example:
s = "hello"
s.capitalize()
print(s.capitalize()) # Capitalize a string; prints "Hello"
print(s.upper()) # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7)) # Right-justify a string, padding with spaces; prints " hello"
print(s.center(10)) # Center a string, padding with spaces; prints " hello "
s=s.replace('e', 'yyy')
s
print(s) # Replace all instances of one substring with another; # prints "he(ell)(ell)o"
s=s.replace('o', 'yyy')
print(s) # Replace all instances of one substring with another; # prints "he(ell)(ell)o"
s = "hello"
z=' world '
print(z)
print(z.strip()) # Strip leading and trailing whitespace; prints "world"
#%%%Containers
#Python includes several built-in container types: lists, dictionaries, sets, and tuples.
#ListsA list is the Python equivalent of an array, but is resizeable and can contain elements of different types:
xs = [30, 10, "ff", 55, 888] # Create a list
xs
print(xs[2]) # Prints "[3, 1, 2] 2"
print(xs[-2]) # Negative indices count from the end of the list; prints "2"
xs[2] = 'foo' # Lists can contain elements of different types
print(xs) # Prints "[3, 1, 'foo']"
xs.append('')
xs.append('bar') # Add a new element to the end of the list
print(xs) # Prints "[3, 1, 'foo', 'bar']"
x = xs.pop() # Remove and return the last element of the list
x
xs
print(x, xs) # Prints "bar [3, 1, 'foo']"
#Slicing: In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing:
x=range(5, 10)
x
a=100.6
b=a//10
b
import math
math.ceil(b)
a = range(10, 20)
type(a)
nums = list(a) # range is a built-in function that creates a list of integers
nums
print(nums) # Prints "[0, 1, 2, 3, 4]"
print(nums[2:5]) # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[5:]) # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:3]) # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums) # Get a slice of the whole list; prints "[0, 1, 2, 3, 4]"
print(nums[-4:]) # Slice indices can be negative; prints "[0, 1, 2, 3]"
nums[2:4] = [8, 9] # Assign a new sublist to a slice
nums
print(nums) # Prints "[0, 1, 8, 9, 4]"
#Some Builtin Functions
a= bin(17)
a
a=bool(0)
a
a=bytearray(10)
a
#a=bytes(6)
a
ASCII
a=chr(65)
a
a=eval("False or False")
a
help()
a=hex(19)
a
x = iter(["apple", "banana", "cherry"])
x
print(next(x))
print(next(x))
print(next(x))
len(a)
max(iter(["apple", "banana", "cherry"]))
a=range(2,10)
a
list_a=list(a)
list_a
round(22.6)
a=str(11.7)
a
x=iter([1,4,2])
a=sum(x)
a
type(a)
abs(-11.7)
mylist = [True, True, False]
x = any(mylist)
x
len(x)
x = ['apple', 'banana', 'cherry']
len(x)
print('Enter your name:')
x = input()
x
x= input("Enter a number")
x
x = pow(4, 3)
x
|
ef1d6ca5aa113b72984f55a10ddd9cf0561e190f | CHINAJR/Sort | /GenerateRandomArray.py | 238 | 3.546875 | 4 | import random
def GenerateRandomArray(size,maxnum):
n = []
size = random.randint(1,size)
for i in range(size):
n.append(random.randint(1,maxnum))
print(n)
if __name__ == '__main__':
for i in range(10):
GenerateRandomArray(5,10)
|
8656ff504d98876c89ead36e7dd4cc73c3d2249e | jlopezmx/community-resources | /careercup.com/exercises/04-Detect-Strings-Are-Anagrams.py | 2,923 | 4.21875 | 4 | # Jaziel Lopez <[email protected]>
# Software Developer
# http://jlopez.mx
words = {'left': "secured", 'right': "rescued"}
def anagram(left="", right=""):
"""
Compare left and right strings
Determine if strings are anagram
:param left:
:param right:
:return:
"""
# anagram: left and right strings have been reduced to empty strings
if not len(left) and not len(right):
print("Anagram!")
return True
# anagram not possible on asymetric strings
if not len(left) == len(right):
print("Impossible Anagram: asymetric strings `{}`({}) - `{}`({})".format(left, len(left), right, len(right)))
return False
# get first char from left string
# it should exist on right regardless char position
# if first char from left does not exist at all in right string
# anagram is not possible
char = left[0]
if not has_char(right, char):
print("Impossible Anagram: char `{}` in `{}` not exists in `{}`".format(char, left, right))
return False
left = reduce(left, char)
right = reduce(right, char)
if len(left) and len(right):
print("After eliminating char `{}`\n `{}` - `{}`\n".format(char, left, right))
else:
print("Both strings have been reduced\n")
# keep reducing left and right strings until empty strings
# anagram is possible when left and right strings are reduced to empty strings
anagram(left, right)
def has_char(haystack, char):
"""
Determine if a given char exists in a string regardless of the position
:param haystack:
:param char:
:return:
"""
char_in_string = False
for i in range(0, len(haystack)):
if haystack[i] == char:
char_in_string = True
break
return char_in_string
def reduce(haystack, char):
"""
Return a reduced string after eliminating `char` from original haystack
:param haystack:
:param char:
:return:
"""
output = ""
char_times_string = 0
for i in range(0, len(haystack)):
if haystack[i] == char:
char_times_string += 1
if haystack[i] == char and char_times_string > 1:
output += haystack[i]
if haystack[i] != char:
output += haystack[i]
return output
print("\nAre `{}` and `{}` anagrams?\n".format(words['left'], words['right']))
anagram(words['left'], words['right'])
# How to use:
# $ python3 04-Detect-Strings-Are-Anagrams.py
#
# Are `secured` and `rescued` anagrams?
#
# After eliminating char `s`
# `ecured` - `recued`
#
# After eliminating char `e`
# `cured` - `rcued`
#
# After eliminating char `c`
# `ured` - `rued`
#
# After eliminating char `u`
# `red` - `red`
#
# After eliminating char `r`
# `ed` - `ed`
#
# After eliminating char `e`
# `d` - `d`
#
# Both strings have been reduced
#
# Anagram!
#
# Process finished with exit code 0
|
035899efa2286718b1862f03d39cd36936a2283b | Giioke/SacredTexts_Scraper | /Web_Scrapper.py | 1,271 | 3.703125 | 4 | #Web Scraper for SacredTexts.com
# Source - https://www.youtube.com/watch?v=7SWVXPYZLJM&t=397s
import requests
from bs4 import BeautifulSoup
url = "http://www.sacred-texts.com/index.htm"
resp = requests.get(url)
#Ability to read the HTML in python
soup = BeautifulSoup(resp.text, 'lxml')
WebCode = soup.prettify()
print(WebCode)
# Find the names and links to the books in the website's menu elements
topicMenu = soup.find('span', class_='menutext')
#print(topicMenu)
#Extract topic names
topicMenu_cut = topicMenu.find_all(string = True)
titles = [title.strip() for title in topicMenu_cut]
titles = list(filter(None, titles))
#print(titles)
# Extract Links
LinksMenu = [soup.find('a', href = True) for links in topicMenu]
#LinksMenu = LinksMenu.attrs['href']
#print(LinksMenu)
## Data Structure
# topics = {
# "topic1": {
# "descript": "content",
# "topicLink": "weblink"
# },
# "topic2": {
# "descript": "content",
# "topicLink": "weblink"
# }
## Add more topics?
# }
##For-Loop each topic displays their name, description, and the link.
# for topicname, topicinfo in topics.items():
# print("\n")
# print(topicname)
# print(topicinfo['descript'])
# print(topicinfo['topicLink'])
# print("\n") |
71e6ac073a1488d1f9ce4abdc86aad30fcd67e25 | HannibalCJH/Leetcode-Practice | /002. Add Two Numbers/Python: Recursive Solution.py | 921 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
def addNumbers(list1, list2, carry):
if not list1 and not list2:
# Python的三元运算符,"True result" if True else "False result"
return ListNode(1) if carry else None
if not list1:
list1 = ListNode(0)
if not list2:
list2 = ListNode(0)
sum = list1.val + list2.val + carry
node = ListNode(sum % 10)
node.next = addNumbers(list1.next, list2.next, sum // 10)
return node
return addNumbers(l1, l2, 0)
|
95243651c271a0289c9879e90f86b29f0534cf10 | camilooob/pythonisfun | /errores.py | 246 | 3.890625 | 4 | paises = {
"colombia": 49,
"mexico": 244,
"argentina": 20
}
while True:
country = str(input("Ingrese el pais:")).lower()
try:
print("El pais {} tiene {}".format(country, paises[country]))
except KeyError:
print("No tenemos ese dato")
|
a0ee55e5165643eac48e2701eb0d4690b177df38 | camilooob/pythonisfun | /.history/discounted_20191130165043.py | 1,100 | 3.890625 | 4 | def main():
# # Inputs
price = 500
# # Process
DISCOUNT30 = 0.3
DISCOUNT20 = 0.2
DISCOUNT10 = 0.1
DISCOUNT5 = 0.05
DISCOUNT0 = 0
DISCOUNTO = 0
NEWPRICE = 0
if PRICE >= 300:
DESCUENTO = PRICE * DISCOUNT30
NEWPRICE = PRICE - DESCUENTO
print("discount= ", DISCOUNT30)
print("price = ", NEWPRICE)
elif PRICE >= 200 and PRICE < 300:
DESCUENTO = PRICE * DISCOUNT20
NEWPRICE = PRICE - DESCUENTO
print("discount= ", DISCOUNT20)
print("price = ", NEWPRICE)
elif PRICE >= 100 and PRICE < 200:
DESCUENTO = PRICE * DISCOUNT10
NEWPRICE = PRICE - DESCUENTO
print("discount= ", DISCOUNT10)
print("price = ", NEWPRICE)
elif PRICE < 100 and PRICE >= 0:
DESCUENTO = PRICE * DISCOUNT5
NEWPRICE = PRICE - DESCUENTO
print("discount= ", DISCOUNT5)
print("price = ", NEWPRICE)
elif PRICE < 0:
DESCUENTO = PRICE * DISCOUNT0
NEWPRICE = PRICE
print("No Discount")
print("price = ", NEWPRICE)
main()
|
8861ee4af0e8b701eeda7d304a4d2293f67f8132 | Pejoicen/CalcRtlCodeLineNumber | /检测有效代码行数.py | 5,293 | 3.796875 | 4 | #open file
#read one line contex,judge if code or comment
# if '--' in the head this line is comment
# if doesn’t has code this line is empty
# else this line is code line
filename = input('''要求文件编码格式为UTF-8
.vhd文件,支持识别 -- 注释,以及空行
.v 文件,支持识别 // 注释, /**/ 注释,以及空行
输入文件路径(包含文件名和扩展名):''')
# open file
#file = open(filename,encoding='ANSI')
#file = open(filename,encoding='UTF-8')
#file = open(filename)
totalline = 0
validline = 0
emptyline = 0
commentline = 0
commentcnt = 0
commentflag = 0
validcharcnt= 0
# .vhd => 1 .v => 2
FileType = 0
#file is .v or .vhd(.VHD)
#get filename length
length = len(filename)
if filename[length-3:length] == 'vhd' or filename[length-3:length] == 'VHD':
FileType = 1
elif filename[length-1:length] == 'v' or filename[length-3:length] == 'V':
FileType = 2
else:
FileType = 3
print('不支持该文件类型')
exit()
# open file with auto close
with open(filename,encoding='UTF-8') as file:
if FileType == 1 :
for line in file.readlines():
totalline = totalline +1
commentcnt = 0
commentflag = 0
validcharcnt = 0
#print(line)
for char in line:
if char == '-' and validcharcnt == 0: #if - over 2 means this line is comment line
commentcnt = commentcnt +1
#print('find - ,commentcnt =',commentcnt)
elif commentcnt == 1 and char == '-' and validcharcnt == 1: #because - is also validchar
commentflag = 1
#print('注释行+1')
break
if char !='' and char != ' ' and char !='\n' and char != '\r' : #if this line is not empty and not comment line so it is validline
validcharcnt = validcharcnt +1
#print('validcharcnt + 1',validcharcnt)
if validcharcnt==0: # 1 line for complete and validchar still = 0 so this line is empty line
emptyline = emptyline +1
elif commentflag == 0:
validline = validline +1 # 1 line for complete and validchar > 0 so this line is valid line
else:
commentline = commentline + 1
#print('one line compelte ,now validcharcnt is',validcharcnt)
print('总行数为:',totalline)
print('有效行数为:',validline)
print('空行数为:',emptyline)
print('注释行为:',commentline)
# when file type is verilog
else :
BlockCommentFlag1 =0 # for /**/ and # if 0 #endif
for line in file.readlines():
totalline = totalline +1
commentcnt = 0
commentflag = 0
validcharcnt = 0
#print(line) #for debug
for char in line:
if char == '/' and validcharcnt == 0: # the first valid char is '/' #if / over 2 means this line is comment line
commentcnt = commentcnt +1
#print('find - ,commentcnt =',commentcnt)
elif commentcnt == 1 and char == '/' and validcharcnt == 1: #because / is also validchar //
commentflag = 1
#print('注释行+1')
break
elif commentcnt == 1 and char =='*' and validcharcnt == 1: # /* start
BlockCommentFlag1 = 1
break
if char =='*' and validcharcnt == 0: # the first valid char is '*'
commentcnt = commentcnt +1
elif commentcnt == 1 and char =='/' and validcharcnt == 1 : # */ complete
BlockCommentFlag1 = 0
commentline = commentline +1 # because this line is also comment line
break
if char !='' and char != ' ' and char !='\n' and char != '\r' : #if this line is not empty and not comment line so it is validline
validcharcnt = validcharcnt +1
#print('validcharcnt + 1',validcharcnt)
if validcharcnt==0: # 1 line check complete and validchar still = 0 so this line is empty line
emptyline = emptyline +1
elif commentflag == 0 and BlockCommentFlag1 == 0 :
validline = validline +1 # 1 line check complete and validchar != 0 and it isn't comment line, so this line is valid line
else:
commentline = commentline +1
#print('one line compelte ,now validcharcnt is',validcharcnt)
print('总行数为:',totalline)
print('有效行数为:',validline)
print('空行数为:',emptyline)
print('注释行为:',commentline)
# close file
#file.close()
str = input('push any key exit') |
f70c55e08d97b515181b42d4f80798bbf7118e0a | hadrizia/coding | /hackerrank-challenges/Warm-up Challenges/Counting Valleys.py | 387 | 3.515625 | 4 | # Complete the countingValleys function below.
'''
Time efficienty: O(n)
'''
def countingValleys(n, s):
count = 0
if n > 1:
alt = 0
for step in s:
if step == 'U':
alt += 1
if alt == 0:
count += 1
else:
alt -= 1
return count
n = 8
s = ["U", "D", "D", "D", "U", "D", "U", "U", "D", "D", "U", "U"]
print countingValleys(n, s) |
5e824e80b1fc165be33154f8d1c69028f5814e3c | hadrizia/coding | /code/advanced_algorithms_problems/list_2/resort.py | 1,415 | 3.78125 | 4 | '''
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Link: http://codeforces.com/problemset/problem/350/B
'''
def create_graph():
n = int(input())
input_types = input().split(" ")
types = [int(i) for i in input_types]
input_vertex = input().split(" ")
prev = [0 for i in range(n)]
cntFrom =[0 for i in range(n)]
for i in range(n):
prev[i] = int(input_vertex[i])
prev[i] -= 1
if (prev[i] != -1):
cntFrom[prev[i]] += 1
ans = []
for i in range(n):
if types[i] == 1:
curV = i
cur = []
while prev[curV] != -1 and cntFrom[prev[curV]] <= 1:
cur.append(curV)
curV = prev[curV]
cur.append(curV)
if len(ans) < len(cur):
ans = cur
ans_alt = [str(i + 1) for i in ans[::-1]]
print(len(ans_alt))
return(' '.join(ans_alt))
print(create_graph())
|
df3d3df41e0297e35e83104db05f588db460cc8b | hadrizia/coding | /hackerrank-challenges/Dictionaries and Hashmaps/Hash Tables: Ransom Note.py | 1,044 | 3.921875 | 4 | def addWordsToDict(arr):
availableDict = {}
for word in arr:
if word not in availableDict:
availableDict[word] = 1
else:
availableDict[word] = availableDict[word] + 1
return availableDict
'''
Given that
o = number of different words in note array
Time efficiency: O(m + n + o)
'''
def checkMagazine(magazine, note):
answer = 'Yes'
availableDictInMagazine = addWordsToDict(magazine)
noteDict = addWordsToDict(note)
for word in noteDict:
if word not in availableDictInMagazine or availableDictInMagazine[word] < noteDict[word]:
answer = 'No'
break
print answer
#magazine = ["give", "me", "one", "grand", "today", "night"]
#note = ["give", "one", "grand", "today"]
magazine = ["avtq", "ekpvq", "z", "rdvzf", "m", "zu", "bof", "pfkzl", "ekpvq", "pfkzl", "bof", "zu", "ekpvq", "ekpvq", "ekpvq", "ekpvq", "z"]
note = ["m", "z", "z", "avtq", "zu", "bof", "pfkzl", "pfkzl", "pfkzl", "rdvzf", "rdvzf", "avtq", "ekpvq", "rdvzf", "avtq"]
checkMagazine(magazine, note)
|
392277285a7b7a96b240f6fe2967ea8382bdc168 | hadrizia/coding | /code/data_structures/linkedlist/singly_linkedlist.py | 3,222 | 4.0625 | 4 | from code.data_structures.linkedlist.node import Node
class LinkedList(object):
def __init__(self, head = None):
self.head = head
def insert(self, data):
new_node = Node(data)
node = self.head
if self.size() == 0:
self.head = new_node
else:
while node.next:
node = node.next
node.next = new_node
def insertNode(self, new_node):
node = self.head
if self.size() == 0:
self.head = new_node
else:
while node.next:
node = node.next
node.next = new_node
def insertToHead(self, data):
new_node = Node(data)
if self.size() == 0:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
def search(self, data):
head = self.head
node = head
if node.data == data:
self.head = node.next
return head
else:
while node.next:
if node.next.data == data:
deleted_node = node.next
node.next = deleted_node.next
return deleted_node
node = node.next
raise ValueError("Data not in list")
def size(self):
node = self.head
count = 0
while node:
count += 1
node = node.next
return count
def delete(self, data):
head = self.head
node = head
if node.data == data:
self.head = node.next
return head
else:
while node.next:
if node.next.data == data:
previous = node
next = node.next
deleted_node = node.next
self.deleteByIndex(previous, next)
return deleted_node
node = node.next
raise ValueError("Data is not in list")
def deleteByIndex(self, previous, node):
if node.data == self.head.data:
self.head = node.next
else:
previous.next = node.next
def deleteHead(self):
if not self.size() == 0:
deleted_head = self.head
self.head = self.head.next
return deleted_head
# The next functions are related to questions from Cracking the Coding Interview
def countOccurences(self, data):
node = self.head
occurences = 0
while node:
if node.data == data:
occurences += 1
node = node.next
return occurences
def getKthToLast(self, k):
node = self.head
last = 0
# Get the index of last element
while node.next:
node = node.next
last += 1
# Kth to last
kth_to_last = last - k
# Search for kth_to_last
index = 0
node = self.head
while index != kth_to_last and node.next:
node = node.next
index += 1
if index == kth_to_last:
return node
raise ValueError("The Kth number does not exists!")
def prettify(self):
node = self.head
array = []
while node.next:
array.append((node.data, node.next.data))
node = node.next
array.append((node.data, node.next))
return array
def tail(self):
node = self.head
while node.next:
node = node.next
return node
def is_empty(self):
return self.size() == 0
def addAll(self, ll):
node = ll.head
while node.next:
self.insertNode(node)
node = node.next |
d4f790b54e2279548c4c00fa1fff63bfc578e2df | hadrizia/coding | /code/cracking-the-coding-interview/cap_1_strings_and_arrays/1.7.rotate-matrix.py | 1,309 | 3.625 | 4 | '''
Given a matrix NxN,
Time efficiency: O((N / 2) * N) = O(N^2)
Memory efficiency: O(1)
'''
def rotateMatrix(matrix):
n = len(matrix)
if n == 0:
return False
layers = n / 2
for layer in xrange(layers):
offset_begin = layer
offset_end = n - 1 - layer
for i in xrange(offset_begin, offset_end):
# temp variable to store top
temp = matrix[offset_begin][i]
# rotating left to top
matrix[offset_begin][i] = matrix[offset_end - i][offset_begin]
# rotating bottom to left
matrix[offset_end - i][offset_begin] = matrix[offset_end][offset_end - i]
# rotating right to bottom
matrix[offset_end][offset_end - i] = matrix[i][offset_end]
# rotating top to right
matrix[i][offset_end] = temp
return matrix
matrix_4x4 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
matrix_3x3 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
rotated_matrix_4x4 = [
[13, 9, 5, 1],
[14, 10, 6, 2],
[15, 7, 11, 3],
[16, 12, 8, 4]
]
rotated_matrix_3x3 = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
def tests():
assert rotateMatrix(matrix_3x3) == rotated_matrix_3x3
assert rotateMatrix(matrix_4x4) == rotated_matrix_4x4
assert rotateMatrix([[]]) == False
if __name__ == "__main__":
tests() |
f0ae1b82091f7d4a57ae39e8c2786ca7528db526 | hadrizia/coding | /code/data_structures/queue/queue.py | 571 | 4.0625 | 4 | from code.data_structures.linkedlist.node import Node
class Queue(object):
def __init__(self, head = None, tail = None):
self.head = head
self.tail = tail
def enqueue(self, value):
node = Node(value)
if self.is_empty():
self.head = node
self.tail = node
else:
n = self.head
while n.next:
n = n.next
n.next = node
self.tail = node
def dequeue(self):
if not self.is_empty():
n = self.head
self.head = self.head.next
return n
def is_empty(self):
return self.head == None |
fbb84944da05457e470013b116dc9bca78423a14 | hadrizia/coding | /code/advanced_algorithms_problems/list_2/laser_sculpture.py | 1,421 | 3.8125 | 4 | '''
Input
The input contains several test cases. Each test case is composed by two lines. The first line of a test case contains two integers A and C, separated by a blank space, indicating, respectively, the height (1 ≤ A ≤ 104) and the length (1 ≤ C ≤ 104) of the block to be sculpted, in milimeters. The second line contains C integers Xi, each one indicating the final height, in milimeters of the block between the positions i and i + 1 through the length (0 ≤ Xi ≤ A, for 0 ≤ i ≤ C - 1). Consider that on each step, a layer of width 1 mm is removed on the parts of the block where the laser is turned on.
The end of the input is indicated by a line that contains only two zeros, separated by a blank space.
Output
For each test case, your program must print a single line, containing an integer, indicating the number of times that the laser must be turned on to sculpt the block in the indicated format.
Link: https://www.urionlinejudge.com.br/judge/en/problems/view/1107
'''
def laser_sculpture():
raw_input = input()
while raw_input != "0 0":
h = int(raw_input.split(" ")[0])
l = int(raw_input.split(" ")[1])
last_block = h
moves = 0
blocks = [int(x) for x in input().split(" ")]
for b in blocks:
if last_block > b:
moves += (h - b) - (h - last_block)
last_block = b
print(moves)
raw_input = input()
laser_sculpture() |
cd9996229b3da37855c54db0bbfd8d404c2c0479 | hadrizia/coding | /code/cracking-the-coding-interview/cap_3_stacks_and_queues/3.3.stack_of_plates.py | 1,949 | 3.75 | 4 | from code.data_structures.stack.stack import Stack
from code.data_structures.linkedlist.node import Node
class SetOfStacks(object):
def __init__(self, stacks = [], capacity_of_stacks = 0):
self.stacks = stacks
self.capacity_of_stacks = capacity_of_stacks
def is_empty(self):
return len(self.stacks) == 0
def add_new_stack_to_set(self, value):
stack = Stack()
stack.push(value)
self.stacks.append(stack)
def push(self, value):
if self.is_empty():
self.add_new_stack_to_set(value)
else:
last_stack = self.stacks[-1]
if last_stack.size() < self.capacity_of_stacks:
last_stack.push(value)
else:
self.add_new_stack_to_set(value)
def pop(self):
if not self.is_empty():
last_stack = self.stacks[-1]
deleted_node = last_stack.pop()
if last_stack.is_empty():
self.stacks.remove(last_stack)
return deleted_node
def pop_at(self, index):
indexed_stack = self.stacks[index]
if indexed_stack != None:
deleted_node = indexed_stack.pop()
if indexed_stack.size() == self.capacity_of_stacks - 1:
for i in range(index, len(self.stacks) - 1):
self.stacks[i].push(self.stacks[i + 1].remove_bottom().data)
if self.stacks[i + 1].is_empty():
self.stacks.remove(self.stacks[i + 1])
break
return deleted_node
def tests():
set_of_stacks = SetOfStacks(capacity_of_stacks = 2)
set_of_stacks.push(1)
set_of_stacks.push(2)
set_of_stacks.push(3)
assert len(set_of_stacks.stacks) == 2
set_of_stacks.pop()
assert len(set_of_stacks.stacks) == 1
set_of_stacks.push(3)
set_of_stacks.push(4)
set_of_stacks.push(5)
assert len(set_of_stacks.stacks) == 3
set_of_stacks.pop_at(0)
assert len(set_of_stacks.stacks) == 2
assert set_of_stacks.stacks[0].top.data == 3
assert set_of_stacks.stacks[1].top.data == 5
if __name__ == "__main__":
tests() |
f3974732df9e9a3124cdffb22f7664f3e35892c1 | hadrizia/coding | /code/data_structures/heap/heap.py | 881 | 3.90625 | 4 | class Heap(object):
def __init__(self, heap=[]):
self.heap = heap
def heapify(self, i, n):
biggest = i
left = i * 2 + 1
right = i * 2 + 2
if left < n and self.heap[left] > self.heap[i]:
biggest = left
if right < n and self.heap[right] > self.heap[biggest]:
biggest = right
if biggest != i:
self.heap[biggest], self.heap[i] = self.heap[i], self.heap[biggest]
self.heapify(biggest, n)
else:
return
def build_heap(self):
n = len(self.heap)
for i in range(len(h.heap) // 2 - 1, -1, -1):
h.heapify(i, n)
def heapsort(self):
self.build_heap()
n = len(self.heap)
for i in range(n - 1, 0, -1):
self.heap[i], self.heap[0] = self.heap[0], self.heap[i]
self.heapify(0, i)
h = Heap([4, 6, 2, 3, 1, 9])
h.build_heap()
h.heapsort()
assert h.heap == [1, 2, 3, 4, 6, 9]
|
32235f471cbf55cbe6a643306112c62f66dd756e | hadrizia/coding | /code/advanced_algorithms_problems/list_2/where_are_my_keys.py | 1,210 | 3.890625 | 4 | '''
Input
The first line contains two integers Q(1 ≤ Q ≤ 1*103) and E(1 ≤ E ≤ Q) representing respectively the number of offices that he was in the last week and the number of offices that he was in the last two days.
The second line contains E integers Si (1 ≤ Si ≤ 1000) containing the Identification number of each office that he was in the last two days.
The next line contains Q integers Ci (1 ≤ Ci ≤ 1000) containing the identification number of each one of the offices that he was in the last week.
Output
For each office that he was in the last week your program should return “0” in case he has already visited that office while looking for the keys. Else your program should return “1” in case he hasn't visited that office yet while he was looking for the keys.
Link: https://www.urionlinejudge.com.br/judge/pt/problems/view/1800
'''
def was_room_visited():
total_offices = int(input().split(" ")[0])
visited_offices = [int(x) for x in input().split(" ")]
for _ in range(total_offices):
office = int(input())
if office not in visited_offices:
print(1)
visited_offices.append(office)
else:
print(0)
was_room_visited() |
4df464f1545fa3165344654a596eeedf5d78444d | hadrizia/coding | /code/cracking-the-coding-interview/cap_1_strings_and_arrays/1.6.string-compression.py | 647 | 3.875 | 4 | '''
Given that:
N = len(string),
Time efficiency: O(n)
Memory efficiency: O(n)
'''
def stringCompression(string):
occurrences = 0
compressedString = ''
for i in range(len(string)):
occurrences += 1
if (i + 1 >= len(string)) or string[i] != string[i + 1]:
compressedString += string[i] + str(occurrences)
occurrences = 0
return compressedString if len(compressedString) < len(string) else string
def tests():
assert stringCompression('aaaabbbbcccc') == 'a4b4c4'
assert stringCompression('abcde') == 'abcde'
assert stringCompression('aaaabbbbccccAA') == 'a4b4c4A2'
if __name__ == "__main__":
tests() |
2bbb704056da71a4f0e76263de4cf58ff9522979 | hadrizia/coding | /code/cracking-the-coding-interview/cap_2_linked_lists/2.1.remove_dups.py | 757 | 3.578125 | 4 | from code.data_structures.linkedlist.singly_linkedlist import LinkedList
'''
Given that N = linked_list.size(),
Time efficiency: O(N)
'''
def removeDups(linked_list):
node = linked_list.head
buffer = []
buffer.append(node)
while node:
if node.data not in buffer:
buffer.append(node.data)
else:
linked_list.delete(node.data)
node = node.next
return linked_list
def removeDupsWithoutBuffer(linked_list):
node = linked_list.head
if(linked_list.countOccurences(node.data) > 1):
linked_list.deleteByIndex(None, node)
while node.next:
count = linked_list.countOccurences(node.next.data)
if count > 1:
linked_list.deleteByIndex(node, node.next)
node = node.next
return linked_list
c |
9dfd3b48523e12e4bafac6630a48024e03c3bff8 | czarny25/pythonStudy | /PythonFundamentals/testingFolder/testnumpy.py | 270 | 3.859375 | 4 | '''
Created on 14 Apr 2020
@author: Marty
'''
import numpy as np # numpy is external library and need to be imported
# simple list
list = [1,2,3,4,5,6,7]
# variable of numpy array type take list as argument
x = np.array(list)
print(type(x))
print(x) |
723b4825326e39a7c363ea10bab1c4c634945e7a | Flipez/snippets | /python/list_dir.py | 784 | 3.8125 | 4 | #!/usr/bin/env python
import os, sys, sqlite3
def get_dirs(dir):
path = dir
dir_list = os.listdir( path )
return( dir_list )
print("This will list the dirs and save them to a sqlite database")
print("Please enter a valid path")
dir_list = get_dirs(input())
if os.path.exists("db.db"):
print("[db]database exists")
sys.exit
connection = sqlite3.connect("db.db")
cursor = connection.cursor()
sql = "CREATE TABLE dirs(" \
"name TEXT, " \
"number INTEGER PRIMARY KEY)"
cursor.execute(sql)
count = 0
for file in dir_list:
cursor.execute("INSERT INTO dirs (name, number) values (?,?)", (file, count))
count = count + 1
connection.commit()
connection.close
#fobj = open("db.txt", "w")
#for file in dir_list:
# fobj.write(file)
#fobj.close()
|
846cc6cd0915328b64f83d50883167e0d0910f6a | Teju-28/321810304018-Python-assignment-4 | /321810304018-Python assignment 4.py | 1,839 | 4.46875 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## 1.Write a python function to find max of three numbers.
# In[5]:
def max():
a=int(input("Enter num1:"))
b=int(input("Enter num2:"))
c=int(input("Enter num3:"))
if a==b==c:
print("All are equal.No maximum number")
elif (a>b and a>c):
print("Maximum number is:",a)
elif (b>c and b>a):
print("Maximum number is:",b)
else:
print("Maximum number is:",c)
max()
# ## 2.Write a python program to reverse a string.
# In[6]:
def reverse_string():
A=str(input("Enter the string:"))
return A[::-1]
reverse_string()
# ## 3.write a python function to check whether the number is prime or not.
# In[13]:
def prime():
num=int(input("Enter any number:"))
if num>1:
for i in range(2,num):
if (num%i==0):
print(num ,"is not a prime number")
break
else:
print(num ,"is a prime number")
else:
print(num ,"is not a prime number")
prime()
# ## 4.Use try,except,else and finally block to check whether the number is palindrome or not.
# In[25]:
def palindrome():
try:
num=int(input("Enter a number"))
except Exception as ValueError:
print("Invalid input enter a integer")
else:
temp=num
rev=0
while(num>0):
dig=num%10
rev=rev*10+dig
num=num//10
if(temp==rev):
print("The number is palindrome")
else:
print("Not a palindrome")
finally:
print("program executed")
palindrome()
# ## 5.Write a python function to find sum of squares of first n natural numbers
# In[27]:
def sum_of_squares():
n=int(input("Enter the number"))
return (n*(n+1)*(2*n+1))/6
sum_of_squares()
|
f65750847bc5cd37f7e53a50469f2db9498f84b4 | Ivan395/Python | /rfc.py | 961 | 3.859375 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
import curp
def letters(ap):
letras = [chr(x) for x in range(65, 91)] + [chr(x) for x in range(97, 123)]
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
if(len(ap) == 13):
if(ap[0] in letras and ap[1] in letras and ap[2] in letras and ap[3] in letras):
if(ap[4] in numbers and ap[5] in numbers and ap[6] in numbers and ap[7] in numbers and ap[8] in numbers and ap[9] in numbers):
st = str('19' + ap[4:6] + '/' + ap[6:8] + '/' + ap[8: 10]).split('/')
if(ap[10] in numbers or ap[10] in letras and ap[11] in numbers or ap[11] in letras and ap[12] in numbers or ap[12] in letras):
return curp.dtval(st)
return False
def run():
tmp_rfc = input("Ingresa el RFC: ")
if(letters(tmp_rfc)):
print('El RFC es correcto')
else:
print('El RFC NO es correcto')
if __name__ == '__main__':
run()
|
adb2991ea7cc9e8c3a2c35d1698dee8949e84497 | NereBM/Python-Pandas | /Working with datasets.py | 4,483 | 4.1875 | 4 | import pandas as pd
########--------------------5:Concatenating and Appending dataframes------------
df1 = pd.DataFrame({'HPI':[80,85,88,85],
'Int_rate':[2, 3, 2, 2],
'US_GDP_Thousands':[50, 55, 65, 55]},
index = [2001, 2002, 2003, 2004])
df2 = pd.DataFrame({'HPI':[80,85,88,85],
'Int_rate':[2, 3, 2, 2],
'US_GDP_Thousands':[50, 55, 65, 55]},
index = [2005, 2006, 2007, 2008])
df3 = pd.DataFrame({'HPI':[80,85,88,85],
'Int_rate':[2, 3, 2, 2],
'Low_tier_HPI':[50, 52, 50, 53]},
index = [2001, 2002, 2003, 2004])
#simple concatenation, as df1 and df2 have same columns and different indexes
concat = pd.concat([df1,df2])
print(concat)
#here we have missing values
concat = pd.concat([df1,df2,df3])
print(concat)
#we use append to add at the end
df4 = df1.append(df2)
print(df4)
#BUT THIS HAPPENS IF WE APPEND DATA WITH THE SAME INDEX
df4 = df1.append(df3)
print(df4)
#It is important here to introduce the concept of "Series".A series is basically a single-columned dataframe.
#A series does have an index, but, if you convert it to a list, it will be just those values.
#Whenever we say something like df['column'], the return is a series.
s = pd.Series([80,2,50], index=['HPI','Int_rate','US_GDP_Thousands'])
df4 = df1.append(s, ignore_index=True)
print(df1)
print(df4)
#We have to ignore the index when appending a series, because that is the law, unless the series has a name.
#############--------------6:Joining and Merging Dataframes--------------------------
df1 = pd.DataFrame({'HPI':[80,85,88,85],
'Int_rate':[2, 3, 2, 2],
'US_GDP_Thousands':[50, 55, 65, 55]},
index = [2001, 2002, 2003, 2004])
df2 = pd.DataFrame({'HPI':[80,85,88,85],
'Int_rate':[2, 3, 2, 2],
'US_GDP_Thousands':[50, 55, 65, 55]},
index = [2005, 2006, 2007, 2008])
df3 = pd.DataFrame({'HPI':[80,85,88,85],
'Unemployment':[7, 8, 9, 6],
'Low_tier_HPI':[50, 52, 50, 53]},
index = [2001, 2002, 2003, 2004])
#Here we merge by HPI
print(pd.merge(df1,df3, on='HPI'))
#We can also merge by several columns
print(pd.merge(df1,df2, on=['HPI','Int_rate']))
#Pandas is a great module to marry to a database like mysql? here's why
df4 = pd.merge(df1,df3, on='HPI')
df4.set_index('HPI', inplace=True)
print(df4)
#Now, what if HPI was already the index?
# Or, in our case, We'll probably be joining on the dates,
# but the dates might be the index. In this case, we'd probably use join.
df1.set_index('HPI', inplace=True)
df3.set_index('HPI', inplace=True)
print(df1)
print(df3)
joined = df1.join(df3)
print(joined)
#What happens if we have slightly different indexes?
df1 = pd.DataFrame({
'Int_rate':[2, 3, 2, 2],
'US_GDP_Thousands':[50, 55, 65, 55],
'Year':[2001, 2002, 2003, 2004]
})
df3 = pd.DataFrame({
'Unemployment':[7, 8, 9, 6],
'Low_tier_HPI':[50, 52, 50, 53],
'Year':[2001, 2003, 2004, 2005]})
merged = pd.merge(df1,df3, on='Year')
print(merged)
merged = pd.merge(df1,df3, on='Year')
merged.set_index('Year', inplace=True)
print(merged)
#The parameters that ar not common are missing, how do we solve this? With the "how" parameter of merge:
#Left - equal to left outer join SQL - use keys from left frame only
#Right - right outer join from SQL- use keys from right frame only.
#Outer - full outer join - use union of keys
#Inner - use only intersection of keys.
merged = pd.merge(df1,df3, on='Year', how='left')
merged.set_index('Year', inplace=True)
print(merged)
#Merging on the left is literally on the left dataframe. We had df1, df3,
# the one on the left is the first one, df1. So, we wound up with an index
# that was identical to the left dataframe (df1).
merged = pd.merge(df1,df3, on='Year', how='outer')
merged.set_index('Year', inplace=True)
print(merged)
#With the "outer" all the indexes are shown
#Finally, "inner" is the intersection of keys, basically just what is shared between all the sets.(It is the defautl option)
#we an do the same with join:
df1.set_index('Year', inplace=True)
df3.set_index('Year', inplace=True)
joined = df1.join(df3, how="outer")
print(joined) |
a843bf881c50bb3f0dda17c4da2dca48d410fce4 | Jorgelsl/batchroja | /listas.py | 416 | 3.984375 | 4 | list1 = [2,3,1,4,5]
list2 = ["A","B","C","D"]
list3 = ["MATEMATICAS", "HISTORIA", 1999, 1992]
list4 = [list1, list2, list3]
'''
print(list1)
print(list2)
print(list3)
print(list4)
for i in list3:
print(i)
'''
frutas = ['naranja', 'manzana', 'pera', 'fresa', 'banana', 'manzana', 'kiwi']
print(frutas)
frutas.append('uva')
print(frutas)
frutas.extend(list2)
print(frutas)
frutas.insert(0,'melon')
print(frutas) |
186d9dcc93bb4b20c9f79a3460f00b2e2e0f0728 | sanjaylokula/100dayspython | /days/month/day8_23.py | 890 | 3.984375 | 4 | #Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
#Example:
#Input: [1,2,1,3,2,5]
#Output: [3,5]
#Note:
#The order of the result is not important. So in the above example, [5, 3] is also correct.
#Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
output_dict = dict()
for i in nums:
if i not in output_dict:
output_dict[i] = 1
else:
output_dict[i] += 1
return [key for key, value in output_dict.items() if value == 1]
if __name__=="__main__":
output=Solution().singleNumber([1,2,3,4,2,1,2])
print(output) |
b973afe64648468eb6bb9e8a83b8cfdba2e4c8b9 | CBASoftwareDevolopment2020/Exam-Notes | /Algorithms/Implementations/sorting.py | 3,607 | 3.53125 | 4 | from time import time
from random import choice, randint, shuffle
def selection_sort(arr, timeout=60):
n = len(arr)
if 0 <= n <= 1:
return
start = time()
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
if time() - start > timeout:
raise TimeoutError(f'Sorting took longer than {timeout} seconds')
def insertion_sort(arr, timeout=60):
n = len(arr)
if 0 <= n <= 1:
return
start = time()
for i in range(1, n):
for j in range(i, 0, -1):
if arr[j] < arr[j - 1]:
arr[j], arr[j - 1] = arr[j - 1], arr[j]
if time() - start > timeout:
raise TimeoutError(f'Sorting took longer than {timeout} seconds')
def merge_sort(arr):
def merge(l, r):
new = []
left_idx = right_idx = data_idx = 0
left_len, right_len = len(l), len(r)
while left_idx < left_len and right_idx < right_len:
if l[left_idx] < right[right_idx]:
new.append(l[left_idx])
left_idx += 1
else:
new.append(r[right_idx])
right_idx += 1
data_idx += 1
while left_idx < left_len:
new.append(l[left_idx])
left_idx += 1
data_idx += 1
while right_idx < right_len:
new.append(r[right_idx])
right_idx += 1
data_idx += 1
return new
data = arr[:]
n = len(data)
if n < 2:
return data
mid = len(data) // 2
left = merge_sort(data[:mid])
right = merge_sort(data[mid:])
data = merge(left, right)
return data
def quick_sort(items):
arr = items.copy()
n = len(arr)
if 0 <= n <= 1:
return arr
shuffle(arr)
# if the sub array has 15 items or less use insertion sort
if n <= 15:
insertion_sort(arr)
return arr
else:
idx = randint(0, n - 1)
arr[0], arr[idx] = arr[idx], arr[0]
pivot = arr[0]
less = []
greater = []
for x in arr[1:]:
if x < pivot:
less.append(x)
else:
greater.append(x)
return quick_sort(less) + [pivot] + quick_sort(greater)
def quick_sort_3way(items):
arr = items.copy()
n = len(arr)
if 0 <= n <= 1:
return arr
shuffle(arr)
# if the sub array has 15 items or less use insertion sort
if n <= 15:
insertion_sort(arr)
return arr
else:
pivot = choice(arr)
less = []
equal = []
greater = []
for x in arr:
if x < pivot:
less.append(x)
elif x == pivot:
equal.append(x)
else:
greater.append(x)
return quick_sort_3way(less) + equal + quick_sort_3way(greater)
def heapify(data, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and data[left] > data[largest]:
largest = left
if right < n and data[right] > data[largest]:
largest = right
if largest != i:
data[i], data[largest] = data[largest], data[i]
heapify(data, n, largest)
def heap_sort(arr):
n = len(arr)
if n < 2:
return arr
for i in range(n, -1, -1):
heapify(arr, n, i)
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
return arr
|
22b5a162408555fa5aea974ebafc6dbd56ea8f18 | BercziSandor/pythonCourse_2020_09 | /DataTransfer/json_1.py | 1,153 | 4.21875 | 4 | # https://www.w3schools.com/python/python_json.asp
# https://www.youtube.com/watch?v=9N6a-VLBa2I Python Tutorial: Working with JSON Data using the json Module (Corey Schaefer)
# https://lornajane.net/posts/2013/pretty-printing-json-with-pythons-json-tool
# http://jsoneditoronline.org/ JSON online editor
###################
# JSON: JavaScript Object Notation. Adatcseréhez, konfigurációs fájlokhoz használják,
# a legtöbb nyelvben van illesztő egység hozzá.
# loads: Sztringből beolvasás.
import json
str_1 = '{"name": "John", "age":30.5, "cities": ["New York", "Budapest"]}'
x = json.loads(str_1)
print(x) # {'name':'John', 'age':30.5, 'cities': ['New York', 'Budapest']}
# A sztringeknél idézőjelet kell használni, aposztrofot nem fogad el.
str_1 = '{'name': "John"}'
x = json.loads(str_1) # SyntaxError
# A dict kulcsoknak sztringeknek kell lenniük.
# tuple-t, set-et nem ismer.
###################
# dumps: sztringbe írás.
import json
lst_1 = ['John', 30.5, ['New York', 'Budapest']]
str_1 = json.dumps(lst_1)
print(str_1, type(str_1)) # ["John", 30.5, ["New York", "Budapest"]] <class 'str'>
###################
|
efca8c666dfa01890679fb36817da3abc2a8c586 | BercziSandor/pythonCourse_2020_09 | /Lecture_11/mix_11.py | 350 | 3.953125 | 4 | # Else ág ciklusoknál: akkor megy rá a vezérlés, ha nem volt break
for i in range(5):
print(i)
else:
print('végigment a for ciklus')
for i in range(5):
print(i)
if i == 3:
break
else:
print('no break')
# Üres ciklusnál is működik:
for i in range(5,0):
print(i)
else:
print('végigment a for ciklus')
|
0fd245e6318b5016856b46828f1e397779bf3da6 | BercziSandor/pythonCourse_2020_09 | /Lecture_3/break_continue_1.py | 365 | 3.9375 | 4 | # Kilépés while és for ciklusból: break utasítás
lst = [1, 2, 3, 4, 5, 6]
for e in lst:
if e > 2:
break
print(e)
# 10
# 20
# while ciklusban ugyanígy működik.
lst = [1, 2, 3, 4, 5, 6]
# Ciklus folytatása:
for e in lst:
if e % 3 == 0:
continue
print(e)
# 1
# 2
# 4
# 5
|
62b18cc42a6e7a4bbca94ed532807160b5e56cdc | BercziSandor/pythonCourse_2020_09 | /Num_py/numpy_8.py | 2,047 | 4.09375 | 4 | # Fancy indexing
# Egyes szerzőknél a boolean indexelés (maszkolás) is ezen címszó alá tartozik.
# Én csak az integer listával való indexelést hívom így.
# http://scipy-lectures.org/intro/numpy/array_object.html#fancy-indexing
# https://medium.com/better-programming/numpy-illustrated-the-visual-guide-to-numpy-3b1d4976de1d
# http://jalammar.github.io/visual-numpy/
# Fancy indexing: tetszőleges indexeket összegyűjtök egy listába és ezzel indexelem a tömböt.
# Ellentétben a slicing-gal itt nem kell semmilyen szabályosságnak fennállnia.
import numpy as np
arr_1 = np.array([10, 20, 30, 40, 50])
arr_2 = arr_1[[1, 2, 4]]
print(arr_2) # [20 30 50]
# Ezt helyettesíti:
arr_2 = np.array([arr_1[1], arr_1[2], arr_1[4]])
# Az indexet sokszor egy változóba tesszük:
ix = [1, 2, 4]
arr_2 = arr_1[ix]
print(arr_2) # [20 30 50]
#############################
# Két dimenziós tömböknél persze külön indexelhetjük a sorokat és az oszlopokat:
arr_1 = np.array([
[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]
])
row = np.array([0, 1, 2])
col = np.array([2, 1, 3])
arr_2 = arr_1[row, col]
print(arr_2) # [2, 5, 11]
#############################
# A keletkező tömb másolat, NEM referencia (view).
arr_1 = np.array([10, 20, 30, 40, 50])
arr_2 = arr_1[[1, 2, 4]]
print(arr_2) # [20 30 50]
arr_2[0] = 99
print(arr_2) # [99 30 50]
print(arr_1) # [10 20 30 40 50] -- nem változott
# ****** Amikor egy adatszerkezetet előállítunk egy másikból, MINDIG vizsgáljuk
# ****** meg, hogy másolat (copy) keletkezett-e, vagy referencia (view).
#############################
# Viszont a fancy indexeléssel kiválasztott elemeket módosítani is tudjuk.
arr_1 = np.array([10, 20, 30, 40, 50])
ix = [1, 2, 4]
arr_1[ix] = 99
print(arr_1) # [10 99 99 40 99]
# Nem csak egyetlen értékkel írhatjuk fölül a tömb elemeit, a broadcast itt is működik:
arr_1 = np.array([10, 20, 30, 40, 50])
ix = [1, 2, 4]
arr_1[ix] = [97, 98, 99]
print(arr_1) # [10 97 98 40 99]
#############################
|
bbd8632e442e9f7ab0812a7a1942e157ecdfc26b | BercziSandor/pythonCourse_2020_09 | /Lecture_2/tippmix_2.py | 1,719 | 3.703125 | 4 | # Mi lesz a kimenet? Lehet hibajelzés is.
# NE futtassuk le, mielőtt tippelnénk!
# Órán a szabályok:
# Amikor valaki úgy gondolja, hogy van ötlete a megoldásra, akkor bemondja, hogy: VAN TIPP!
# Amikor azt mondom, hogy "Kérem a tippeket" és valaki egy kicsit még gondolkodni szeretne, akkor bemondja, hogy: IDŐT KÉREK!
# Egyébként pedig nyilván sorra mindenki bemondja, hogy mit gondolt ki.
###########################################################
# 1.
def f(x, y, z):
print(x, y, z)
f(z=30, y=20, x=10)
###################
# 2.)
def f(x, y, z):
print(x, y, z)
f(z=30, y=20, 10)
###################
# 3.)
lst = [3, (10, 20, 30),['A', 'B']]
print(lst[1][2])
print(lst[1],[2])
###################
# 4.)
lst = [3, (10, 20, 30),['A', 'B']]
print(len(lst[2][1]))
print(len(lst[1][2]))
###################
# 5.)
def f(x, y, z):
print(x, y, z)
f(10, y=20, z=30)
###################
# 6.)
dic = {'a': 10, 'b': 20}
print(dic['B'])
###################
# 7.)
for i in range(1,2):
print(10*i)
###################
# 8.)
def f(*, x, y, z):
print(x, y, z)
f(10, y=20, z=30))
###################
# 9.)
x = 100
X = 10
print(x + X)
###################
# 10.)
for x in range(3, 1, -2):
print(x)
###################
# 11.)
def f(x, y, z):
print(x, y, z)
f(30, y=20, x=10)
###################
# 12.)
r = range(1, 4)
for x in r:
print(x, end=' ')
print()
###################
# 13.)
def func(param):
return y + param
y = 'abc'
print(func('xxx'))
y = [10, 20, 30]
print(func([99]))
y = (100)
print(func((5, 4, 3)))
###################
# 14.)
def func(param):
y += 100
return y + param
y = 30
print(func(1))
################### |
e26bfd8720509b619de1ce671ea3ca273f606b9a | BercziSandor/pythonCourse_2020_09 | /Lecture_8/solutions_7.py | 2,668 | 3.515625 | 4 | # Lecture_7\exercises_7.py megoldásai
# 1.)
# A dict-té alakítás felesleges, ráadásul 3.7-es verzió előtt hibás is lehet az eredmény,
# mert a dict-ből kiolvasásnál nincs definiálva a sorrend.
names_reversed = [ e[0] for e in sorted(employees, key=lambda x: x[0], reverse=True)]
print(names_reversed) # ["Zach","James", "Cecilia", "Ann"]
####################################
# 2.)
# A.
# Ha az lst-ben vannak többször előforduló elemek, ezek a kimeneten csak egyszer
# fognak szerepelni:
lst = [10, 11, 5, 6, 7, 4, 6] # 6 kétszer van
tup = (10, 11, 7, 4)
# [25, 36]
# B.
res = [e*e for e in lst if e not in tup]
# [25, 36, 36]
####################################
# 3.)
lines = ['AA BB CC', 'AA EE FF', 'GG HH II']
s_list = ('AA', 'EE', 'XX')
result = find_any(lines, s_list)
print(result) # ['AA BB CC', 'AA EE FF', 'AA EE FF']
# Ha több keresett sztring is előfordul egy sorban, akkor az a sor többször meg
# fog jelenni a kimeneten.
# B.
def find_any(lines, search_list):
out_lst = []
for line in lines:
for searched in search_list:
if searched in line:
out_lst. append(line)
break # ez hiányzott
return out_lst
####################################
# 4.)
def find_all(lines, search_list):
out_lst = []
for line in lines:
do_it = True
for searched in search_list:
if searched not in line:
do_it = False
break
if do_it:
out_lst.append(line)
return out_lst
lines = ['AA BB CC', 'AA EE FF', 'GG HH II']
s_list = ('AA', 'EE')
result = find_all(lines, s_list)
print(result)
####################################
# 5.)
def merge_func(series_1, series_2):
x_1 = None; x_2 = None
it_1 = iter(series_1)
it_2 = iter(series_2)
while True:
try:
if x_1 is None:
x_1 = next(it_1)
except StopIteration:
x_1 = None
try:
if x_2 is None:
x_2 = next(it_2)
except StopIteration:
x_2 = None
if x_1 is None and x_2 is None:
return
if x_2 is None:
yield x_1
x_1 = None
continue
if x_1 is None:
yield x_2
x_2 = None
continue
if x_1 <= x_2:
yield x_1
x_1 = None
else:
yield x_2
x_2 = None
lst_1 = [10, 20, 30, 40, 40]
lst_2 = [15, 25, 25, 50]
lst = [x for x in merge_func(lst_1, lst_2)]
print(lst) # [10, 15, 20, 25, 25, 30, 40, 40, 50]
####################################
|
3d72b228e7f5806f8d20bd160fe166ad496f39bc | BercziSandor/pythonCourse_2020_09 | /Lecture_13/exercises_13.py | 772 | 3.78125 | 4 | # 1.)
# Lecture_12\exercises_12.py 3. feladathoz térünk vissza, módosítjuk egy kicsit.
# Írjunk generátor-függvénnyel megvalósított iterátort, amely inicializáláskor egy
# iterálható obkektumot és egy egész számot kap paraméterként. Azokat az elemeket
# adja vissza a számmal elosztva a bemeneti objektum által szolgáltatott sorozatból,
# amelyek oszthatóak a számmal. A bemeneti sorozat lehet inhomogén; amely elemeken nem
# végezhető el a modulo művelet, azokat az iterátor adja ki változatlanul a kimenetre.
def modIterFunc_2(inputSeries, number):
pass
m = modIterFunc_2([1, 'A', [10, 20], 66, 8, 12, (24, 36)], 6)
for e in m:
print(e)
# 'A'
# [10, 20]
# 11.0
# 2.0
# (24, 36)
############################################
|
f81b9e4fdf5b0d1dc28194beb061bd140d6996b9 | BercziSandor/pythonCourse_2020_09 | /Functions/scope_2.py | 2,977 | 4.21875 | 4 | # Változók hatásköre 2.
# Egymásba ágyazott, belső függvények
# global kontra nonlocal
# https://realpython.com/inner-functions-what-are-they-good-for/
# Függvényen belül is lehet definiálni függvényt. Ezt sok hasznos dologra fogjuk tudni használni.
# Első előny: információrejtés. Ha a belső függvény csak segédművelet, amit kívül nem
# használunk, akkor jobb, ha a függvényen kívül nem is látszik.
# A változót belülről kifelé haladva keresi a futtató rendszer.
def func():
def inner():
x = 'x inner' # x itt definiálódott
print(x)
x = 'x func local'
inner()
x = 'x global'
func() # x inner
######################################
def func():
def inner():
print(x)
x = 'x func local'
inner()
x = 'x global'
func() # x func local
######################################
def func():
def inner():
print(x)
inner()
x = 'x global'
func() # x global
######################################
def func():
def inner():
print(x) # itt használom
x = 'x inner' # de csak itt definiálom
inner()
x = 'x global'
func() # hiba, először használom, aztán definiálom
######################################
def func():
def inner():
global x
print(x)
x = 'x inner'
inner()
x = 'x global'
func() # x global
print('x func() után:', x) # x func() után: x inner
######################################
# A global-nak deklarált változókat a tartalmazó függvényben NEM keresi.
def func():
def inner():
global x
print(x)
x = 'x func local' # nem ezt találja meg
inner()
x = 'x global'
func() # x global
######################################
# A nonlocal-nak deklarált változókat a legkülső függvényen kívül (modul szinten) nem keresi.
# Ez rendben van:
def func():
def inner():
nonlocal x
print(x)
x = 'x func local'
inner()
x = 'x global'
func() # x func local
# De ez nem működik:
def func():
def inner():
nonlocal x
print(x) # itt használná
inner()
x = 'x global'
func() # hiba
# x hiába van modul-szinten definiálva, ott már nem keresi.
# Ez sem működik:
def func():
def inner():
nonlocal x
print(x) # itt használná
inner()
x = 'x func local' # de csak itt definiálódik
x = 'x global'
func() # hiba
# A felhasználáskor még nem volt definiálva x.
######################################
# A belső függvény a tartalmazó függvénynek a bemenő paramétereit is látja.
def func(outerParam):
def inner():
print('inner:',outerParam)
inner()
x = 'x global'
func('func parameter') # func parameter
# Ezt sok helyen fogjuk használni.
##################
|
e7fa14ad1683f757c0af7cb0b591d2e67a9b53df | BercziSandor/pythonCourse_2020_09 | /Datastructures/index_2.py | 2,457 | 3.921875 | 4 | # Értékadás slicing segítségével.
lst = [10, 20, 30, 40, 50]
# Az 1, 2, 3 indexű elemeket le akarjuk cserélni erre: [-2, -3, -4]
lst[1:4] = [-2, -3, -4]
print(lst) # [10, -2, -3, -4, 50]
#######################################
# Ha slicing segítségével végzünk értékadást, akkor az új elemnek egy iterálható
# sorozatnak kell lennie, amelynek az elemei kerülnek be. Ez tehát NEM működik:
lst = [10, 20, 30, 40, 50]
lst[1:4] = 99 # TypeError: can assign only an iterable
#######################################
# Az új sorozat lehet más elemszámú, mint az eredeti:
lst = [10, 20, 30, 40, 50]
lst[1:4] = [-100]
print(lst) # [10, -100, 50]
# A felső határ túlcímzése most sem okoz gondot:
lst = [10, 20, 30, 40, 50]
lst[1:100] = [-2, -3, -4]
print(lst) # [10, -2, -3, -4]
# Ha a kezdő index túl van a lista végén, akkor az elemek hozzáfűződnek a lista végéhez:
lst = [10, 20, 30, 40, 50]
lst[10:100] = [-2, -3, -4]
print(lst) # [10, 20, 30, 40, 50, -2, -3, -4]
# Ha a kezdő index túl van a lista elején, akkor az elemek hozzáfűződnek a lista
# eleje elé:
lst = [10, 20, 30, 40, 50]
lst[-6:1] = [-2, -3, -4]
print(lst) # [-2, -3, -4, 10, 20, 30, 40, 50]
#######################################
# Nyilván egyetlen elemet is le lehet cserélni:
lst = [10, 20, 30, 40, 50]
lst[1:1] = [99, 100]
print(lst) # [10, 99, 100, 30, 40, 50]
#######################################
# A lista helyben marad megváltozott tartalommal:
lst_1 = [10, 20, 30, 40, 50]
lst_2 = lst_1
lst_1[1:1] = [99, 100]
print(lst_2) # [10, 99, 100, 30, 40, 50]
# Így tudunk tehát helyben új listát létrehozni:
lst_1 = [10, 20, 30, 40, 50]
lst_2 = lst_1
lst_1[:] = [99, 100]
print(lst_2) # [99, 100]
#######################################
# A beillesztendő értéksorozat persze nem csak lista, hanem tetszőleges iterálható
# sorozat lehet:
lst = [10, 20, 30, 40, 50]
lst[1:4] = (-2, -3, -4)
print(lst) # [10, -2, -3, -4, 50]
lst = [10, 20, 30, 40, 50]
lst[1:4] = range(5)
print(lst) # [10, 0, 1, 2, 3, 4, 50]
lst = [10, 20, 30, 40, 50]
dic = {'A': 1, 'B': 2}
lst[1:4] = dic.keys()
print(lst) # [10, 'A', 'B', 50] -- a sorrend 3.6 verzió előtt nem garantált!
#######################################
# Törlés slicing segítségével.
lst = [10, 20, 30, 40, 50]
del(lst[1:4])
print(lst) # [10, 50]
lst = [10, 20, 30, 40, 50]
del(lst[1:100])
print(lst) # [10]
#######################################
|
fdda3d6a9e9284bf7f2a2379a7a328554c423bbc | BercziSandor/pythonCourse_2020_09 | /Datastructures/list_1.py | 3,101 | 4.34375 | 4 | # https://www.python-course.eu/python3_sequential_data_types.php
# Listák 1.
# append() metódus, for ciklus
# elem törlése: del() és lista törlése
# memóriacím lekérdezése: id()
x = [10, 20, 30]
print(x, type(x), len(x)) # [10, 20, 30] <class 'list'> 3
# A hosszat ugyanúgy a len() függvénnyel kérdezzük le, mint a sztringeknél.
# Különféle típusú elemeket tartalmazhat
x = [10, 'John', 32.5]
print(x) # [10, 'John', 32.5]
# Nemcsak alaptípusokat tartalmazhat, hanem listát és egyéb összetett típusokat is.
lst = [1, ['A', 2], 'B'] # a második elem egy lista
print(lst, len(lst)) # [1, ['A', 2], 'B'] 3
# Üres lista készítése
x = []
y = list()
print(x, y) # [] []
#################################
# Indexelhető
x = [10, 'John', 32.5]
print(x[0], x[len(x) - 1]) # 10 32.5
#################################
# Iterálható, for ciklussal bejárható
for e in x:
print(e, end=' ') # 10 John 32.5
print()
# Nem pythonikus for ciklus - működik, de szószátyár és ezért utáljuk.
# Az i változóra semmi szükség nincs!
for i in range(len(x)): # hivatalból üldözendő!
print(x[i], end=' ')
print() # 10 John 32.5
#################################
# Módosítható
x[1] = 'Jane'
print(x) # [10, 'Jane', 32.5]
#################################
# Új elem hozzáfűzése (append)
x.append('new item')
print(x) # [10, 'Jane', 32.5, 'new item']
# Figyeljük meg, hogy a módosítás helyben történik. Miből látszik ez?
#################################
# Elem törlése (del)
del(x[1])
print(x) # [10, 32.5, 'new item']
# Itt is helyben történik a módosítás, az x lista memóriacíme nem változik.
#################################
# Teljes lista törlése
x = []
# Ekkor x egy ÚJ, üres listára mutat! Lássuk:
x = [1, 2, 3]
id_1 = id(x)
x = []
id_2 = id(x)
print(id_1, id_2) # 7202696 7202136
# id(x): az x változó által megjelölt elem memóriacíme decimálisan.
# Látható, hogy a két memóriacím nem egyezik; 7202696 címen van
# az eredeti lista, rá már egyetlen változó sem mutat, a futtató
# rendszer ezt észreveszi és felszabadítja a memóriát.
#################################
# Teljes lista törlése és a változó megsemmisítése.
# Ritkán csináljuk: Ha nagyon nagy a lista és kevés a
# memória --> mikor már nem kell, töröljük.
# Egyébként a futtató rendszer úgyis automatikusan felszabadítja
# a memóriát, amikor már egy változó sem mutat az illető elemre.
del(x) # megszüntetjük az x nevet
print(x)
# Traceback (most recent call last):
# File "test.py", line 51, in <module>
# print(x)
# NameError: name 'x' is not defined
# Csak a NÉV szűnik meg a del()-től!!!
x = [1, 2, 3]
y = x
print(y) # [1, 2, 3] y ugyanarra a memóriacímre mutat, mint x
del(x) # megszüntetjük az x nevet
print(y) # [1, 2, 3] y megmaradt
del(y)
print(y) # de most már nincs
# Traceback (most recent call last):
# File "test.py", line 57, in <module>
# print(y)
# NameError: name 'y' is not defined
#################################
|
e23b48fd83d62d7cd6c99b18dcb614edcfa61713 | BercziSandor/pythonCourse_2020_09 | /Num_py/numpy_1.py | 6,404 | 4.1875 | 4 | # numpy tömbök bemutatása
# shape, ndim, dtype, slicing
# https://www.w3schools.com/python/numpy_intro.asp
# https://www.w3schools.com/python/numpy_array_slicing.asp
# https://medium.com/better-programming/numpy-illustrated-the-visual-guide-to-numpy-3b1d4976de1d
# http://jalammar.github.io/visual-numpy/
# https://stackoverflow.com/questions/49751000/how-does-numpy-determine-the-array-data-type-when-it-contains-multiple-dtypes
# https://numpy.org/doc/stable/reference/arrays.dtypes.html
# https://www.geeksforgeeks.org/data-type-object-dtype-numpy-python/
import numpy as np
# Egy dimenziójú tömb (vektor):
arr_1 = np.array([10, 20, 30])
print(arr_1.ndim, arr_1.shape) # 1 (3,)
##################################
# Két dimenziós, egysoros tömb:
arr_1 = np.array([ [10, 20, 30] ])
print(arr_1.ndim, arr_1.shape) # 2 (1, 3)
##################################
# Két dimenziós, egyoszlopos tömb:
arr_1 = np.array([
[10],
[20],
[30]
]
)
# Persze így is írható:
arr_1 = np.array([ [10], [20], [30] ])
print(arr_1.ndim, arr_1.shape) # 2 (3,1)
##################################
# Kétsoros, három oszlopos tömb:
arr_1 = np.array([
[10, 20, 30],
[40, 50, 60]
]
)
# Leírhatjuk így is:
arr_1 = np.array([ [10, 20, 30], [40, 50, 60] ])
print(arr_1.ndim, arr_1.shape) # 2 (2, 3)
##################################
# Adattípusok
# Csupa egész szám van a tömbben:
arr_1 = np.array([10, 20, 30])
print(arr_1.dtype, arr_1.dtype.type) # int32 <class 'numpy.int32'>
##################################
# Sztring is van a tömbben::
arr_1 = np.array([10, 20, '30'])
print(arr_1.dtype, arr_1.dtype.type) # <U11 <class 'numpy.str_'>
# Ez az eset viszonylag gyakran előfordul, pl. fejléces táblázatoknál, vagy
# szövegként beírt számoknál.
# Az U betű azt jelenti, hogy Unicode kódolású sztring, a 11 azt, hogy legfeljebb 11
# karakteres, a < jel azt, hogy little endian (a legkisebb helyiértékű bájt van legelöl).
# Nem tudom, milyen heurisztika szerint számították ki, hogy itt (Windows alatt, ennél a
# numpy verziónál) a méret pont 11 karakter legyen.
# Egy 15 karakteres sztringnél 13 lesz az érték:
arr_1 = np.array([10, 20, '1235678901235'])
print(arr_1.dtype) # <U13
# Nincs nagy jelentősége - a lényeg: ha egyetlen sztring van a tömbben, akkor már az egész
# tömb is sztring típusú lesz; ami azt jelenti, hogy MINDEGYIK eleme sztring típusú:
print(arr_1[0].dtype) # <U2
# ami azt jelenti, hogy numerikus műveletet nem végezhetünk velük:
print(arr_1[0] + 2) # TypeError
# A sztringet az astype() metódussal számmá kell alakítanunk:
print(arr_1[0].astype(int) + 2, arr_1[0].astype(float) + 2) # 2 2.0
##################################
# Általánosabb esetben, egyéb típusoknál:
arr_1 = np.array([10, 20, {3}])
print(arr_1.dtype, arr_1.dtype.type) # object <class 'numpy.object_'>
###########################################
# A slicing ugyanúgy megy, mint az egydimenziós listáknál, az egyes dimenziókhoz
# tartozó kifejezések vesszővel vannak elválasztva. A hiányzó kifejezés itt is a
# default-ot jelenti. Ha egy dimenzióra teljesen hiányzik a kifejezés, akkor
# azon dimenzió szerint az összes elemet kell venni.
arr_1 = np.array([
[10, 20, 30],
[40, 50, 60]
]
)
arr_2 = arr_1[:,:] # teljes másolat: összes sor, összes oszlop
print(arr_2)
# [[10 20 30]
# [40 50 60]]
# Ugyanez másként:
arr_2 = arr_1[:] # összes sor, oszlopokról hallgatunk --> tehát az összes
arr_2 = arr_1[:,] # összes sor, oszlopokról semmit nem specifikálunk --> az összes
##################################
# Az első dimenzió (a sorok) helye nem lehet üres, ez:
arr_2 = arr_1[,1]
# szintaktikai hiba. Itt az ellipsis jelölést használhatjuk:
arr_2 = arr_1[...,1]
print(arr_2) # [20 50]
##################################
# Egy teljes sor kiválasztása többféle módon leírható.
# Egy dimenziós tömbbé alakítva:
print(arr_1[0]) # [10 20 30]
print(arr_1[0,]) # [10 20 30]
print(arr_1[0,:]) # [10 20 30]
print(arr_1[0,::]) # [10 20 30]
# A második változat a legolvashatóbb (bár ez szubjektív). Nekem azért ez tetszik
# legjobban, mert rövid, de látszik belőle, hogy két dimenziós tömbről van szó. Az
# első alakról nem tudjuk eldönteni, hogy egy- vagy kétdimenziós-e a tömb.
# Az, hogy indegyik esetben egy dimenziós tömbként kapjuk meg az eredményt, már a
# fenti kiíratásból is látszik (egyetlen szögletes zárójelpárban vannak az elemek).
print(arr_1[0,].shape) # (3,)
# Egy teljes sor kiválasztása egy soros kétdimenziós tömbként:
print(arr_1[0:1]) # [[10 20 30]]
print(arr_1[0:1,]) # [[10 20 30]]
print(arr_1[0:1,:]) # [[10 20 30]]
print(arr_1[0:1,::]) # [[10 20 30]]
print(arr_1[0:1].shape) # (1, 3)
##################################
# Összes sor, második oszloptól végig:
print(arr_1[:,1:])
# [[20 30]
# [50 60]]
##################################
# A teljes első oszlop egydimenziós tömbbé alakítva:
arr_2 = arr_1[:,0]
print(arr_2, arr_2.shape) # [10 40] (2,)
# Az első oszlop egyoszlopos két dimenziós tömbbé alakítva:
arr_2 = arr_1[:,0:1]
print(arr_2, arr_2.shape)
# [[10]
# [40]] (2, 1)
# Utolsó oszlop egydimenziós tömbbé alakítva:
arr_2 = arr_1[:,-1]
print(arr_2, arr_2.shape) # [30 60] (2,)
# Utolsó oszlop egyoszlopos két dimenziós tömbbé alakítva:
arr_2 = arr_1[:,-1:]
print(arr_2, arr_2.shape)
# [[30]
# [60]] (2, 1)
##################################
# Explicit típuskonverziók
arr_1 = np.array([10, 20, '30'])
arr_2 = arr_1.astype(int)
print(arr_2) # [10 20 30]
arr_1 = np.array([10, 20, 'xyz'])
arr_2 = arr_1.astype(int) # hiba
###########################################
# A slice másik objektum, de AZ EREDETI tömbre mutató referenciákat tartalmaz,
# azaz NEM másolat:
import numpy as np
arr_1 = np.array([1, 2, 3])
arr_2 = arr_1[:]
print(id(arr_1), id(arr_2)) # 7999064 66477016
arr_2[0] = 99
print(arr_1) # [99 2 3]
# A Python list-nél nem így van:
lst_1 = [1, 2, 3]
lst_2 = lst_1[:]
lst_2[0] = 99
print(lst_1) # [1, 2, 3]
# Itt a slice másolat.
##################################
# Ha másolatot akarunk létrehozni a numpy array-nél, akkor a copy() metódust kell meghívni:
arr_1 = np.array([1, 2, 3])
arr_2 = arr_1.copy()
arr_2[0] = 99
print(arr_1) # # [1 2 3]
##################################
|
f4b554f911103a63fd1ef840f986af810967c43a | UmaRathore/Regular_Expressions | /Password_Validation.py | 863 | 3.890625 | 4 | # email and password validation
import re
email_pattern = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
while True:
email_id = input('Enter email address : ')
email_id_object = email_pattern.search(email_id)
if email_id_object is None:
print('Enter correct email address : ')
continue
else:
print('Email registered')
break
# password validation which is at least 8 characters long, has signs @#$% and ends with a number
pwd_pattern = re.compile(r"([a-zA-Z0-9$%#@]{7,}[0-9])")
while True:
pwd = input('Strong Password of at least 8 characters, numbers, @#$%: ')
pwd_object = pwd_pattern.fullmatch(pwd)
if pwd_object is None:
print("Enter correct password of at least 8 characters, numbers, @#$% :")
continue
else:
print("Welcome !!")
break
|
3fd7d0c449585ee03b8a378486025cf49bf098ac | KarolGOli/Praticas_em_Python | /exercicio_4.py | 2,318 | 3.9375 | 4 | from operator import itemgetter
lista = []
cont = 0
int(cont)
def cadastro_produto(produto_para_cadastrar: dict): # função que adiciona o objeto produto à lista
lista.append(produto_para_cadastrar) # o método append faz com que o produto seja adicionado na lista
return
while cont >= 0: # condição para manter em execução o 'menu' escolhas e valores a serem informados
cadastro = int(input('\nCADASTRAR NOVO PRODUTO? (0 - Não 1 - Sim) '))
cont += 1
if cadastro == 1:
new_product = {} # dicionário para armazenar os produtos, enquanto rodar ele vai ser atualizado com um novo produto armazenado
new_product['codigo'] = int(input('INFORME O CÓDIGO DO PRODUTO: '))
if new_product['codigo'] == 0: # condição para verificar se o valor inserido é válido
print('CÓDIGO 0, encerra o cadastro de produtos.')
break
new_product['atual'] = int(input('INFORME O ESTOQUE ATUAL: '))
new_product['minimo'] = int(input('INFORME O ESTOQUE MÍNIMO: '))
if new_product['atual'] < new_product['minimo']: # condição para informar a situação do estoque
print('ESTOQUE ATUAL ABAIXO D0 MÍNIMO INDICADO!')
cadastro_produto(new_product) # chamada da função de cadastro
elif cadastro == 0:
print('\nENCERRANDO CADASTRO DE PRODUTOS...')
break
visualizar = int(input('\nAPRESENTAR TABELA DE PRODUTOS? (2 - Visualizar | 3 - Cancelar) '))
if visualizar == 2 and len(lista) > 0: # se o usuário quiser visualizar a tabela e ela estiver preenchida ele à apresenta
print('TABELA DE PRODUTOS - ORDEM CRESCENTE:')
print("CÓDIGO".center(10), end='') # métodos utilizados para centralização e estruturação da tabela
print("EST. ATUAL".center(15), end='')
print("EST. MÍNIMO".center(18))
# linha de comando responsável por ordenar a lista de forma crescente, usando como referência o item código
for produto in sorted(lista, key=itemgetter('codigo')):
print(str(produto['codigo']).center(10), end='')
print(str(produto['atual']).center(15), end='')
print(str(produto['minimo']).center(18))
elif visualizar == 3:
print('FINALIZANDO...') |
612686443d9cda5b6aa2766a6a90cc997610abf2 | vivek28111992/DailyCoding | /problem_#56_11042019.py | 1,952 | 4.09375 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given an undirected graph represented as an adjacency matrix and an integer k, write a function to determine whether each vertex in the graph can be colored such that no two adjacent vertices share the same color using at most k colors.
https://www.geeksforgeeks.org/m-coloring-problem-backtracking-5/
"""
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
# A utility function to check if the current color assignment is safe for vertex v
def isSafe(self, v, colour, c):
print('v ', v)
print('color ', colour)
print('c ', c)
print('graph ', self.graph)
print('------------------')
for i in range(self.V):
if self.graph[v][i] == 1 and colour[i] == c:
return False
return True
# A recursive utility function to solve m coloring problem
def graphColourUtil(self, noOfColor, colour, v):
if v == self.V:
return True
for c in range(1, noOfColor+1):
if self.isSafe(v, colour, c) == True:
colour[v] = c
if self.graphColourUtil(noOfColor, colour, v+1) == True:
return True
colour[v] = 0
# Main function for graph Coloring
def graphColouring(self, noOfColor):
colour = [0] * self.V
if self.graphColourUtil(noOfColor, colour, 0) == None:
return False
# Print the solution
print("Solution exist and Following are the assigned colours:")
for c in colour:
print(c, end=', ')
return True
if __name__ == '__main__':
g = Graph(4)
g.graph = [[0, 1, 1, 1], [1, 0, 1, 0], [1, 1, 0, 1], [1, 0, 1, 0]]
noOfColor = 3
g.graphColouring(noOfColor)
|
39f3c7125d985d4a7d5c494884e16ed2fc27c844 | vivek28111992/DailyCoding | /problem_#98.py | 2,258 | 4.0625 | 4 | """
Given a 2D board of characters and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example, given the following board:
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
exists(board, "ABCCED") returns true, exists(board, "SEE") returns true, exists(board, "ABCB") returns false.
"""
r = 4
c = 4
# Function to check if a word exists in a grid starting from the first match in the grid level: index till which pattern is matched x, y: current position in 2D array
def findMatch(mat, pat, x, y, nrow, ncol, level):
l = len(pat)
# Pattern matched
if level == l:
return True
# out of boundry
if (x < 0 or y < 0) or (x >= nrow or y >= ncol):
return False
# If grid matches with a letter while recursion
if (mat[x][y] == pat[level]):
# Marking this cell as visited
temp = mat[x][y]
mat[x].replace(mat[x][y], "#")
# finding subpattern in 4 directions
res = ((mat, pat, x - 1, y, nrow, ncol, level + 1) or
(mat, pat, x + 1, y, nrow, ncol, level + 1) or
(mat, pat, x, y+1, nrow, ncol, level + 1) or
(mat, pat, x, y-1, nrow, ncol, level + 1))
# marking this cell as unvisited again
return res
else: # Not matching then false
return False
# Function to check if the word exists in the grid or not
def checkMatch(mat, pat, nrow, ncol):
l = len(pat)
# if total characters in matrix is less then pattern lenghth
if (l > nrow * ncol):
return False
# Traverse in the grid
for i in range(nrow):
for j in range(ncol):
# If the first letter matches then recur and check
if mat[i][j] == pat[0]:
if (findMatch(mat, pat, i, j, nrow, ncol, 0)):
return True
return False
if __name__ == "__main__":
grid = ["axmy", "bgdf","xeet", "raks"]
# Function to check if word
# exists or not
if (checkMatch(grid, "geeks", r, c)):
print("Yes")
else:
print("No") |
c9087ee72e96521122ccb48f9995ab7a8e9e1d39 | vivek28111992/DailyCoding | /problem_#26_13032019.py | 1,507 | 3.921875 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given a singly linked list and an integer k, remove the kth last element from the list. k is guaranteed to be smaller than the length of the list.
The list is very long, so making more than one pass is prohibitively expensive.
Do this in constant space and in one pass.
https://leetcode.com/problems/remove-nth-node-from-end-of-list/solution/
https://www.geeksforgeeks.org/nth-node-from-the-end-of-a-linked-list/
"""
class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# createNode and make linked list
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def removeNthFromEnd(self, n):
dummy = Node(0)
dummy.next = self.head
first = dummy
second = dummy
# Advances first pointer so that the gap between first and second is n nodes apart
for i in range(n):
first = first.next
# Move first to the end, maintaining the gap
while first.next != None:
first = first.next
second = second.next
second.next = second.next.next
return second.next.data
# Driver Code
llist = LinkedList()
llist.push(5)
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)
print(llist.removeNthFromEnd(2))
|
404bdfdf31e4aa00015b74c58ff37c103f84df8f | vivek28111992/DailyCoding | /problem_#48_03042019.py | 2,435 | 3.921875 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given pre-order and in-order traversals of a binary tree, write a function to reconstruct the tree.
For example, given the following preorder traversal:
[a, b, d, e, c, f, g]
And the following inorder traversal:
[d, b, e, a, f, c, g]
You should return the following tree:
a
/ \
b c
/ \ / \
d e f g
https://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/
"""
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
Recursive function to construct binary of size len from Inorder traversal in[] and Preorder traversal pre[]. Initialize values of inStrt and inEnd should be 0 and len - 1. The function doesn't do any error checking for cases where inorder and preorder do not form a tree
"""
def buildTree(inOrder, preOrder, inStrt, inEnd):
if(inStrt > inEnd):
return None
# Pinch current node from Preorder traversal using preIndex and increment preIndex
tNode = Node(preOrder[buildTree.preIndex])
buildTree.preIndex += 1
# If this node has no children then return
if inStrt == inEnd:
return tNode
# Else find the index of this node in Inorder traversal
inIndex = search(inOrder, inStrt, inEnd, tNode.data)
# Using index in Inorder Traversal, construct left and right subtrees
tNode.left = buildTree(inOrder, preOrder, inStrt, inIndex-1)
tNode.right = buildTree(inOrder, preOrder, inIndex+1, inEnd)
return tNode
# UTILITY FUNCTIONS
# Function to find index of value in arr[start...end]
# The function assumes that value is present inOrder[]
def search(arr, start, end, value):
for i in range(start, end + 1):
if arr[i] == value:
return i
def printInorder(node):
if node is None:
return
# first recur on left child
printInorder(node.left)
# then print the data of node
print(node.data, end=' ')
# now recur on right child
printInorder(node.right)
inOrder = ['D', 'B', 'E', 'A', 'F', 'C']
preOrder = ['A', 'B', 'D', 'E', 'C', 'F']
# Static variable preIndex
buildTree.preIndex = 0
root = buildTree(inOrder, preOrder, 0, len(inOrder) - 1)
# Let us test the build tree by priting Inorder traversal
printInorder(root)
|
a9169a0606ef75c17087acce0c610bb5aa8e1660 | vivek28111992/DailyCoding | /problem_#99.py | 624 | 4.1875 | 4 | """
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example, given [100, 4, 200, 1, 3, 2], the longest consecutive element sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
"""
def largestElem(arr):
s = set(arr)
m = 0
for i in range(len(arr)):
if arr[i]+1 in s:
j = arr[i]
m1 = 0
while j in s:
j += 1
m1 += 1
m = max(m, m1)
print(m)
return m
if __name__ == "__main__":
largestElem([100, 4, 200, 1, 3, 2])
|
f96e8a52c38e140ecf3863d1ea138e15b78c7aa8 | vivek28111992/DailyCoding | /problem_#28_15032019.py | 1,687 | 4.125 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Palantir.
Write an algorithm to justify text. Given a sequence of words and an integer line length k, return a list of strings which represents each line, fully justified.
More specifically, you should have as many words as possible in each line. There should be at least one space between each word. Pad extra spaces when necessary so that each line has exactly length k. Spaces should be distributed as equally as possible, with the extra spaces, if any, distributed starting from the left.
If you can only fit one word on a line, then you should pad the right-hand side with spaces.
Each word is guaranteed not to be longer than k.
For example, given the list of words ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"] and k = 16, you should return the following:
["the quick brown", # 1 extra space on the left
"fox jumps over", # 2 extra spaces distributed evenly
"the lazy dog"] # 4 extra spaces distributed evenly
https://leetcode.com/problems/text-justification/discuss/24891/Concise-python-solution-10-lines.
"""
def fulljustify(words, maxWidth):
res, cur, num_of_letters = [], [], 0
for w in words:
if num_of_letters + len(w) + len(cur) > maxWidth:
for i in range(maxWidth - num_of_letters):
cur[i%(len(cur)-1 or 1)] += ' '
res.append(''.join(cur))
cur, num_of_letters = [], 0
cur += [w]
num_of_letters += len(w)
return res + [' '.join(cur).ljust(maxWidth)]
words = ["the quick brown",
"fox jumps over",
"the lazy dog"]
print(fulljustify(words, 16))
|
03dc0512b0e47789f95ea5628c4f84f5cfad6b16 | vivek28111992/DailyCoding | /#825.py | 135 | 3.9375 | 4 | # [-9, -2, 0, 2, 3]
def square(arr):
sq_arr = [i * i for i in arr]
sq_arr.sort()
return sq_arr
print(square([-9, -2, 0, 2, 3])) |
370ff8761ac2230627a5b2d37ec47c0141c1339b | vivek28111992/DailyCoding | /problem_#62_17042019.py | 1,060 | 3.96875 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Facebook.
There is an N by M matrix of zeroes. Given N and M, write a function to count the number of ways of starting at the top-left corner and getting to the bottom-right corner. You can only move right or down.
For example, given a 2 by 2 matrix, you should return 2, since there are two ways to get to the bottom-right:
Right, then down
Down, then right
Given a 5 by 5 matrix, there are 70 ways to get to the bottom-right.
https://www.geeksforgeeks.org/count-possible-paths-top-left-bottom-right-nxm-matrix/
https://www.youtube.com/watch?v=GO5QHC_BmvM
"""
def nWays(n, m):
nWaysArr = [[0] * m for _ in range(n)]
for i in range(n):
for j in range(m):
if i == 0:
nWaysArr[i][j] = 1
elif j == 0:
nWaysArr[i][j] = 1
else:
nWaysArr[i][j] = nWaysArr[i][j-1] + nWaysArr[i-1][j]
return nWaysArr[n-1][m-1]
if __name__ == '__main__':
print(nWays(3, 3))
|
b19cc3a733b21cb61cf7aaf717e316809ee00220 | vivek28111992/DailyCoding | /problem_#70.py | 619 | 3.96875 | 4 | """
A number is considered perfect if its digits sum up to exactly 10.
Given a positive integer n, return the n-th perfect number
"""
def findNthPerfect(n):
count = 0
curr = 19
while True:
# Find sum of digits in current no.
sum = 0
x = curr
while x > 0:
sum += x % 10
x = int(x/10)
# If sum is 10, we increment count
if sum == 10:
count += 1
# If count becomes n, we return current number
if count == n:
return curr
curr += 9
return -1
# Driver Code
print(findNthPerfect(5))
|
dc0a57534f9f646355c49d9714ebdbfc14ab5adf | vivek28111992/DailyCoding | /problem_#21_08032019.py | 1,236 | 3.765625 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Snapchat.
Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required.
For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.
https://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/
"""
from operator import itemgetter
from itertools import chain
def noOfRooms():
data = [(30, 75), (0, 50), (60, 150)]
lectures_start = list(list(zip(*data))[0])
lectures_start.sort()
lectures_end = list(list(zip(*data))[1])
lectures_end.sort()
rooms_req = 0
j = 0
i = 0
max_rooms = 0
n = len(lectures_start)
while i < n and j < n:
if lectures_start[i] < lectures_end[j]:
rooms_req += 1
max_rooms = rooms_req if rooms_req > max_rooms else max_rooms
i += 1
else:
while lectures_end[j] < lectures_start[i]:
rooms_req -= 1
j += 1
print(max_rooms)
# data = list(chain.from_iterable(data))
#
# print(data)
# data = sorted(data, key=itemgetter(0))
# print(data)
noOfRooms()
|
cbb259086c41bdc29d9569b3c4cecebfc355bad9 | vivek28111992/DailyCoding | /problem_#101.py | 1,336 | 4.03125 | 4 | """
Given an even number (greater than 2), return two prime numbers whose sum will be equal to the given number.
A solution will always exist. See Goldbach’s conjecture.
Example:
Input: 4
Output: 2 + 2 = 4
If there are more than one solution possible, return the lexicographically smaller solution.
If [a, b] is one solution with a <= b, and [c, d] is another solution with c <= d, then
[a, b] < [c, d]
If a < c OR a==c AND b < d.
"""
def sieveOfEratosthenes(n, isPrime):
# Initialize all entries of boolean array as True. A value in isPrime[i] will finally be False if i is not a Prime, else Ture bool isPrime[n+1]
isPrime[0] = isPrime[1] = False
for i in range(2, n+1):
isPrime[i] = True
p = 2
while p*p <= n:
# If isPrime[p] is not changed, then it is a Prime
if (isPrime[p] == True):
# Update all multiples of p
i = p * p
while i <= n:
isPrime[i] = False
i += p
p += 1
def findPrimePair(n):
# Generating primes using Sieve
isPrime = [0] * (n+1)
sieveOfEratosthenes(n, isPrime)
# Traversing all numbers to find first pair
for i in range(n):
if (isPrime[i] and isPrime[n-i]):
return (i, (n-i))
if __name__ == "__main__":
n = 74
print(findPrimePair(n))
|
f6a83bb9d12fae8b81bd522dfec9fcb93952e5a9 | vivek28111992/DailyCoding | /problem_#93.py | 1,887 | 4 | 4 | """
Given a tree, find the largest tree/subtree that is a BST.
Given a tree, return the size of the largest tree/subtree that is a BST.
"""
INT_MIN = -2147483648
INT_MAX = 2147483647
# Helper function that allocates a new
# node with the given data and None left
# and right pointers.
class newNode:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Returns Information about subtree. The
# Information also includes size of largest
# subtree which is a BST
def largestBSTBT(root):
# Base cases : When tree is empty or it has
# one child.
if root == None:
return 0, INT_MIN, INT_MAX, 0, True
if root.left == None and root.right == None:
return 1, root.data, root.data, 1, True
# Recur for left subtree and right subtree
l = largestBSTBT(root.left)
r = largestBSTBT(root.right)
# Create a return variable and initialize its
# size.
ret = [0, 0, 0, 0, 0]
ret[0] = (1 + l[0] + r[0])
# If whole tree rooted under current root is
# BST.
if (l[4] and r[4] and l[1] <
root.data and r[2] > root.data):
ret[2] = min(l[2], min(r[2], root.data))
ret[1] = max(r[1], max(l[1], root.data))
# Update answer for tree rooted under
# current 'root'
ret[3] = ret[0]
ret[4] = True
return ret
# If whole tree is not BST, return maximum
# of left and right subtrees
ret[3] = max(l[3], r[3])
ret[4] = False
return ret
if __name__ == '__main__':
"""Let us construct the following Tree
60
/ \
65 70
/
50 """
root = newNode(60)
root.left = newNode(65)
root.right = newNode(70)
root.left.left = newNode(50)
print("Size of the largest BST is",
largestBSTBT(root)[3])
|
4277764dd9fe0ae8877436cd014f4b52e900dfa9 | vivek28111992/DailyCoding | /problem_#14_01032019.py | 846 | 3.984375 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.
Hint: The basic equation of a circle is x2 + y2 = r2.
https://www.geeksforgeeks.org/estimating-value-pi-using-monte-carlo/
"""
import random
def pi(interval):
circle_points = 0
square_points = 0
i = 0
while i < (interval*interval):
x = float(random.randint(0, interval) % (interval+1)) / interval
y = float(random.randint(0, interval) % (interval+1)) / interval
d = x*x + y*y
if d <= 1:
circle_points += 1
square_points += 1
est_pi = float(4 * circle_points) / square_points
i += 1
return est_pi
if __name__ == '__main__':
print(pi(100))
|
140a539e327bd9608796fb12d68d343b4f1a18a8 | acneuromancer/problem_solving_python | /graphs_2/word_ladder.py | 1,313 | 3.53125 | 4 | from collections import defaultdict
from collections import deque
from itertools import product
# import os
def build_graph(words):
buckets = defaultdict(list)
graph = defaultdict(set)
for word in words:
for i in range(len(word)):
bucket = '{}_{}'.format(word[:i], word[i+1:])
buckets[bucket].append(word)
for bucket, mutual_neighbours in buckets.items():
for word1, word2 in product(mutual_neighbours, repeat = 2):
if word1 != word2:
graph[word1].add(word2)
graph[word2].add(word1)
return graph
def get_words(vocabulary_file):
with open(vocabulary_file, 'r') as words_file:
for line in words_file:
yield line[:-1]
def traverse(graph, starting_vertex):
visited = set()
queue = deque([[starting_vertex]])
while(queue):
path = queue.popleft()
vertex = path[-1]
yield vertex, path
for neighbour in graph[vertex] - visited:
visited.add(neighbour)
queue.append(path + [neighbour])
word_graph = build_graph(get_words('words_shorter.txt'))
for k, v in word_graph.items():
print('{} -> {}'.format(k, v))
for vertex, path in traverse(word_graph, 'fool'):
if vertex == 'sage':
print(' -> '.join(path)) |
8a07b97ab69c6716d99564830d3625a9fa9ca17c | acneuromancer/problem_solving_python | /trees/binary_tree/bin_tree_parser.py | 3,545 | 3.984375 | 4 | class BinaryTree:
def __init__(self, root):
self.key = root
self.left_child = None
self.right_child = None
def insert_left(self, new_node):
if self.left_child == None:
self.left_child = BinaryTree(new_node)
else:
t = BinaryTree(new_node)
t.left_child = self.left_child
self.left_child = t
def insert_right(self, new_node):
if self.right_child == None:
self.right_child = BinaryTree(new_node)
else:
t = BinaryTree(new_node)
t.right_child = self.right_child
self.right_child = t
def get_right_child(self):
return self.right_child
def get_left_child(self):
return self.left_child
def set_root_val(self, obj):
self.key = obj
def get_root_val(self):
return self.key
def preorder(self):
print(self.key)
if self.left_child:
self.left_child.preorder()
if self.right_child:
self.right_child.preorder()
def postorder(self):
if self.left_child:
self.left_child.postorder()
if self.right_child:
self.right_child.postorder()
print(self.key)
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
'''
1. If the current token is a ‘(’, add a new node as the left child of the current node, and
descend to the left child.
2. If the current token is in the list [‘+’,‘−’,‘/’,‘*’], set the root value of the current node to
the operator represented by the current token. Add a new node as the right child of the
current node and descend to the right child.
3. If the current token is a number, set the root value of the current node to the number and
return to the parent.
4. If the current token is a ‘)’, go to the parent of the current node.
'''
def build_parse_tree(fp_exp):
fp_list = fp_exp.split()
p_stack = Stack()
e_tree = BinaryTree('')
p_stack.push(e_tree)
current_tree = e_tree
for i in fp_list:
if i == '(':
current_tree.insert_left('')
p_stack.push(current_tree)
current_tree = current_tree.get_left_child()
elif i not in ['+', '-', '*', '/', ')']:
current_tree.set_root_val(int(i))
parent = p_stack.pop()
current_tree = parent
elif i in ['+', '-', '*', '/']:
current_tree.set_root_val(i)
current_tree.insert_right('')
p_stack.push(current_tree)
current_tree = current_tree.get_right_child()
elif i == ')':
current_tree = p_stack.pop()
else:
raise ValueError
return e_tree
import operator
def evaluate(parse_tree):
opers = {
'+' : operator.add,
'-' : operator.sub,
'*' : operator.mul,
'/' : operator.truediv
}
left = parse_tree.get_left_child()
right = parse_tree.get_right_child()
if left and right:
fn = opers[parse_tree.get_root_val()]
return fn(evaluate(left), evaluate(right))
else:
return parse_tree.get_root_val()
pt = build_parse_tree("( ( 10 + 5 ) * 3 )")
pt.postorder()
print(evaluate(pt))
|
e23bb077affd2781fd36113b03fe55755ae16b9f | acneuromancer/problem_solving_python | /basic_data_structures/queue/queue_test.py | 200 | 3.890625 | 4 | from Queue import Queue
q = Queue()
q.enqueue('hello')
q.enqueue('dog')
q.enqueue(3)
print("Size of the queue is %d." % q.size())
while not q.is_empty():
print(q.dequeue(), end = " ")
print()
|
9914dde414bc7ad3df7543e58d0e478ecef3b013 | acneuromancer/problem_solving_python | /python_basics/list_comprehension.py | 621 | 3.9375 | 4 | def practice_1():
sq_list = [x * x for x in range(1, 11)]
print(sq_list)
sq_list = [x * x for x in range(1, 11) if x % 2 != 0]
print(sq_list)
ch_list = [ch.upper() for ch in "Hello World!" if ch not in 'aeiou']
print(ch_list)
def method_1():
word_list = ['cat', 'dog', 'rabbit']
letter_list = []
for word in word_list:
for ch in word:
letter_list.append(ch)
print(letter_list)
def method_2():
word_list = ['cat', 'dog', 'rabbit']
ch_list = []
[ch_list.append(ch) for word in word_list for ch in word if ch not in ch_list]
print(ch_list)
|
bf7c8573149487a85dbcb6e971ccee8afc0b5e76 | acneuromancer/problem_solving_python | /recursion/reverse_string.py | 346 | 3.96875 | 4 | def reverse_str(str):
if len(str) == 1:
return str[0]
last = len(str) - 1
return str[last] + reverse_str(str[0:last])
def reverse_str_2(str):
if str == "":
return str
return reverse_str_2(str[1:]) + str[0]
print(reverse_str_2("Hello World!"))
print(reverse_str_2("abcdefgh"))
print(reverse_str_2("xyz"))
|
152e728c543b491be4f8b0135ace70778fc6734a | runt1m33rr0r/python_homeworks | /homework_2/F87134_L3_T2.py | 668 | 3.671875 | 4 | import sys
import string
input = sys.argv[1:]
text = input[0].strip().upper().translate(string.maketrans('', ''), string.punctuation)
key = input[1].strip().upper().translate(string.maketrans('', ''), string.punctuation)
# extend the key
initial_len = len(key)
current_letter = 0;
while len(key) < len(text):
key += key[current_letter]
current_letter = (current_letter + 1) % initial_len
# encode the text
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
result = []
for text_let, key_let in zip(text, key):
key = alphabet.index(key_let)
encoded = alphabet[(alphabet.index(text_let) + key) % len(alphabet)]
result.append(encoded)
print ''.join(result)
|
7e9b02feb9177e628d4774559beb4104a0c240de | runt1m33rr0r/python_homeworks | /homework_1/F87134_L2_T1.py | 164 | 3.78125 | 4 | import sys
input = sys.argv[1:]
for i in range(len(input) - 1):
if input[i] > input[i + 1]:
print("unsorted")
break
else:
print("sorted")
|
91d0c13f973959afb4d736ea75bed6043e5d0fec | Brucehanyf/python_tutorial | /base/param.py | 888 | 4.03125 | 4 | # 参数相关语法
def param (param="123456"):
print("123123")
# 函数的收集参数和分配参数用法(‘*’ 和 ‘**’)
# arg传递的是实参, kvargs传递的是带key值的参数
# 函数参数带*的话,将会收集非关键字的参数到一个元组中;
# 函数参数带**的话,将会收集关键字参数到一个字典中;
# 参数arg、*args、必须位于**kwargs之前
# 指定参数不会分配和收集参数
def param_check(*args,value = 'param', **kvargs):
print(value)
print(args)
print("args--------start")
for arg in args:
print(arg)
print("args--------end")
print(kvargs)
print("kvargs--------start")
for k, v in kvargs.items():
print("key: " + str(k) + " value:" + str(v))
print("kvargs--------end")
# **参数需要指定key值
param_check(1, 2, 3,value="1024",k=5,v=6,a=7,b=8)
|
f2ddc408fe7ca9f5fc5da16dcdca4a83fbce9c54 | Brucehanyf/python_tutorial | /base/day01.py | 1,041 | 3.78125 | 4 | ### 字符串相关语法
print('hello,world')
message = "hello,message"
print(message)
message = "hello world"
print(message)
# 变量名不能以数字开头, 中间不能包含空格,其中可以包含下划线
# 字符串字母首字母大写 字符串大写 字符串小写
name = "hello bruce"
print(name.title())
print(name.upper())
print(name.lower())
# 合并字符串
first_name = "Bruce"
last_name = "Han"
full_name = first_name + " " + last_name
print(full_name.title()+"!")
# 使用制表符或者换行符来添加空白
# 制表符 \t 换行符 \n
print("language java \n\tpython js ")
# 删除空白
# rstrip() 删除右侧空格
# lstrip() 删除左侧空格
# strip() 删除两侧空格
favorite_language = " python "
print(favorite_language)
favorite_language = favorite_language.rstrip()
print(favorite_language)
favorite_language = favorite_language.lstrip()
print(favorite_language)
# 使用str() 避免类型错误
age = 23
message = "hello Bruce "+ str(age) + "rd birthday!";
print(message)
|
9ab9305ebf7869b1b9576730ec40163260cd0e12 | Brucehanyf/python_tutorial | /api/a_zip.py | 672 | 3.890625 | 4 | # zip函数
# zip() 函数用于将可迭代的对象作为参数,
# 将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,
# 这样做的好处是节约了不少的内存。
a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,9]
zipped = zip(c,a)
# print(list(zipped))
# 之后取出最小集配对
# 解压
# a1, a2 = zip(*zip(a,b))
a1, a2 = zip(*zipped)
print(a1)
print(a2)
from itertools import groupby
# 测试无用变量 y_list = [v for _, v in y]
map = []
for x,y in groupby(sorted(zip(c,a),key=lambda _:_[0])):
list = [v for _,v in y]
print(x,list)
map.append([x,sum(list)/len(list)])
z1, z2 = zip(*map)
print(z1, z2) |
c80b26a41d86ec4f2f702aab0922b86eec368e84 | Brucehanyf/python_tutorial | /file_and_exception/file_reader.py | 917 | 4.15625 | 4 | # 读取圆周率
# 读取整个文件
# with open('pi_digits.txt') as file_object:
# contents = file_object.read()
# print(contents)
# file_path = 'pi_digits.txt';
# \f要转义
# 按行读取
file_path = "D:\PycharmProjects\practise\\file_and_exception\pi_digits.txt";
# with open(file_path) as file_object:
# for line in file_object:
# print(line)
# file_object.readlines()
# with open(file_path) as file_object:
# lines = file_object.readlines()
# for line in lines:
# print(line)
# 使用文件中的内容
with open(file_path) as file_object:
lines = file_object.readlines()
result = '';
for line in lines:
result += line.strip()
print(result)
print(result[:10]+'......')
print(len(result))
birthday = input('请输入您的生日')
if birthday in result:
print("your birthday appears in pai digits")
else:
print("your birthday does not appears in pai digits")
|
7642b6f57230a3f436cb3bec38286f227b7df9a2 | moscowjh/fullstack-nanodegree-vm | /vagrant/tournament/tester.py | 2,436 | 3.671875 | 4 | from tournament import *
def test():
"""Test various functions of tournament project
Most particularly, playerStandings may be tested along with BYE insertion
and deletion prior to match results. Also allows clearing of players and/or
matches, and registration of players.
"""
print ""
print "s -- player standings"
print "p -- to register players"
print "c -- clear players *note* Players cannot be cleared if they have \
matches."
print "m to clear matches *note* Clearing matches will not clear players."
print "bye -- delete bye"
print "Press any other key to exit"
print ""
answer = raw_input("What would you like to do? \n")
if answer == "s":
standings = playerStandings()
current = countPlayers()
print ""
print standings
print ""
print "Current number of players:"
print current
test()
elif answer == "p":
print ""
number = countPlayers()
print "Current Players:"
print number
print ""
player = raw_input("Enter a new Player's name: \n")
registerPlayer(player)
number2 = countPlayers()
print "New current players:"
print number2
print ""
test()
elif answer == "m":
print ""
print "WARNING:"
print "THIS WILL DELETE ALL MATCHES!"
print ""
player = raw_input("Are you sure? [ y or n] \n")
if player == "y":
deleteMatches()
num = countPlayers()
print ""
print "Current players:"
print num
print ""
test()
else:
print ""
print "Okay... Going back..."
print ""
test()
elif answer == "c":
print ""
print "WARNING:"
print "THIS WILL DELETE ALL PLAYERS!"
print ""
player = raw_input("Are you sure? [ y or n] \n")
if player == "y":
deletePlayers()
num = countPlayers()
print ""
print "Current players:"
print num
print ""
test()
else:
print ""
print "Okay... Going back..."
print ""
test()
elif answer == "bye":
deleteByes()
test()
else:
end
if __name__ == '__main__':
test()
|
7bef62a6cee86d61bc1bd5323e7d8c47bbc7f8ae | ardus-uk/anagrams | /anagram2.py | 573 | 3.78125 | 4 | #!/usr/bin/python3
def unique(listx):
listy=[]
for x in listx:
if x not in listy:
listy.append(x)
return listy
with open('./wordsEn.txt') as f:
lines = f.readlines() # lines is a list of words
word = 'refined'
letters = list(word) # letters is a list of the letters
unique_letters = unique(letters)
n = len(letters)
cands = [elem for elem in lines if (len(elem)==n+1)]
i=0
for letter in unique_letters:
num = letters.count(letter)
cands = [elem for elem in cands if (letter in elem) and elem.count(letter) == num]
for cand in cands:
print (cand)
|
6669d87b8795e1d8b062f2b25ca4eeea00ecc79f | thekevinsmith/project_euler_python | /9/special_pythagorean_triplet.py | 1,238 | 4.0625 | 4 | # Problem 9 : Statement : Special Pythagorean triplet
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a**2 + b**2 = c**2
# For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
# Some math and the thinking process:
# must: a**2 + b**2 = c**2 TRUE
# and a + b + c = 1000 TRUE
# find a*b*c = ? QUESTION
# #variables and 2 true statements
# (a**2 + b**2)**(-1) = c
# 1000 - a - b = c
# 1000 - a - b = (a**2 + b**2)**(-1)
# (1000 - a - b)**2 = a**2 + b**2
# (1000 - a - b)*(1000 - a - b) = a**2 + b**2
# 1000*1000 -1000a -1000b -1000a +a**2 ab -1000b +ab + b**2 = a**2 + b**2
# 1 000 000 - 2000a -2000b = 0
# 500 - a = b -> this is replaced in another formulae
# code:
# for a
# for b
# 1000 - a - b = c
# if c > 0
# if c*c = b*b + a*a
# if a < b
def main():
output = 0
for a in range(1,1000):
for b in range(1,1000):
c = 1000 - a - b
if c > 0:
if c*c == (b*b + a*a):
if a < b:
output = a*b*c
print(a, b, c)
print(output)
if __name__ == '__main__':
main() |
62bd9b81b6ace8f9bab84fb293710c50ca0bcf29 | thekevinsmith/project_euler_python | /4/largest_palindrome_product.py | 1,778 | 4.125 | 4 | # Problem 4 : Statement:
# A palindromic number reads the same both ways. The largest palindrome
# made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
def main():
largest = 0
for i in range(0, 1000, 1):
count = 0
Num = i
while Num > 0:
Num = Num//10
count += 1
if count == 3:
prodNum.append(i)
for p in range(len(prodNum)):
for n in range(len(prodNum)):
result = prodNum[p] * prodNum[n]
test = result
count = 0
while test > 0:
test = test // 10
count += 1
if count == 6:
sixNum.append(result)
if (result // 10 ** 5 % 10) == (result // 10 ** 0 % 10):
if (result // 10 ** 4 % 10) == (result // 10 ** 1 % 10):
if (result // 10 ** 3 % 10) == (result // 10 ** 2 % 10):
palindromeNum.append(result) # all that fit criteria
if result > largest:
largest = result
print("Largest palindromic: %d" % largest)
if __name__ == '__main__':
palindromeNum = []
prodNum = []
sixNum = []
main()
# Dynamic attempt: Technically its possible but very difficult as we need to
# consider set points if a for or while is used to do verification
# Think on this...
# largest = 0
# count = 6
# result = 994009
# for c in range(0, count // 2, 1):
# if (result // 10 ** (count - 1 - c) % 10) == (result // 10 ** (c) % 10):
# if result > largest:
# largest = result
# print(result)
|
c32d0f7b44749e6ae0ecec14ed2a2002e9b8bb7b | rootme254/Python-Projects | /shop.py | 3,154 | 4.21875 | 4 | '''
This is a shopping list like ile inatumiwa in jumia the online shopping
Create a class called ShoppingCart.
Create a constructor that has no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items.
Create a method add_item that requires item_name, quantity and price arguments. This method should add the cost of the added items to the current value of total. It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item.
Create a method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of these items from the current total and also update the items dict accordingly. If the quantity of items to be removed exceeds current quantity in cart, assume that all entries of that item are to be removed.
Create a method checkout that takes in cash_paid and returns the value of balance from the payment. If cash_paid is not enough to cover the total, return Cash paid not enough.
Create a class called Shop that has a constructor which initializes an attribute called quantity at 100.
Make sure Shop inherits from ShoppingCart.
In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one.
'''
class ShoppingCart (object):
def __init__(self):
self.total = 0
self.items = {}
def add_item(self,item_name ,quantity ,price):
self.total =self.total + price
self.items[item_name]=quantity
def remove_item(self,item_name ,quantity,price):
del self.items[item_name]
self.total = self.total - price
value=0
for k,v in self.items.items():
value += v
if (quantity > value ):
self.items.clearAll()
def checkout(self,cash_paid):
if (cash_paid < self.total):
print ("Cash paid not enough ")
else:
self.balance= cash_paid - self.total
print ("Total amount for the goods below ",self.total)
print (self.items)
print ("The arrears after payment is ",self.balance)
def show_details(self):
print (self.items)
class Shop(ShoppingCart):
'''If you wanted the constructor to be handled by the ->>
super constructor
super.(ShoppingCart,self).__init__(item_name ,quantity ,price)
'''
def __init__(self):
self.quantity=100
#Overriding the remove_item
def remove_item(self):
self.quantity =- 1
sh=ShoppingCart()
sh.add_item("Cars",30,3452.34)
sh.add_item("Computer",20,3452.34)
sh.add_item("Movies",20,34523.34)
sh.add_item("Papers",10,1000)
sh.remove_item("Papers",10,1000)
sh.show_details()
sh.checkout(80000)
|
e604fb50261893929a57a9377d7e7b0e11a9b851 | georgeyjm/Sorting-Tests | /sort.py | 2,686 | 4.34375 | 4 | def someSort(array):
'''Time Complexity: O(n^2)'''
length = len(array)
comparisons, accesses = 0,0
for i in range(length):
for j in range(i+1,length):
comparisons += 1
if array[i] > array[j]:
accesses += 1
array[i], array[j] = array[j], array[i]
return array, comparisons, accesses
def insertionSort(array):
'''Time Complexity: O(n^2)'''
length = len(array)
comparisons, accesses = 0,0
for i in range(length):
for j in range(i):
comparisons += 1
if array[j] > array[i]:
accesses += 1
array.insert(j,array[i])
del array[i+1]
return array, comparisons, accesses
def selectionSort(array):
'''Time Complexity: O(n^2)'''
length = len(array)
comparisons, accesses = 0,0
for i in range(length-1):
min = i
for j in range(i+1,length):
comparisons += 1
if array[j] < array[min]:
accesses += 1
min = j
array[i], array[min] = array[min], array[i]
return array, comparisons, accesses
def bubbleSort(array):
'''Time Complexity: O(n^2)'''
length = len(array)
comparisons, accesses = 0,0
for i in range(length-1):
for j in range(length-1,i,-1):
comparisons += 1
if array[j] < array[j-1]:
accesses += 1
array[j], array[j-1] = array[j-1], array[j]
return array, comparisons, accesses
def mergeSort(array,comparisons=0,accesses=0):
'''Or is it quick sort??'''
if len(array) == 1: return array, comparisons, accesses
result = []
middle = len(array) // 2
left, comparisons, accesses = mergeSort(array[:middle],comparisons,accesses)
right, comparisons, accesses = mergeSort(array[middle:],comparisons,accesses)
leftIndex, rightIndex = 0,0
while leftIndex < len(left) and rightIndex < len(right):
comparisons += 1
if left[leftIndex] > right[rightIndex]:
result.append(right[rightIndex])
rightIndex += 1
else:
result.append(left[leftIndex])
leftIndex += 1
result += left[leftIndex:] + right[rightIndex:]
return result, comparisons, accesses
def bogoSort(array):
'''Time Complexity: O(1) (best), O(∞) (worst)'''
from random import shuffle
comparisons, accesses = 0,0
while True:
for i in range(1, len(array)):
comparisons += 1
if array[i] < array[i-1]: break
else:
break
shuffle(array)
accesses += 1
return array, comparisons, accesses
|
c444e7a76a76479c82d08818bcdb38b51cfe073e | 4dasha45/COM411 | /basics/data_visuialisation/function/ascii_code.py | 238 | 4.09375 | 4 | print("program started")
print("Please enter a standard character:")
word=input()
if (len(word)==1):
print("th ascii code for {}is {}".format(word,ord(word)))
else:
print("A single character was expected")
print("end the program") |
4f4431799d2dc9cf46e296cf132e3f77bdeffc3d | asiskc/python_assignment_jan5 | /student.py | 1,030 | 3.875 | 4 | class CheckError():
def __init__(self,roll):
if(roll>24):
raise NameError()
dict = {
1: "student1",
2: "student2"
}
choice = 1
while (choice==1):
try:
choice = int(input("choose an option"))
if (choice == 1):
roll = int(input("roll no:"))
name = input("name: ")
CheckError(roll)
dict.update({roll: name})
elif (choice == 2):
roll = int(input("roll no.: "))
print(dict[roll])
elif (choice == 3):
del dict
except KeyError:
print("Roll no. does not exist")
except NameError:
print("cannot accomadate more than 24 students")
except ValueError:
print("enter an ingteger roll no.")
except TypeError:
print("students list doesnot exist")
else:
print("Error occured")
finally:
loop = input("would you like to continue? (yes/no)")
if(loop == "yes"):
choice=1
else:
choice=0
|
7c314615e75b8f7f02f68c040f50f854bcb8e1cb | jilljenn/tryalgo | /tryalgo/knapsack.py | 3,210 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Knapsack
jill-jênn vie et christoph dürr - 2015-2019
"""
# snip{
def knapsack(p, v, cmax):
"""Knapsack problem: select maximum value set of items if total size not
more than capacity
:param p: table with size of items
:param v: table with value of items
:param cmax: capacity of bag
:requires: number of items non-zero
:returns: value optimal solution, list of item indexes in solution
:complexity: O(n * cmax), for n = number of items
"""
n = len(p)
opt = [[0] * (cmax + 1) for _ in range(n + 1)]
sel = [[False] * (cmax + 1) for _ in range(n + 1)]
# --- basic case
for cap in range(p[0], cmax + 1):
opt[0][cap] = v[0]
sel[0][cap] = True
# --- induction case
for i in range(1, n):
for cap in range(cmax + 1):
if cap >= p[i] and opt[i-1][cap - p[i]] + v[i] > opt[i-1][cap]:
opt[i][cap] = opt[i-1][cap - p[i]] + v[i]
sel[i][cap] = True
else:
opt[i][cap] = opt[i-1][cap]
sel[i][cap] = False
# --- reading solution
cap = cmax
solution = []
for i in range(n-1, -1, -1):
if sel[i][cap]:
solution.append(i)
cap -= p[i]
return (opt[n - 1][cmax], solution)
# snip}
def knapsack2(p, v, cmax):
"""Knapsack problem: select maximum value set of items if total size not
more than capacity.
alternative implementation with same behavior.
:param p: table with size of items
:param v: table with value of items
:param cmax: capacity of bag
:requires: number of items non-zero
:returns: value optimal solution, list of item indexes in solution
:complexity: O(n * cmax), for n = number of items
"""
n = len(p)
# Plus grande valeur obtenable avec objets ≤ i et capacité c
pgv = [[0] * (cmax + 1) for _ in range(n)]
for c in range(cmax + 1): # Initialisation
pgv[0][c] = v[0] if c >= p[0] else 0
pred = {} # Prédécesseurs pour mémoriser les choix faits
for i in range(1, n):
for c in range(cmax + 1):
pgv[i][c] = pgv[i - 1][c] # Si on ne prend pas l'objet i
pred[(i, c)] = (i - 1, c)
# Est-ce que prendre l'objet i est préférable ?
if c >= p[i] and pgv[i - 1][c - p[i]] + v[i] > pgv[i][c]:
pgv[i][c] = pgv[i - 1][c - p[i]] + v[i]
pred[(i, c)] = (i - 1, c - p[i]) # On marque le prédécesseur
# On pourrait s'arrêter là, mais si on veut un sous-ensemble d'objets
# optimal, il faut remonter les marquages
cursor = (n - 1, cmax)
chosen = []
while cursor in pred:
# Si la case prédécesseur a une capacité inférieure
if pred[cursor][1] < cursor[1]:
# C'est qu'on a ramassé l'objet sur le chemin
chosen.append(cursor[0])
cursor = pred[cursor]
if cursor[1] > 0: # A-t-on pris le premier objet ?
# (La première ligne n'a pas de prédécesseur.)
chosen.append(cursor[0])
return pgv[n - 1][cmax], chosen
|
5f5e2d3f7bf5b6e1553e8c10d331d5d4143346af | jilljenn/tryalgo | /tryalgo/gauss_jordan.py | 2,290 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Linear equation system Ax=b by Gauss-Jordan
jill-jenn vie et christoph durr - 2014-2018
"""
__all__ = ["gauss_jordan", "GJ_ZERO_SOLUTIONS", "GJ_SINGLE_SOLUTION",
"GJ_SEVERAL_SOLUTIONS"]
# snip{
# pylint: disable=chained-comparison
def is_zero(x): # tolerance
"""error tolerant zero test
"""
return -1e-6 < x and x < 1e-6
# replace with x == 0 si we are handling Fraction elements
GJ_ZERO_SOLUTIONS = 0
GJ_SINGLE_SOLUTION = 1
GJ_SEVERAL_SOLUTIONS = 2
def gauss_jordan(A, x, b):
"""Linear equation system Ax=b by Gauss-Jordan
:param A: m by n matrix
:param x: table of size n
:param b: table of size m
:modifies: x will contain solution if any
:returns int:
0 if no solution,
1 if solution unique,
2 otherwise
:complexity: :math:`O(n^2m)`
"""
n = len(x)
m = len(b)
assert len(A) == m and len(A[0]) == n
S = [] # put linear system in a single matrix S
for i in range(m):
S.append(A[i][:] + [b[i]])
S.append(list(range(n))) # indices in x
k = diagonalize(S, n, m)
if k < m:
for i in range(k, m):
if not is_zero(S[i][n]):
return GJ_ZERO_SOLUTIONS
for j in range(k):
x[S[m][j]] = S[j][n]
if k < n:
for j in range(k, n):
x[S[m][j]] = 0
return GJ_SEVERAL_SOLUTIONS
return GJ_SINGLE_SOLUTION
def diagonalize(S, n, m):
"""diagonalize """
for k in range(min(n, m)):
val, i, j = max((abs(S[i][j]), i, j)
for i in range(k, m) for j in range(k, n))
if is_zero(val):
return k
S[i], S[k] = S[k], S[i] # swap lines k, i
for r in range(m + 1): # swap columns k, j
S[r][j], S[r][k] = S[r][k], S[r][j]
pivot = float(S[k][k]) # without float if Fraction elements
for j in range(k, n + 1):
S[k][j] /= pivot # divide line k by pivot
for i in range(m): # remove line k scaled by line i
if i != k:
fact = S[i][k]
for j in range(k, n + 1):
S[i][j] -= fact * S[k][j]
return min(n, m)
# snip}
|
1204ef8366837b66f591ff142e663df7302c87b5 | jilljenn/tryalgo | /tryalgo/graph01.py | 1,275 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Shortest path in a 0,1 weighted graph
jill-jenn vie et christoph durr - 2014-2018
"""
from collections import deque
# snip{
def dist01(graph, weight, source=0, target=None):
"""Shortest path in a 0,1 weighted graph
:param graph: directed graph in listlist or listdict format
:param weight: matrix or adjacency dictionary
:param int source: vertex
:param target: exploration stops once distance to target is found
:returns: distance table, predecessor table
:complexity: `O(|V|+|E|)`
"""
n = len(graph)
dist = [float('inf')] * n
prec = [None] * n
black = [False] * n
dist[source] = 0
gray = deque([source])
while gray:
node = gray.pop()
if black[node]:
continue
black[node] = True
if node == target:
break
for neighbor in graph[node]:
ell = dist[node] + weight[node][neighbor]
if black[neighbor] or dist[neighbor] <= ell:
continue
dist[neighbor] = ell
prec[neighbor] = node
if weight[node][neighbor] == 0:
gray.append(neighbor)
else:
gray.appendleft(neighbor)
return dist, prec
# snip}
|
322e307335af2bdf4474d2f78117c867668243ef | jilljenn/tryalgo | /tryalgo/levenshtein.py | 817 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Levenshtein edit distance
jill-jenn vie et christoph durr - 2014-2018
"""
# snip{
def levenshtein(x, y):
"""Levenshtein edit distance
:param x:
:param y: strings
:returns: distance
:complexity: `O(|x|*|y|)`
"""
n = len(x)
m = len(y)
# Create the table A
# Row 0 and column 0 are initialized as required
# The remaining entries will be overwritten during the computation
A = [[i + j for j in range(m + 1)] for i in range(n + 1)]
for i in range(n):
for j in range(m):
A[i + 1][j + 1] = min(A[i][j + 1] + 1, # insert
A[i + 1][j] + 1, # delete
A[i][j] + int(x[i] != y[j])) # subst.
return A[n][m]
# snip}
|
eea13b5f1c5f7a88cbba2d5a56e5101de59a96dd | jilljenn/tryalgo | /tryalgo/dijkstra.py | 2,886 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Shortest paths by Dijkstra
jill-jênn vie et christoph dürr - 2015-2018
"""
# pylint: disable=wrong-import-position
from heapq import heappop, heappush
from tryalgo.our_heap import OurHeap
# snip{
def dijkstra(graph, weight, source=0, target=None):
"""single source shortest paths by Dijkstra
:param graph: directed graph in listlist or listdict format
:param weight: in matrix format or same listdict graph
:assumes: weights are non-negative
:param source: source vertex
:type source: int
:param target: if given, stops once distance to target found
:type target: int
:returns: distance table, precedence table
:complexity: `O(|V| + |E|log|V|)`
"""
n = len(graph)
assert all(weight[u][v] >= 0 for u in range(n) for v in graph[u])
prec = [None] * n
black = [False] * n
dist = [float('inf')] * n
dist[source] = 0
heap = [(0, source)]
while heap:
dist_node, node = heappop(heap) # Closest node from source
if not black[node]:
black[node] = True
if node == target:
break
for neighbor in graph[node]:
dist_neighbor = dist_node + weight[node][neighbor]
if dist_neighbor < dist[neighbor]:
dist[neighbor] = dist_neighbor
prec[neighbor] = node
heappush(heap, (dist_neighbor, neighbor))
return dist, prec
# snip}
# snip{ dijkstra_update_heap
# snip}
# snip{ dijkstra_update_heap
def dijkstra_update_heap(graph, weight, source=0, target=None):
"""single source shortest paths by Dijkstra
with a heap implementing item updates
:param graph: adjacency list or adjacency dictionary of a directed graph
:param weight: matrix or adjacency dictionary
:assumes: weights are non-negatif and weights are infinite for non edges
:param source: source vertex
:type source: int
:param target: if given, stops once distance to target found
:type target: int
:returns: distance table, precedence table
:complexity: `O(|V| + |E|log|V|)`
"""
n = len(graph)
assert all(weight[u][v] >= 0 for u in range(n) for v in graph[u])
prec = [None] * n
dist = [float('inf')] * n
dist[source] = 0
heap = OurHeap([(dist[node], node) for node in range(n)])
while heap:
dist_node, node = heap.pop() # Closest node from source
if node == target:
break
for neighbor in graph[node]:
old = dist[neighbor]
new = dist_node + weight[node][neighbor]
if new < old:
dist[neighbor] = new
prec[neighbor] = node
heap.update((old, neighbor), (new, neighbor))
return dist, prec
# snip}
|
1f90271814c98307cdfb0dc1111f011c619498ba | eliaskousk/example-code-2e | /24-class-metaprog/setattr/example_from_leo.py | 340 | 3.71875 | 4 | #!/usr/bin/env python3
class Foo:
@property
def bar(self):
return self._bar
@bar.setter
def bar(self, value):
self._bar = value
def __setattr__(self, name, value):
print(f'setting {name!r} to {value!r}')
super().__setattr__(name, value)
o = Foo()
o.bar = 8
print(o.bar)
print(o._bar)
|
a82eb08a4de5bab1c90099a414eda670219aeb95 | eliaskousk/example-code-2e | /21-async/mojifinder/charindex.py | 2,445 | 4.15625 | 4 | #!/usr/bin/env python
"""
Class ``InvertedIndex`` builds an inverted index mapping each word to
the set of Unicode characters which contain that word in their names.
Optional arguments to the constructor are ``first`` and ``last+1``
character codes to index, to make testing easier. In the examples
below, only the ASCII range was indexed.
The `entries` attribute is a `defaultdict` with uppercased single
words as keys::
>>> idx = InvertedIndex(32, 128)
>>> idx.entries['DOLLAR']
{'$'}
>>> sorted(idx.entries['SIGN'])
['#', '$', '%', '+', '<', '=', '>']
>>> idx.entries['A'] & idx.entries['SMALL']
{'a'}
>>> idx.entries['BRILLIG']
set()
The `.search()` method takes a string, uppercases it, splits it into
words, and returns the intersection of the entries for each word::
>>> idx.search('capital a')
{'A'}
"""
import sys
import unicodedata
from collections import defaultdict
from collections.abc import Iterator
STOP_CODE: int = sys.maxunicode + 1
Char = str
Index = defaultdict[str, set[Char]]
def tokenize(text: str) -> Iterator[str]:
"""return iterator of uppercased words"""
for word in text.upper().replace('-', ' ').split():
yield word
class InvertedIndex:
entries: Index
def __init__(self, start: int = 32, stop: int = STOP_CODE):
entries: Index = defaultdict(set)
for char in (chr(i) for i in range(start, stop)):
name = unicodedata.name(char, '')
if name:
for word in tokenize(name):
entries[word].add(char)
self.entries = entries
def search(self, query: str) -> set[Char]:
if words := list(tokenize(query)):
found = self.entries[words[0]]
return found.intersection(*(self.entries[w] for w in words[1:]))
else:
return set()
def format_results(chars: set[Char]) -> Iterator[str]:
for char in sorted(chars):
name = unicodedata.name(char)
code = ord(char)
yield f'U+{code:04X}\t{char}\t{name}'
def main(words: list[str]) -> None:
if not words:
print('Please give one or more words to search.')
sys.exit(2) # command line usage error
index = InvertedIndex()
chars = index.search(' '.join(words))
for line in format_results(chars):
print(line)
print('─' * 66, f'{len(chars)} found')
if __name__ == '__main__':
main(sys.argv[1:])
|
a04924cd0fc7da072413c4062f8a2a1258f58e32 | eliaskousk/example-code-2e | /05-data-classes/dataclass/coordinates.py | 512 | 3.5625 | 4 | """
``Coordinate``: simple class decorated with ``dataclass`` and a custom ``__str__``::
>>> moscow = Coordinate(55.756, 37.617)
>>> print(moscow)
55.8°N, 37.6°E
"""
# tag::COORDINATE[]
from dataclasses import dataclass
@dataclass(frozen=True)
class Coordinate:
lat: float
lon: float
def __str__(self):
ns = 'N' if self.lat >= 0 else 'S'
we = 'E' if self.lon >= 0 else 'W'
return f'{abs(self.lat):.1f}°{ns}, {abs(self.lon):.1f}°{we}'
# end::COORDINATE[]
|
f23ba5514189ed232eeaaf3cd6a4ea8fb799864e | eliaskousk/example-code-2e | /20-executors/getflags/slow_server.py | 3,986 | 3.515625 | 4 | #!/usr/bin/env python3
"""Slow HTTP server class.
This module implements a ThreadingHTTPServer using a custom
SimpleHTTPRequestHandler subclass that introduces delays to all
GET responses, and optionally returns errors to a fraction of
the requests if given the --error_rate command-line argument.
"""
import contextlib
import os
import socket
import time
from functools import partial
from http import server, HTTPStatus
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler
from random import random, uniform
MIN_DELAY = 0.5 # minimum delay for do_GET (seconds)
MAX_DELAY = 5.0 # maximum delay for do_GET (seconds)
class SlowHTTPRequestHandler(SimpleHTTPRequestHandler):
"""SlowHTTPRequestHandler adds delays and errors to test HTTP clients.
The optional error_rate argument determines how often GET requests
receive a 418 status code, "I'm a teapot".
If error_rate is .15, there's a 15% probability of each GET request
getting that error.
When the server believes it is a teapot, it refuses requests to serve files.
See: https://tools.ietf.org/html/rfc2324#section-2.3.2
"""
def __init__(self, *args, error_rate=0.0, **kwargs):
self.error_rate = error_rate
super().__init__(*args, **kwargs)
def do_GET(self):
"""Serve a GET request."""
delay = uniform(MIN_DELAY, MAX_DELAY)
cc = self.path[-6:-4].upper()
print(f'{cc} delay: {delay:0.2}s')
time.sleep(delay)
if random() < self.error_rate:
# HTTPStatus.IM_A_TEAPOT requires Python >= 3.9
try:
self.send_error(HTTPStatus.IM_A_TEAPOT, "I'm a Teapot")
except BrokenPipeError as exc:
print(f'{cc} *** BrokenPipeError: client closed')
else:
f = self.send_head()
if f:
try:
self.copyfile(f, self.wfile)
except BrokenPipeError as exc:
print(f'{cc} *** BrokenPipeError: client closed')
finally:
f.close()
# The code in the `if` block below, including comments, was copied
# and adapted from the `http.server` module of Python 3.9
# https://github.com/python/cpython/blob/master/Lib/http/server.py
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--bind', '-b', metavar='ADDRESS',
help='Specify alternate bind address '
'[default: all interfaces]')
parser.add_argument('--directory', '-d', default=os.getcwd(),
help='Specify alternative directory '
'[default:current directory]')
parser.add_argument('--error-rate', '-e', metavar='PROBABILITY',
default=0.0, type=float,
help='Error rate; e.g. use .25 for 25%% probability '
'[default:0.0]')
parser.add_argument('port', action='store',
default=8001, type=int,
nargs='?',
help='Specify alternate port [default: 8001]')
args = parser.parse_args()
handler_class = partial(SlowHTTPRequestHandler,
directory=args.directory,
error_rate=args.error_rate)
# ensure dual-stack is not disabled; ref #38907
class DualStackServer(ThreadingHTTPServer):
def server_bind(self):
# suppress exception when protocol is IPv4
with contextlib.suppress(Exception):
self.socket.setsockopt(
socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
return super().server_bind()
# test is a top-level function in http.server omitted from __all__
server.test( # type: ignore
HandlerClass=handler_class,
ServerClass=DualStackServer,
port=args.port,
bind=args.bind,
)
|
d2977b7a63a6f0bebe59544ccaf8fc1763570d1c | eliaskousk/example-code-2e | /05-data-classes/typing_namedtuple/coordinates.py | 487 | 3.765625 | 4 | """
``Coordinate``: a simple ``NamedTuple`` subclass with a custom ``__str__``::
>>> moscow = Coordinate(55.756, 37.617)
>>> print(moscow)
55.8°N, 37.6°E
"""
# tag::COORDINATE[]
from typing import NamedTuple
class Coordinate(NamedTuple):
lat: float
lon: float
def __str__(self):
ns = 'N' if self.lat >= 0 else 'S'
we = 'E' if self.lon >= 0 else 'W'
return f'{abs(self.lat):.1f}°{ns}, {abs(self.lon):.1f}°{we}'
# end::COORDINATE[]
|
06b96c803dcc6f53a2db59b8ba48e68c47e4df33 | anqi117/py-study | /namecard-func.py | 2,341 | 3.703125 | 4 | card_infor = []
def print_menu():
print("="*50)
print(" 名片系统 v1.0")
print("1. add a new card")
print("2. delete a card")
print("3. update a card")
print("4. search a card")
print("5. show all of cards")
print("6. exit")
print("="*50)
def add_new_card_info():
new_name = input("name: ")
new_qq = input("qq: ")
new_wechat = input("wechat: ")
new_addr = input("addr: ")
new_infor = {}
new_infor['name'] = new_name
new_infor['qq'] = new_qq
new_infor['wechat'] = new_wechat
new_infor['addr'] = new_addr
# 将一个字典添加到列表中
global card_infor
card_infor.append(new_infor)
print(card_infor)
def delete_card():
flag = 0
target_card_name = input("please input the name you want to delete:")
for i, card in enumerate(card_infor):
if card['name'] == target_card_name:
del card_infor[i]
print(card_infor)
flag = 1
if flag == 0:
print("Card can not be found")
def update_card_info():
flag = 0
target_card_name = input("please input the name you want to update:")
for card in card_infor:
if card['name'] == target_card_name:
card['qq'] = input("please input a new qq: ")
card['wechat'] = input("please input a new wechat: ")
card['addr'] = input("please input a new addr: ")
flag = 1
print("update successd!\n")
print("%s\t%s\t%s\t%s"%(card['name'], card['qq'], card['wechat'], card['addr']))
break
if flag == 0:
print("Card can not be found.")
def search_card():
"""search a card by name"""
search_name = input("name: ")
global card_infor
for card in card_infor:
if card['name'] == search_name:
print(card)
break
else:
print("There is not a data about %s."%search_name)
def show_all_card():
print("%s\t%s\t%s\t%s"%("name", "qq", "wechat", "addr"))
global card_infor
for card in card_infor:
print("%s\t%s\t%s\t%s"%(card['name'],card['qq'],card['wechat'],card['addr']))
def main():
#1 打印功能提示
print_menu()
while True:
#2 获取用户输入
num = int(input("Please input a function number: "))
#3 根据用户的数据执行相对应的功能
if num==1:
add_new_card_info()
elif num==2:
delete_card()
elif num==3:
update_card_info()
elif num==4:
search_card()
elif num==5:
show_all_card()
elif num==6:
break
else:
print("Please input correct number.")
print("")
main()
|
50dc5fc8bf4ec94682c5d984b9e57cb46b35fc28 | hcmMichaelTu/python | /lesson08/sqrt_cal2.py | 793 | 3.859375 | 4 | import math
def Newton_sqrt(x):
y = x
for i in range(100):
y = y/2 + x/(2*y)
return y
def cal_sqrt(method, method_name):
print(f"Tính căn bằng phương pháp {method_name}:")
print(f"a) Căn của 0.0196 là {method(0.0196):.9f}")
print(f"b) Căn của 1.21 là {method(1.21):.9f}")
print(f"c) Căn của 2 là {method(2):.9f}")
print(f"d) Căn của 3 là {method(3):.9f}")
print(f"e) Căn của 4 là {method(4):.9f}")
print(f"f) Căn của {225/256} là {method(225/256):.9f}")
cal_sqrt(math.sqrt, "math’s sqrt")
cal_sqrt(lambda x: pow(x, 0.5), "built-in pow")
cal_sqrt(lambda x: math.pow(x, 0.5), "math’s pow")
cal_sqrt(lambda x: x ** 0.5, "exponentiation operator")
cal_sqrt(Newton_sqrt, "Newton’s sqrt")
|
dd7145fa02abd11c3490fa783f40f8b696c8261e | hcmMichaelTu/python | /lesson12/turtle_draw.py | 336 | 3.78125 | 4 | import turtle as t
t.shape("turtle")
d = 20
actions = {"L": 180, "R": 0, "U": 90, "D": 270}
while ins := input("Nhập chuỗi lệnh cho con rùa (L, R, U, D): "):
for act in ins:
if act in actions:
t.setheading(actions[act])
else:
continue
t.forward(d)
print("Done!")
|
01b471090a34326b7c1c1a898ec5a25a9dbb0164 | hcmMichaelTu/python | /lesson04/string_format.py | 165 | 3.640625 | 4 | import math
r = float(input("Nhập bán kính: "))
c = 2 * math.pi * r
s = math.pi * r**2
print("Chu vi là: %.2f" % c)
print("Diện tích là: %.2f" % s)
|
87b04bf978a40493536c104be127f2ff83c55f74 | hcmMichaelTu/python | /lesson18/Sierpinski_carpet.py | 684 | 3.71875 | 4 | import pygame
def Sierpinski(x0, y0, w, level):
if level == stop_level:
return
for i in range(3):
for j in range(3):
if i == 1 and j == 1:
pygame.draw.rect(screen, WHITE, (x0 + w//3, y0 + w//3, w//3, w//3))
else:
Sierpinski(x0 + i*w//3, y0 + j*w//3, w//3, level + 1)
width = 600
stop_level = 5
WHITE = (255, 255, 255)
PINK = (255, 192, 203)
pygame.init()
screen = pygame.display.set_mode((width, width))
pygame.display.set_caption("Sierpinski carpet")
screen.fill(PINK)
Sierpinski(0, 0, width, 0)
pygame.display.update()
input("Press Enter to quit. ")
pygame.quit()
|
71fb5ab35539839f8d8810bbd26003f5ba605ee2 | hcmMichaelTu/python | /lesson12/turtle_escape.py | 328 | 3.828125 | 4 | import turtle as t
import random
t.shape("turtle")
d = 20
actions = {"L": 180, "R": 0, "U": 90, "D": 270}
while (abs(t.xcor()) < t.window_width()/2 and
abs(t.ycor()) < t.window_height()/2):
direction = random.choice("LRUD")
t.setheading(actions[direction])
t.forward(d)
print("Congratulations!")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.