blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b77d9ad34b7ca42a441be75c4ba747a1e68f905a | Techbanerg/TB-learn-Python | /02_DataTypes/List/list_comprehension.py | 700 | 4.34375 | 4 | # This short course breaks down Python list comprehensions for yuo step by step
# see how python's comprehensions can be transformed from and to equivalent for loops
# so you wil know exactly what's going on behind the scenes
# one of the favorite features in Python are list comprehension.
# they can seem a bit arcane at first but when you break them down
# they are actually very simple constructs.
# list comprehensions
squares = [x * x for x in range(10)]
add = [x + x for x in range(5)]
slist = ['sachin', 'sourav', 'dravid']
list1 = [item for item in slist if item.startswith('s')]
# Best practices to use list comprehensions
# values = [ expression]
print(add)
print(squares)
print(list1) | true |
83e6ff6c51fbe4792d8436a147a9891d9b7fcb4c | sub7ata/Pattern-Programs-in-Python | /pattern13.py | 224 | 4.125 | 4 | """
Example:
Enter the number of rows: 5
A
B B
C C C
D D D D
E E E E E
"""
n = int(input("Enter the number of rows: "))
for i in range(1, n + 1):
for j in range(1, i + 1):
print(chr(64 + i), end=" ")
print()
| false |
34e73359d26da46aa90d3ac78717f9e134eba568 | sub7ata/Pattern-Programs-in-Python | /pattern73.py | 248 | 4.21875 | 4 | """
Example:
Enter a number: 5
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
"""
num = int(input("Enter a number: "))
for i in range(1, num+1):
print(" "*(i-1),end=" ")
for j in range(1,num+2-i):
print(num+2-i-j,end=" ")
print() | false |
fdd01f4e6ed62cfca31426b445134f69cc65e62b | sub7ata/Pattern-Programs-in-Python | /pattern27.py | 261 | 4.25 | 4 | """
Example:
Enter the number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
"""
n = int(input("Enter the number of rows: "))
for i in range(1, n + 1):
print(" "*(n - i), end=" ")
for j in range(1, i + 1):
print(j, end=" ")
print()
| false |
97e50ce2795bf7e6ac149ab76ab97f147209d5a2 | sub7ata/Pattern-Programs-in-Python | /pattern41.py | 296 | 4.125 | 4 | """
Example:
Enter the number of rows: 5
A
A B C
A B C D E
A B C D E F G
A B C D E F G H I
"""
n = int(input("Enter the number of rows: "))
for i in range(1, n + 1):
print(" "*(n - i), end=" ")
for j in range(65, 65 + 2 * i - 1):
print(chr(j), end=" ")
print()
| false |
df46645a243da1227b13c372061a61fb59cc9576 | sub7ata/Pattern-Programs-in-Python | /pattern62.py | 314 | 4.1875 | 4 | """
Example:
Enter a number: 5
4
3 4
2 3 4
1 2 3 4
0 1 2 3 4
1 2 3 4
2 3 4
3 4
4
"""
num = int(input("Enter a number: "))
for i in range(1,num+1):
for j in range(1,i+1):
print(num-i+j-1,end=" ")
print()
for a in range(1,num+1):
for k in range(0, num-a):
print(k+a,end=" ")
print()
| false |
9160b2901c50fe7aa9e901598409315daf832b98 | sub7ata/Pattern-Programs-in-Python | /pattern12.py | 215 | 4.25 | 4 | """
Example:
Enter the number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
"""
n = int(input("Enter the number of rows: "))
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j, end=" ")
print()
| true |
d07265f2a6bb6fe86770efa6d3d67d680d0c6c41 | VishalGupta2597/techopy | /multi_userinput.py | 1,753 | 4.15625 | 4 | #try:
Hin, Eng, Maths, Phy, Che=input("Enter the marks").split(",")
print(Hin, Eng, Maths, Phy, Che)
print(int(Hin) + int(Eng) + int(Maths) + int(Phy) + int(Che))
"""print("Student Result : ")
Hin = int(input("Enter the marks of Hindi : "))
if Hin < 0 or Hin > 100:
raise ValueError("Marks cannot be more than zero")
Eng = int(input("Enter the marks of English : "))
if Eng < 0 or Eng > 100:
raise ValueError("Marks cannot be less than zero and more than Hundred ")
Maths = int(input("Enter the marks of Mathematics : "))
if Maths < 0 or Maths > 100:
raise ValueError("Marks cannot be less than zero and more than Hundred ")
Phy = int(input("Enter the marks of Physics : "))
if 0< Eng > 100:
raise ValueError("Marks cannot be less than zero and more than Hundred ")
Che = int(input("Enter the marks of Chemistry : "))
if 0 < Che > 100:
raise ValueError("Marks cannot be less than zero and more than Hundred ")
total_marks = Hin + Eng + Maths + Phy + Che
print("Total marks obtained by Student ", total_marks)
percentage = (total_marks * 100) / 500
print("Student gets ", percentage, "% marks")
if percentage < 33:
print("Student is Fail")
elif percentage >= 33 and percentage < 45:
print("Student pass with third division")
elif percentage >= 45 and percentage < 60:
print("Student pass with second division")
else:
print("Student pass with First division")
except ValueError as error:
print("You cannot enter invalid input --> This error is : ", error)
except Exception as e: # for unknown error
print("This error is called : ", e)
finally:
print("Thanks for the result.")"""
| false |
e41d6ea1c9c686ebaa71f250f3f790360f03c48e | Dmach12/GeekBrainsTutorial-Python_lessons_basic | /less_1_home_1.py | 1,002 | 4.1875 | 4 | #1) Поработайте с переменными, создайте несколько,
# выведите на экран, запросите у пользователя
# несколько чисел и строк и сохраните в переменные,
# выведите на экран.
a = 1
print(a)
b = - 2
print(b)
print(a-b)
c = input('Введите Ваше имя и фамилию')
print(c)
print(a, c)
print(a + c)
name = input('Введите Ваше имя и фамилию: ')
position = input('Введите Вашу должность:')
experience = input('Введите Ваш стаж: ')
print(f'Гражданин {name} работает в должности {position} {experience} лет')
sent = 'Грачи прилетели'
data = input('Введите когда прилетели грачи: ')
number = int(input('Введите сколько прилетело грачей: '))
print(f' {sent} {data}: {number} птицы')
| false |
03da85580e8cdc8e967f94677a5837c31e8bf245 | HanChaun/driving | /driving.py | 420 | 4.1875 | 4 | country = input('Which country are you from:')
age = input('pls input your age:')
age = int(age)
if country == 'Taiwan':
if age >= 16 :
print('you can test for Driving Licence ')
else:
print('you can not test for Driving Licence ')
elif country == 'USA':
if age >= 16 :
print('you can test for Driving Licence ')
else:
print('you can not test for Driving Licence ')
else:
print('please input Taiwan or USA') | false |
3cdfd9358e1fd875787b179dff332289f293304a | ashley-honn/homework2- | /solution1.py | 444 | 4.15625 | 4 | # solutions
##This is for Solution 1
#Titles for cells
cell_1 = 'Number'
cell_2 = 'Square'
cell_3 = 'Cube'
space = '20'
align = ' '
#This will print titles for all cells
print(f'{cell_1 :{align}>{space}}',f'{cell_2 :{align}>{space}}',f'{cell_3 :{align}>{space}}')
num = 0
#This will print number, squared, and cubed from range 0 to 6
for num in range (0, 6):
print(f'{num :{space}}',f'{num*num :{space}}',f'{num*num*num :{space}}')
| true |
369ec93632634b50b84c774397449edfbf1b4332 | SmiththeHacker/tehnikum_domashka | /domashka3/task3.py | 593 | 4.15625 | 4 | print('Здравствуйте, я программа, которая умеет писать ваш список наоборот')
print()
print('Давайте для начала добавим данные в список. Введите "stop", когда решите остановиться')
base = []
while True:
x = input()
base.append(x)
print(base)
print('Добавим что-то еще?')
if x == 'stop':
break
del base[-1]
print()
print('Это ваша база')
print(base)
print('А это она наоброт')
base.reverse()
print(base)
| false |
b34a8ceb62caf8cf858f8cb987890ed60d48fa2f | itchyporcupine/Project-Euler-Solutions | /problems/problem1.py | 538 | 4.28125 | 4 | """
If we list all of the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6, and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
http://www.projecteuler.net/index.php?section=problems&id=1
"""
def problem_1():
print "The sum of all natural numbers below 1000 that are multiples of 3 and 5 is %d" % sum(filter(multiple_of_3_or_5, range(1, 1000)))
def multiple_of_3_or_5(n):
"""Returns true if n is divisible by 3 or 5"""
return (not (n%3)) or (not (n%5))
| true |
7a8ba86d03fd50adc54e8950c416c4dc466bb251 | prepiscak/beatson_rosalind | /id_HAMM/RS/006_Rosalind_HAMM.py | 2,367 | 4.125 | 4 | #!/usr/bin/env python3
'''
Counting Point Mutations
Problem
Given two strings s and t of equal length, the Hamming distance between s and t, denoted dH(s,t), is the number of corresponding symbols that differ in s and t.
Given: Two DNA strings s and t of equal length (not exceeding 1 kbp).
Return: The Hamming distance dH(s,t).
'''
import os
import re
def allowed_match(strg, search=re.compile(r'[^GCTA.]').search):
return not bool(search(strg))
def hamm(s, t):
dH = 0
for l in range(0, len(s)):
if s[l] != t[l]:
dH += 1
return dH
def test():
test_s = "GAGCCTACTAACGGGATA"
test_t = "CATCGTAATGACGGCCTG"
print(test_s)
print(test_t)
print("Hamming Distance:")
print(hamm(test_s, test_t))
def inputSequence():
s_i = input("Input first sequence ")
t_i = input("Input second sequence: ")
if s_i == 'q' or t_i == 'q':
print("Quiting")
exit()
elif len(s_i) != len(t_i):
print("Sequences of different length. Please re-enter")
inputSequence()
elif allowed_match(s_i) or allowed_match(t_i):
print("Illegal characters in sequence. Please re-enter")
inputSequence()
else:
print(hamm(s_i, t_i))
def check_file(lst):
if len(lst[0]) != len(lst[1]):
return False
elif allowed_match(lst[0]) or allowed_match(lst[1]):
return False
else:
return True
def main():
fn = input("Please enter path, 'test' for test data, 'input' to input sequences or 'q' to quit\n")
if fn == 'test':
test()
elif fn == 'input':
inputSequence()
elif fn == 'q':
exit()
else:
# Check file exists and if so load in data
exists = os.path.isfile(fn)
if exists:
# Store configuration file values
print("File found")
# Load data and split into two
with open(fn, 'r') as fhand:
dt = fhand.read().split('\n')
#check_file(dt)
if True:
print("Hamming Distance:")
print(hamm(dt[0], dt[1]))
else:
print("Sorry, problem with sequences in file")
main()
else:
print("Sorry, couldn't find the file.")
print()
main()
main() | true |
1f769ec8e3df1f204b67776026c50589b3623163 | bhupathirajuravivarma/positive-numbers-in-a-range | /positivenoinrange.py | 523 | 4.3125 | 4 |
#positive numbers in lists
list1 = [6,-7,5,3,-1]
for num in list1: #using membership operator to check if value exists in 'list1'& iterating each element in list.
if num>=0: #checking for positive number in list.
print(num,end=" ")
print("\n")
list2=[2,14,-45,3]
for num in list2: #using membership operator to check if value exists in 'list2'.
if num>=0: #checking for positive number in list.
print(num,end=" ")
| true |
39169e30f904bb9755256220e758e17e2b2afe67 | stoneand2/python-washu-2014 | /day2/clock2.py | 1,330 | 4.21875 | 4 | class Clock():
def __init__(self, hours, minutes=00):
self.hours = hours # this is an instance variable, able to be accessed anywhere you call self
self.minutes = minutes
@classmethod #instead of self, the first thing we access is the class itself
def at(cls, hours, minutes=00):
return cls(hours, minutes) # basically, same as return Clock(...)
def __add__(self, number):
hour_time = self.hours
minute_time = self.minutes
if number + minute_time < 60:
minute_time = minute_time + number
elif number + minute_time > 60:
minute_time = (number + minute_time) - 60 #### won't work if over 120
hour_time = hour_time + ((number + minute_time) / 60)
else:
pass
if hour_time > 23:
hour_time = (hour_time) - 24
else:
pass
self.hours = hour_time
self.minutes = minute_time
return self # lets you use self.hours and self.minutes in the __str__ method
def __str__(self):
hour_time2 = self.hours
minute_time2 = self.minutes
string_hour = str(hour_time2)
string_minute = str(minute_time2)
if len(string_hour) == 1:
string_hour = "0" + string_hour
else:
pass
if len(string_minute) == 1:
string_minute = ":0" + string_minute
else:
pass
return string_hour + string_minute
clock = Clock.at(23) + 3
print clock.__str__() | true |
6624b10758eae9ab14ca93e6b309731311f167b3 | Charles1104/Codewars | /cube.py | 240 | 4.125 | 4 | def cube_odd(arr):
sum = 0
for i, k in enumerate(arr):
if isinstance(k, (int, float, complex)):
if k%2 != 0:
sum += pow(k, 3)
else:
return None
return sum
if __name__ == "__main__":
cube_odd([1,2,3,4]) | false |
14653072f7d31ba1164f26ecbb20c324046ddb66 | ayanakshi/journaldev | /Python-3/basic_examples/leap_year.py | 321 | 4.15625 | 4 | try:
print('Please enter year to check for leap year')
year = int(input())
except ValueError:
print('Please input a valid year')
exit(1)
if year % 400 == 0:
print('Leap Year')
elif year % 100 == 0:
print('Not Leap Year')
elif year % 4 == 0:
print('Leap Year')
else:
print('Not Leap Year') | false |
6e948d96919febbb19d304897276e6ab366960d5 | ayanakshi/journaldev | /Python-3/basic_examples/float_function.py | 617 | 4.59375 | 5 | # init a string with the value of a number
str_to_float = '12.60'
# check the type of the variable
print('The type of str_to_float is:', type(str_to_float))
# use the float() function
str_to_float = float(str_to_float)
# now check the type of the variable
print('The type of str_to_float is:', type(str_to_float))
print('\n')
# init an integer
int_to_float = '12.60'
# check the type of the variable
print('The type of int_to_float is:', type(int_to_float))
# use the float() function
int_to_float = float(int_to_float)
# now check the type of the variable
print('The type of int_to_float is:', type(int_to_float))
| true |
ecb48a4e1889f6e7a88dfaf1bcea829668c3e6e9 | doanthanhnhan/learningPY | /01_fundamentals/04_functions/03_built_in_functions.py | 1,051 | 4.40625 | 4 | # Strings
# Search
# a_string.find(substring, start, end)
random_string = "This is a string"
print(random_string.find("is")) # First instance of 'is' occurs at index 2
print(random_string.find("is", 9, 13)) # No instance of 'is' in this range
# Replace
# a_string.replace(substring_to_be_replace, new_string)
a_string = "Welcome to Educative!"
new_string = a_string.replace("Welcome to", "Greetings from")
print(a_string)
print(new_string)
# Changing the Letter Case
# In Python, the letter case of a string can be easily changed using the upper() and lower() methods.
print("UpperCase".upper())
print("LowerCase".lower())
# Type Conversions
print(int("12") * 10) # String to integer
print(int(20.5)) # Float to integer
print(int(False)) # Bool to integer
# print (int("Hello")) # This wouldn't work!
print(ord('a'))
print(ord('0'))
print(float(24))
print(float('24.5'))
print(float(True))
print(str(12) + '.345')
print(str(False))
print(str(12.345) + ' is a string')
print(bool(10))
print(bool(0.0))
print(bool("Hello"))
print(bool(""))
| true |
d999f45998e7e623f150f3fcad477524da21ee0a | doanthanhnhan/learningPY | /02_oop/04_polymorphism/06_abstract_base_classes.py | 561 | 4.3125 | 4 | from abc import ABC, abstractmethod
class Shape(ABC): # Shape is a child class of ABC
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Square(Shape):
def __init__(self, length):
self.length = length
def area(self):
return (self.length * self.length)
def perimeter(self):
return (4 * self.length)
shape = Shape()
# this will code will not compile since Shape has abstract methods without
# method definitions in it
square = Square(4)
print(square)
| true |
e9aba8cf06774f9232d5b242efef69fb799f3e76 | doanthanhnhan/learningPY | /01_fundamentals/04_functions/02_function_scope.py | 1,561 | 4.78125 | 5 | # Data Lifecycle
# In Python, data created inside the function cannot be used from the outside
# unless it is being returned from the function.
# Variables in a function are isolated from the rest of the program. When the function ends,
# they are released from memory and cannot be recovered.
name = "Ned"
def func():
name = "Stark"
func()
print(name) # The value of 'name' remains unchanged.
# Altering Data
# When mutable data is passed to a function, the function can modify or alter it.
# These modifications will stay in effect outside the function scope as well.
# An example of mutable data is a list.
# In the case of immutable data, the function can modify it,
# but the data will remain unchanged outside the function’s scope.
# Examples of immutable data are numbers, strings, etc.
num = 20
def multiply_by_10(n):
n *= 10
num = n # Changing the value inside the function
print("Value of num inside function:", num)
return n
multiply_by_10(num)
print("Value of num outside function:", num) # The original value remains unchanged
# So, it’s confirmed that immutable objects are unaffected by the working of a function.
# If we really need to update immutable variables through a function,
# we can simply assign the returning value from the function to the variable.
num_list = [10, 20, 30, 40]
print(num_list)
def multiply_by_10(my_list):
my_list[0] *= 10
my_list[1] *= 10
my_list[2] *= 10
my_list[3] *= 10
return my_list
multiply_by_10(num_list)
print(num_list) # The contents of the list have been changed
| true |
6191157eb90cbf6b994c06b80b884695b36e9f01 | doanthanhnhan/learningPY | /02_oop/01_classes_and_objects/12_exercise_01.py | 490 | 4.375 | 4 | """
Square Numbers and Return Their Sum
Implement a constructor to initialize the values of three properties: x, y, and z.
Implement a method, sqSum(), in the Point class which squares x, y, and z and returns their sum.
Sample Properties
1, 3, 5
Sample Method Output
35
"""
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def sqSum(self):
return self.x ** 2 + self.y ** 2 + self.z ** 2
test = Point(1, 3, 5)
print("Sum: ", test.sqSum()) | true |
be2d9d9f1ea11a20209c8d2e816452567dd3114b | carolinetm82/MITx-6.00.1x | /Python_week2/week2_pbset2_pb1.py | 1,305 | 4.21875 | 4 | """
Problem 1 - Paying Debt off in a Year
Write a program to calculate the credit card balance after one year
if a person only pays the minimum monthly payment required by the credit
card company each month.
The following variables contain values as described below:
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
monthlyPaymentRate - minimum monthly payment rate as a decimal
For each month, calculate statements on the monthly payment and remaining
balance.At the end of 12 months, print out the remaining balance.
"""
balance = 484
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
monthlyInterestRate = annualInterestRate/12
for n in range(12):
# Compute the monthly payment, based on the previous month’s balance
minimumMonthlyPayment = monthlyPaymentRate * balance
# Update the outstanding balance by removing the payment
monthlyUnpaidBalance = balance - minimumMonthlyPayment
# then charging interest on the result
UpdatedBalance = monthlyUnpaidBalance + (monthlyInterestRate*monthlyUnpaidBalance)
print('Month', n+1, 'Remaining balance:',round(UpdatedBalance,2))
balance=UpdatedBalance
print('Remaining balance at the end of the year:',round(UpdatedBalance,2))
| true |
69f67048cf25a900a9eb5fa3f444c2c42f0cfb40 | sarozzx/Python_practice | /Functions/18.py | 205 | 4.3125 | 4 | # Write a Python program to check whether a given string is number or not
# using Lambda.
check_number = lambda x:True if x.isnumeric() else False
a=str(input("Enter a string "))
print(check_number(a)) | true |
0743869ff6c47e458db2290981671f555b539794 | sarozzx/Python_practice | /Functions/2.py | 247 | 4.125 | 4 | # Write a Python function to sum all the numbers in a list.
def sum1(list):
return sum(list)
list =[]
n=int(input("Enter number of items in list"))
for i in range(0,n):
x=int(input())
list.append(x)
print("THe sum is ",sum1(list)) | true |
971c857b14a11f193b4e814f8844854e587d0b0f | sarozzx/Python_practice | /Data Structures/27.py | 430 | 4.25 | 4 | # Write a Python program to replace the last element in a list with another list.
def con_list(list1,list2):
list1[-1:]=list2
return list1
list1 =[]
n=int(input("Enter number of items in list1"))
for i in range(0,n):
x=str(input())
list1.append(x)
list2 =[]
n=int(input("Enter number of items in list2"))
for i in range(0,n):
x=str(input())
list2.append(x)
list1=con_list(list1,list2)
print(list1) | true |
ab919b511392475452595c0610cb72f6ca0525a4 | sarozzx/Python_practice | /Functions/9.py | 376 | 4.1875 | 4 | # Write a Python function that takes a number as a parameter and check the
# number is prime or not.
def prime1(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x==0):
return False
return True
x=int(input("Enter a number to check if its prime "))
print(prime1(x)) | true |
19bcef6d7e895e153eebe00dcd434e88b340058b | sarozzx/Python_practice | /Data Structures/38.py | 296 | 4.21875 | 4 | # Write a Python program to remove a key from a dictionary.
dict1 = {}
n=int(input("Enter number of items in dictionary"))
for i in range(n):
x=str(input("key"))
y=str(input("value"))
dict1[x]=y
print(dict1)
q=str(input("which key do u wanna remove"))
del dict1[q]
print(dict1)
| true |
464c3eecf884c6008379552d1bfe2e151a140b4b | sarozzx/Python_practice | /Functions/5.py | 320 | 4.28125 | 4 | # Write a Python function to calculate the factorial of a number (a non-negative
# integer). The function accepts the number as an argument.
def facto(x):
if(x==0):
return 0
if(x==1):
return 1
return x*facto(x-1)
y=int(input("Enter a number : "))
print("The factorial of ",y,"is",facto(y)) | true |
1d0d4598b8477da1f94808a2bea06a28e3211a09 | sarozzx/Python_practice | /Data Structures/23.py | 312 | 4.28125 | 4 | # Write a Python program to check a list is empty or not.
def check_emp(list):
if not list:
print("it is an empty list")
else:
print("it is not an empty list")
list =[]
n=int(input("Enter number of items in list"))
for i in range(0,n):
x=input()
list.append(x)
check_emp(list) | true |
56e9001a79d3810a3b29fb33e3d37e79d27b7732 | starmap0312/refactoring | /dealing_with_generalization/pull_up_constructor_body.py | 1,457 | 4.34375 | 4 | # - if there are identical constructors in subclasses
# you can pull up to superclass constructor and call superclass constructor from subclass constructor
# - if see common behaviors in normal methods of subclasses, consider to pull them up to superclass
# ex. if the common behaviors are in constructors, you need to pull them up to superclass contructors
# you need to call them from subclass constructors unless the subclass construction does nothing
# before: identical constructors in subclasses
class Employee(object):
def __init__(self):
self._name = None
self._id = None
class Manager(Employee):
# subclass
def __init__(self, name, id, grade):
self._name = name
self._id = id
self._grade = grade
class Engineer(Employee):
# subclass
def __init__(self, name, id, grade):
self._name = name
self._id = id
self._grade = grade
engineer = Engineer('John', '15321', '85')
print engineer._name, engineer._id, engineer._grade
# after: pull up constructor to superclass
class Employee(object):
# superclass
def __init__(self, name, id):
self._name = name
self._id = id
class Engineer(Employee):
# subclass
def __init__(self, name, id, grade):
super(Engineer, self).__init__(name, id)
self._grade = grade
engineer = Engineer('John', '15321', '85')
print engineer._name, engineer._id, engineer._grade
| true |
fb1b1e73c7d5311e36eb7f1fd8d2cddd9ad9fb7b | starmap0312/refactoring | /simplifying_conditional_expressions/introduce_null_object.py | 722 | 4.15625 | 4 | # - if you have repeated checks for a null value, then replace the null value with a null object
# - if one of your conditional cases is a null, use introduce null object
# before: use conditionals
class Customer(object):
# abstract class
def getPlan(self):
raise NotImplementedError
# client has a conditional that handles the null case
if customer is None:
plan = doSomething()
else:
plan = customer.getPlan()
# after: add null object in which it performs doSomething(), thus the conditional can be removed
class NullCustomer(Customer):
def getPlan(self):
doSomething()
# simplified code: client uses polymorphism that is able to perform the null case
plan = customer.getPlan()
| true |
79f5435bbcf2bd7b757b6e2f1a0da40e4bf82836 | starmap0312/refactoring | /composing_method/introduce_explaining_variable.py | 930 | 4.4375 | 4 | # - if have a complicated expression that is hard to understand, put the result of the expression
# or parts of the expression in a temp variable with a name explaining its purpose
# - an alternative is to use extract method, but sometimes extract method is hard,
# because there are too many local temp variables then use introduce explaining variables
platform = 'MAC'
browser = 'IE'
# before: long expression
if platform.upper().index('MAC') > -1 and browser.upper().index('IE') > -1:
print 'MAC and IE'
# after: use temp variables to explain parts of the expression
isMac = platform.upper().index('MAC') > -1
isIE = browser.upper().index('IE') > -1
if isMac and isIE:
print 'MAC and IE'
# use extract method instead
def isMac(platform):
return platform.upper().index('MAC') > -1
def isIE(browser):
return browser.upper().index('IE') > -1
if isMac(platform) and isIE(browser):
print 'MAC and IE'
| true |
18164044687548ed741c2d8833149e564f708fa1 | shmishkat/PythonForEveryone | /Week05/forLoopDic.py | 436 | 4.21875 | 4 | #for loop in dictionaries.
countsofNames = {'sarowar': 1, 'hossain': 2, 'mishkat': 2, 'mishu': 2}
for key in countsofNames:
print(key,countsofNames[key])
#converting dictionary to list
nameList = list(countsofNames)
print(nameList)
print(countsofNames.keys())
print(countsofNames.values())
print(countsofNames.items())
#Cool thing!!
#Muiltiple iteration variables!!
for key,value in countsofNames.items():
print(key,value) | true |
4d29c7a19f10bd73b6c7a132e8024bf92e0de176 | tanmay2298/Expenditure_Management | /database.py | 1,715 | 4.3125 | 4 | import sqlite3
from datetime import date # get todays date
def create_table():
conn = sqlite3.connect("Expenditure.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS Expenditure(ID INTEGER PRIMARY KEY, expenditure_date text, Item text, Cost real)")
conn.commit()
conn.close()
def insert_data(expenditure_date, item, cost):
conn = sqlite3.connect("Expenditure.db")
cur = conn.cursor()
cur.execute("INSERT INTO Expenditure VALUES (NULL, ?, ?, ?)", (expenditure_date, item, cost))
conn.commit()
conn.close()
def display_data():
conn = sqlite3.connect("Expenditure.db")
cur = conn.cursor()
cur.execute("SELECT * FROM Expenditure")
data = cur.fetchall()
conn.close()
for i in data:
print(i)
def prompt_database():
while True:
print()
print("1) Make an entry for today")
print("2) Any other date")
print()
n = int(input("Enter your choice: "))
if n == 1:
Expenditure_Date = str(date.today())
print(Expenditure_Date)
break
elif n == 2:
Expenditure_Date = input("Enter the date: ")
break
else:
print("Invalid Choice\n", "Retry")
return Expenditure_Date
def main_function():
create_table()
Expenditure_Date = prompt_database()
item = input("Expenditure on which Item: ")
cost = float(input("Cost of the Item: "))
print("Expenditure_Date: ", Expenditure_Date)
print("Item: ", item)
print("Cost: ", cost)
insert_data(Expenditure_Date, item, cost)
print()
print("CAUTION: PLEASE MAKE SURE THAT YOUR DATABASE IS NOT OPEN \nELSEWHERE IN SOME DB VIEWING APPLICATION")
print("....... Data Successfully Entered in Database ........")
print()
ch = input("Do you want to see the data: ")
if (ch == 'Y') or (ch == 'y'):
display_data()
| true |
c183d38420f2103fa6eb54b8698f2128e45238a1 | zhaopeiyang/PythonLearning | /python_180905_迭代器.py | 955 | 4.28125 | 4 |
# 可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。
# 生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。
# 把list、dict、str等Iterable变成Iterator可以使用iter()函数
# 你可能会问,为什么list、dict、str等数据类型不是Iterator?
# 这是因为Python的Iterator对象表示的是一个数据流,
# Iterator对象可以被next()函数调用并不断返回下一个数据,
# 直到没有数据时抛出StopIteration错误。
# 可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列的长度,
# 只能不断通过next()函数实现按需计算下一个数据,
# 所以Iterator的计算是惰性的,只有在需要返回下一个数据时它才会计算。
# Iterator甚至可以表示一个无限大的数据流,例如全体自然数。而使用list是永远不可能存储全体自然数的。 | false |
e587c00fe271c502b50586b227f077929c609af2 | FaisalRehman234/Basic-Calculator | /Basic Python Calculator.py | 1,015 | 4.21875 | 4 | import argparse
parser=argparse.ArgumentParser(
description='''Select Operators by choosing options '1, 2, 3 & 4'. ''',
epilog="""Author: Faisal Rehman.""")
args=parser.parse_args()
print("Type '-h' or '--help' to show help")
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
num1: int = int(input("Enter a Number: "))
print("Select Operator Below.")
print("1- Addition")
print("2- Subtraction")
print("3- Multiplication")
print("4- Division")
ope = input("Enter Operator Number: ")
num2 = int(input("Enter Another Number: "))
if ope == '1':
print("Your Answer Is: ", num1, '+', num2, "=", add(num1, num2))
elif ope == '2':
print("Your Answer Is: ", num1, "-", num2, "=", subtract(num1, num2))
elif ope == '3':
print("Your Answer Is: ", num1, "x", num2, "=", multiply(num1, num2))
elif ope == '4':
print("Your Answer Is: ", num1, "÷", num2, "=", divide(num1, num2))
else:
print("Wrong input!")
| false |
d6944aa05f2adbb15f1eeeca1bc0713cb8e0000a | geoniju/PythonLearning | /Basics/DictEx1.py | 422 | 4.15625 | 4 |
""""
Write a program that reads words in words.txt and stores them as keys in a dictionary.
It doesnt matter what the values are.
Then you can use the in operator to check whether a string is in the dictionary.
"""
fhand = open('words.txt')
word_dict = dict()
for line in fhand:
words = line.split()
for word in words:
if word not in word_dict.keys():
word_dict[word] = ''
print(word_dict)
| true |
df562ec851108571c9c64114e44b38088a5ca605 | lucas-deschamps/LearnPython-exercises | /ex6.py | 948 | 4.40625 | 4 | types_of_people = 10
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
print(f"I said: {x}")
print(f"I also said: '{y}'")
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {} {}"
print(joke_evaluation.format(types_of_people, do_not))
w = "This is the left side of..."
e = "a string with a right side."
print(w + e)
# types_of_people = 10 creates a variable named types_of_people
# and sets it = (equal) to 10.
# You can put that in any string with: {types_of_people}.
# You also see that I have to use a special type of string to "format";
# it's called an "f-string"
# Python also has another kind of formatting using the .format() syntax
# which you see on line 17.
# You'll see me use that sometimes
# when I want to apply a format to an already created string, such as in a loop.
| true |
6be6ef4eec51a80a29e1516c6c4e074ccb64f5f7 | lucas-deschamps/LearnPython-exercises | /ex38.py | 1,772 | 4.25 | 4 | ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("\nWait, there are not 10 things in that list. Let's fix that.\n")
# splits string into a list @ emptyspaces
stuff = ten_things.split(' ')
# 8 items in the list, but ten_things only needs 4 more
more_stuff = ['Day', 'Night', 'Song', 'Frisbee',
'Corn', 'Banana', 'Girl', 'Boy']
# while loop only adds enough until 10 by popping items of the other list
while len(stuff) != 10:
print(stuff)
print(more_stuff)
next_one = more_stuff.pop()
print("Adding: ", next_one)
stuff.append(next_one)
print(more_stuff)
print(f"There are {len(stuff)} items now.")
print(stuff)
print('\n')
print("There we go: ", stuff, '\n')
print("Let's do some things with stuff:\n")
print(stuff[1]) # prints item #1 in combined list
print(stuff[-1]) # prints last item in combined list
print(stuff.pop()) # pops last item in the list
print(' '.join(stuff)) # prints list by the way of joining them with empty spcs
print('#'.join(stuff[3:6])) # prints list from item 3 to 5 by the way of '#'
print(stuff, '\n')
##Study Drills
# Take each function that is called, and go through the steps for function calls
# to translate them to what Python does.
# For example, more_stuff.pop() is pop(more_stuff).
# Translate these two ways to view the function calls in English.
# For example, more_stuff.pop() reads as, "Call pop on more_stuff."
# Meanwhile, pop(more_stuff) means, "Call pop with argument more_stuff."
# Understand how they are really the same thing.
# Go read about "object-oriented programming" online. Confused?
# I was too. Do not worry.
# You will learn enough to be dangerous, and you can slowly learn more later.
| true |
68ab6e0241554dd0677be30bb3a47066104df38c | 18101555672/LearnPython | /JM_Python/python_01.py | 1,413 | 4.15625 | 4 | print('hello world')
# 基础
# 更详细的格式化方法
print('{:-^40}'.format('更详细的格式化方法'))
# 对于浮点数‘0.333’保留小数点后三位
print('{:.3f}'.format(1.0/3))
# 使用指定符号填充文本,并保持文字处于中间位置
print('{:^11}'.format('hello'))
print('{:_^11}'.format('hello'))
print('{:0^11}'.format('hello'))
# 基于关键词输出
print('{name} wrote {book}'.format(name='Swaroop',book='A Byte of Python'))
# 使用end指定print函数以什么结尾(默认为 \n 换行符)
print('{:-^40}'.format('使用end指定print函数的结尾'))
print('a',end='')
print('b')
print('a',end='|')
print('b',end='|')
print('c')
# 转义序列
print('{:-^40}'.format('转义序列'))
print('This is the first line\nThis is the second line')
print('This is the first sentence.\
This is the second sentence.')
# 原始字符串
print('{:-^40}'.format('原始字符串'))
print(R'Newlines are indicated by \n')
print(r'Newlines are indicated by \n')
# 变量命名规则(标识符)
print('{:-^40}'.format('变量命名规则(标识符)'))
print('''1.第一个字符必须是字母表中的字母(大写ASCII字符或小写ASCII字符或者Unicode字符)或下划线
2.标识符的其他部分可以由字符(大写ASCII字符或小写ASCII字符或者Unicode字符)、下划线(_)、数字(0-9)组成
3.标识符名称区分大小写''')
| false |
bdeddd92cfaed29ffe474b9ce8130046597fcc82 | DhivyaKavidasan/python | /problemset_3/q7.py | 421 | 4.40625 | 4 | '''
function named uses_only that takes a word and a string of letters, and that returns True if the word contains only letters in the list
submitted by : dhivya.kavidasan
date: 05/12/2017
'''
def uses_only(word, only_letters):
i = 0
while i <len(word):
if word[i] in only_letters:
i+=1
else:
return False
return True
word='dhivya'
only_letters='xyz'
print uses_only(word,only_letters) | true |
403d1aa48cd5b2505b7fde211ba0e0bbb9b0cd20 | DhivyaKavidasan/python | /problemset_3/q10.py | 659 | 4.15625 | 4 | '''
function called is_anagram that takes two strings and returns True if they are anagrams
submitted by:dhivya.kavidasan
date: 06/12/2017
'''
def is_anagram(list1,list2):
list3=[]
list4=[]
list1.sort()
list2.sort()
for i in list1:
list3.append(i)
for j in list2:
list4.append(j)
c=(''.join(list3))
d=(''.join(list4))
if c==d :
return True
else:
return False
str1=raw_input("enter STRING 1")
list1=[]
for i in str1:
list1.append(i)
str2=raw_input("enter STRING 2")
list2=[]
for i in str2:
list2.append(i)
print is_anagram(list1,list2)
| false |
8914f54cf44b5bfcab97d30db464ecbb58e4b15b | wesleyendliche/Python_exercises | /World_2/039militaryservice.py | 592 | 4.15625 | 4 | from datetime import date
ano = int(input('Digite o ano de seu nascimento: '))
sexo = str(input('Você é HOMEM ou MULHER? Digite H ou M. ')).upper()
idade = date.today().year - ano
if idade == 18 and sexo == 'h':
print('Você está com 18 anos. Deve se alistar IMEDIATAMENTE!')
elif idade < 18 and sexo == 'h':
print('Você está com {} e deve se alistar daqui a {} anos'.format(idade, 18-idade))
elif sexo == 'M':
print('No Brasil, mulheres não precisam se alistar.')
else:
print('Você está com {} anos. Já deveria ter se alistado há {} anos!'.format(idade, idade-18))
| false |
cdefa6f65d75c76a213a108b0223122b72b30a2f | morrosquin/aleandelebake | /crypto/caesar.py | 385 | 4.125 | 4 |
from helpers import alphabet_position, rotate_char
def encrypt (text, rot):
encrypted_text = ""
for characters in text:
encrypted_text += rotate_char(characters, rot)
return encrypted_text
def main():
text = input('Enter your message: ')
rotation = int(input('Enter rotation: '))
print(encrypt(text, rotation))
if __name__ == "__main__":
main() | true |
89d25d50b13a4ee345ba2aeee3b4f4f2063e0947 | tiveritz/coding-campus-lessons-in-python | /src/dcv/oct/day09part01.py | 695 | 4.3125 | 4 | def bubble_sort(arr):
sorted = arr.copy()
to_swap = True
while to_swap:
to_swap = False
for i in range(1, len(arr)):
if (sorted[i - 1] > sorted[i]):
to_swap = True
sorted[i - 1], sorted[i] = sorted[i], sorted[i - 1]
return sorted
def hello_world_functions():
my_array = [6, 23, 78, 34, 89, 2, 56, 78, 6, 30, 27, 81, 7, 7, 84, 20]
# function call. Note the passed parameter (my_array)
print(bubble_sort(my_array))
print(my_array) # original array remained untouched
# Another example
my_array2 = [-2, -9, 5, 9, 5, 2, 4, -3, 8, -6, 4, 6]
print(bubble_sort(my_array2))
print(my_array2)
| true |
e98f57cc800492598ded6a914a801cd2f78cf846 | tiveritz/coding-campus-lessons-in-python | /src/dcv/sept/day06.py | 2,030 | 4.1875 | 4 | from math import ceil
def hello_world_recursion(n):
# Recherchiere Recursion
if (n == 0):
print("End of Recursion")
else:
print("Recursion number " + str(n))
n -= 1
hello_world_recursion(n)
# Declare global variables for sorting algorithm
compare_counter = 0
swap_counter = 0
def merge_sort():
# Informiere dich über den MergeSort Sortieralgorithmus und setze
# sie in Python um.
# Vergleiche auch die Komplexität, indem du bei jedem Zugriff auf das
# Array einen Counter erhöhst und diesen am Ende mit ausgiebst.
arr = [6, 23, 78, 34, 89, 2, 56, 78, 6, 30, 27, 81, 7, 7, 84, 20, 19]
print(arr)
print(merge_sort_algorithm(arr))
print("Comparisons: " + str(compare_counter))
print("Swaps: " + str(swap_counter))
def merge_sort_algorithm(arr):
sorted_arr = arr
global compare_counter
global swap_counter
if (len(arr) > 1):
half_index = ceil(len(arr) / 2)
left, right = [], []
for i in range(half_index):
left.append(sorted_arr[i])
for j in range(half_index, len(arr)):
right.append(arr[j])
left = merge_sort_algorithm(left)
right = merge_sort_algorithm(right)
i = 0
j = 0
k = 0
while (k < len(sorted_arr)):
compare_counter += 1
if (i < len(left) and j < len(right)):
if (left[i] < right[j]):
sorted_arr[k] = left[i]
swap_counter += 1
i += 1
else:
sorted_arr[k] = right[j]
swap_counter += 1
j += 1
else:
if (i == len(left)):
sorted_arr[k] = right[j]
swap_counter += 1
j += 1
else:
sorted_arr[k] = left[i]
swap_counter += 1
i += 1
k += 1
return sorted_arr
| false |
0c65b84132465c366b5eb84628cad04d5a80866f | StRobertCHSCS/fabroa-hugoli0903 | /Working/Practice Questions/2.livehack_practice_solution2.py | 896 | 4.46875 | 4 | '''
-------------------------------------------------------------------------------
Name: 2.livehack_practice_solution2.py
Purpose: Determining if the triangle is a right angled
Author: Li.H
Created: 14/11/2019
------------------------------------------------------------------------------
'''
# Receive the side lengths from the user
side_1 = (int(input("Enter the length of Side 1: ")))
side_2 = (int(input("Enter the length of Side 2: ")))
side_3 = (int(input("Enter the length of Side 3: ")))
# Calculate the formula
side_1 = side_1**2
side_2 = side_2**2
side_3 = side_3**2
# Calculate the possibilities
if side_1 + side_2 == side_3:
print("This is a right angled triangle")
elif side_1 + side_3 == side_2:
print("This is a right angled triangle")
elif side_2 + side_3 == side_1:
print("This is a right angled triangle")
else:
print("This is not a right angled triangle") | true |
f0a756e7cdc7e35be0efcc03def4afdd366376e7 | cloudacademy/pythonlp1-lab2-cli | /src/code/YoungestPresident/solution-code/youngest_pres.py | 1,449 | 4.15625 | 4 | #! /usr/bin/python3
import sys
sys.version_info[0]
lab_exercise = "YoungestPresident"
lab_type = "solution-code"
python_version = ("%s.%s.%s" % (sys.version_info[0], sys.version_info[1], sys.version_info[2]))
print("Exercise: %s" % (lab_exercise))
print("Type: %s" % (lab_type))
print("Python: %s\n" % (python_version))
print()
#====================================
#CODE1: Import datetime module
import datetime
#CODE2: Create a date creation helper function
def make_date(date_string):
raw_year, raw_month, raw_day = date_string.split('-')
year = int(raw_year)
month = int(raw_month)
day = int(raw_day)
return datetime.date(year, month, day)
#CODE3: Create empty list
all_presidents = []
#CODE4: Open data file and read each record
with open("./presidents.txt") as PRES:
for rec in PRES:
_, last_name, first_name, birthday, _, _, _, inauguration_day, *_ = rec.split(":")
birth_date = make_date(birthday)
took_office_date = make_date(inauguration_day)
raw_age_at_inauguration = took_office_date - birth_date
age_at_inauguration = round(raw_age_at_inauguration.days / 365.25, 1)
full_name = '{} {}'.format(first_name, last_name)
all_presidents.append((age_at_inauguration, full_name))
#CODE5: Loop through sorted list and print out to console
for age, name in sorted(all_presidents):
print(name, age)
| true |
bd3f71a840393b9e85508b627bc234bd20f670bc | CSPon/Workshop_Materials | /Python_Workshop_Files/Works_010.py | 2,236 | 4.34375 | 4 | # Python 2.X workshop
# File: Works_010.py
# Files I/O and Exceptions
# To simply print to the Python shell, use the print keyword
print "Hello, Python!"
print # Empty line
# To read keyboard input within the shell...
print "User input Demo"
string = raw_input("Enter your name: ")
print "Hello, " + string + "!"
print # Empty line
# You can also use 'input' keyword. Difference between raw_input
# is that input only takes valid Python expression
#string = input("Enter your valid Python command: ")
#print string
# To access to a file, you use open() function
filename = "foo.txt"
access_mode = "a+" # Opens file for read and writing
buffering = -1
fileToRead = open(filename, access_mode, buffering)
# file object has different attributes, such as...
print "File Name:", fileToRead.name # Shows name of the file
print "File Mode:", fileToRead.mode # Shows access mode
print "Is File Closed?:", fileToRead.closed # Shows if file is closed
print # Empty line
# To read a file...
aLine = fileToRead.read()
# To read up to specific byte size...
aLine = fileToRead.read(10) # Reads up to 10 bytes
# To write to a file...
print "Writting to foo.txt"
fileToRead.write("Hello World!")
# To check where the current position is...
position = fileToRead.tell()
print "Current Position:", position
# To move the current position within the file...
position = fileToRead.seek(0, 0)
print "Current Position:", position
# To close a file
fileToRead.close()
print # Empty line
# To rename a file
import os
os.rename("foo.txt", "bar.txt")
# To remove a file
os.remove("bar.txt")
# Note the access_mode flag
# r+ allows file to be read and write, with file starting at the beginning
# w is for writting only, and it overwrites from beginning of the file
# w also creates file if file does not exist
# w+ allows file for read and write, overwriting the entire file
# a allows file to be writting, appended from the end of the file
# Exception is used along with try-catch block
try:
aFile = open("Mmm.txt", "r")
except IOError:
print "No such file!"
# If you are not sure which exception is needed, omit the specific exception
try:
aFile = open("bar.txt", "r")
except:
print "No such file!"
# Go to Works_010_Exercise.py
| true |
070f868f26cdeaa2f44ccb0885a9dc5889b1070d | CSPon/Workshop_Materials | /Python_Workshop_Files/Try_Files_Completed/Works_Try_001.py | 644 | 4.125 | 4 | # Python 2.7.X
# Try_001.py
# Modifying the quadratic equation
# Continuing with quadratic equation, modify your code
# So it can check with imaginary numbers
# If 4 * a * c is negative, program must let user know
# quadratic equation is unsolvable
import math
a = 5.0
b = 2.0
c = 10.0
# Write your code here
if ((b**2) - 4 * a * c) < 0:
print "This quadratic function cannot be solved!"
else:
result = -b + math.sqrt((b**2) - 4 * a * c) / (2 * a)
print "-b + sqrt((b**2) - 4 * a * c) / (2 * a) is", result
result = -b - math.sqrt((b**2) - 4 * a * c) / (2 * a)
print "-b - sqrt((b**2) - 4 * a * c) / (2 * a) is", result
| true |
e8af090f30548f575478a7ef18ac554b77bf2dd4 | jonbleibdrey/python-playhouse | /lessons/space/planet.py | 971 | 4.25 | 4 | class Planet:
# class level attribute- has acesss to all instances
shape = "round"
#class methods
#this is allso a decorator and it extends the methods below here.
@classmethod
def commons(cls):
return f"All planets are {cls.shape} becuase of gravity"
#static methods
#this is allso a decorator and it extends the methods below here.
@staticmethod
def spin(speed = " 2000 miles per hour"):
return f"The planet spin and spins at {speed}"
#instint attribute- has acesss to the individual instants created
def __init__(self, name, radius, gravity, system):
self.name = name
self.radius = radius
self.gravity = gravity
self.system = system
def orbit(self):
return f"{self.name} is orbittin in the {self.system}"
# print(f"Name is : {PlanetX.name}")
# print(f"Radius is : {PlanetX.radius}")
# print(f"The gravity is : {PlanetX.gravity}")
# print(PlanetX.orbit())
| true |
009f0354abb393920fd0570f056dab386960f30f | nateychau/leetcode | /medium/430.py | 1,243 | 4.34375 | 4 | # 430. Flatten a Multilevel Doubly Linked List
# You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.
# Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.
# Example 1:
# Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
# Output: [1,2,3,7,8,11,12,9,10,4,5,6]
class Solution:
def flatten(self, head: 'Node') -> 'Node':
if not head:
return head
dummy = prev = Node()
stack = [head]
while stack:
current = stack.pop()
current.prev = prev
prev.next = current
if current.next:
stack.append(current.next)
if current.child:
stack.append(current.child)
current.child = None
prev = current
dummy.next.prev = None
return dummy.next | true |
33457f0033848661c5312884471133f808943b54 | nateychau/leetcode | /medium/735.py | 2,073 | 4.15625 | 4 | # 735. Asteroid Collision
# We are given an array asteroids of integers representing asteroids in a row.
# For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
# Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
# Example 1:
# Input: asteroids = [5,10,-5]
# Output: [5,10]
# Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
# Example 2:
# Input: asteroids = [8,-8]
# Output: []
# Explanation: The 8 and -8 collide exploding each other.
# Example 3:
# Input: asteroids = [10,2,-5]
# Output: [10]
# Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
# Example 4:
# Input: asteroids = [-2,-1,1,2]
# Output: [-2,-1,1,2]
# Explanation: The -2 and -1 are moving left, while the 1 and 2 are moving right. Asteroids moving the same direction never meet, so no asteroids will meet each other.
# Constraints:
# 1 <= asteroids <= 104
# -1000 <= asteroids[i] <= 1000
# asteroids[i] != 0
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
output = [asteroids[0]]
for rock in asteroids[1:]:
if rock < 0:
destroyed = False
while output and output[-1] > 0:
if output[-1] == abs(rock):
output.pop()
destroyed = True
break
elif output[-1] > abs(rock):
destroyed = True
break
else:
output.pop()
if not destroyed:
output.append(rock)
else:
output.append(rock)
return output
| true |
35c0dd06be1544c645f19ff2b6ff101cc04e06c0 | macyryan/lists | /main.py | 1,855 | 4.53125 | 5 | # a list is a sequence of items
# 1D list like a single row or a single column in Excel
# Declare a list using [] and a coma seperated of values
list_ints = [0, 1, 10, 20]
#there are unique indexes for each element in the list
# 0-based, meaning the first element is at zero and the last element is n-1
# where n is the number of elements in this list
# 0 (0), 1 (1), 10 (2), 20(3)
print(list_ints[0])
print(list_ints[-4])
#types can be mixed in a list
list_numbers = [0, 0.0, 1, 1.0, -2]
print(list_numbers)
print(type(list_numbers))
#lists are mutable
list_numbers[0] = "hello"
print(list_numbers)
# ise len() to figure out how many elements are in a list
print(len(list_numbers))
list_numbers.append("another element")
# print out the last element in the list when you dont knoe the number of elements in the list
print(list_numbers[len(list_numbers)-1])
# we can have an empty list
empty_list = []
# we can have lists of lists
nested_list = [[0,1], [2], [3], [4, 5]]
print(len(nested_list))
print(len(nested_list[0]))
# looping through list items
candies = ["twix", "sneakers", "smarties"]
print(candies)
for candy in candies:
print(candy)
i = 0
while i < len(candies):
print(i, candies[i])
i += 1
i = 0
for i in range(len(candies)):
print(i, candies[i])
# common list operators
# list concatenation.. adding two lists together
print(candies)
candies += ["m&ms", "starburst"]
print(candies)
# list repitition... repeating elements in a list
bag_o_candies = 5 * ["twix", "snikers"]
print(bag_o_candies)
#list sclicing
print(candies[1:3]) # : is the slice operator. start index is inclusive
#end index is exclusive
# if you ever need a copy of a list you can simply use the : with no start or end
copy_of_candies = candies[:]
copy_of_candies[0] = "TWIX"
print(copy_of_candies)
print(candies)
#list methods candies.
| true |
08ee5d07cc4cd9fa9ac995979b3ae921875651e9 | eluttrell/string-exercises | /rev.py | 274 | 4.3125 | 4 | # This way works, but is too easy!
# string = raw_input("Give me a string to reverse please\n:")
# print string [::-1]
string = "Hello"
char_list = []
for i in range(len(string) - 1, - 1, - 1):
char list.append(string[i])
#
output = ' '.join(char_list)
print output
| true |
aae92769398e2798c61f59b17eb3e509c1437bfa | Techie-Tessie/Big_O | /linear.py | 766 | 4.28125 | 4 | #Run this code and you should see that as the number of elements
#in the array increases, the time taken to traverse it increases
import time
#measure time taken to traverse small array
start_time = time.time()
array1 = [3,1,4]
for num in array1:
print(num)
print("\n%s seconds" % (time.time() - start_time))
#measure time taken to traverse slightly larger array
start_time = time.time()
array2 = [3,1,4,1,5,9,2]
for num in array2:
print(num)
print("\n%s seconds" % (time.time() - start_time))
#measure time taken to traverse even larger array
start_time = time.time()
array3 = [3,1,4,1,5,9,2,6,5,3,5,8,9,7,9]
for num in array3:
print(num)
print("\n%s seconds" % (time.time() - start_time))
| true |
1bbdf14acb9ddbc2a8d4074b54330152dae6a582 | rajeshkr2016/training | /chapter2_list_map_lambda_list_comprehension/51_loopin1.py | 681 | 4.40625 | 4 | #When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
# To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print('What is your {0}? It is {1}.'.format(q, a))
#To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.
for i in reversed(range(1, 11, 1)):
print(i)
| true |
436590717e700ec74574b56332a1023362f73ee7 | rajeshkr2016/training | /chapter4_class_method_inheritance_override_polymorphism/3_method_1.py | 585 | 4.625 | 5 | '''
The Constructor Method
The constructor method is used to initialize data.
It is run as soon as an object of a class is instantiated.
Also known as the __init__ method, it will be the first definition of a class and looks like this:
'''
class Shark:
def __init__(self):
print("This is the constructor method.")
def swim(self, b):
print("The shark is swimming.", b)
def be_awesome(self):
print("The shark is being awesome.")
def main():
sammy = Shark()
sammy.swim("r")
sammy.be_awesome()
if __name__ == "__main__":
main()
| true |
f781dd47a06f79559ff931a13009f0453944b41c | rajeshkr2016/training | /fib.py | 464 | 4.15625 | 4 | #recurrsive
# big O notation = O(n^2)
def fiboRec(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fiboRec(n-1)+fiboRec(n-2)
#iter
# big O notation = O(n)
def fibIter(n):
a=0
b=1
result=[0]
for i in range(0,n):
a, b = b, a+b
result.append(a)
return a
result = fibIter(6)
print("Iterative Method :",result)
result1 = fiboRec(6)
print("Reccursive Method :", result1)
# 0,1,1,2,3,5 | false |
22ea187f2fe994d8aca2eabeda4ea458af8162b9 | rajeshkr2016/training | /chapter10-Generator_Fibanocci/8-Nested_list_comp.py | 369 | 4.21875 | 4 | #'''
my_list = []
for x in [20, 40, 60]:
for y in [2, 4, 6]:
my_list.append(x * y)
#print(my_list)
my_list = [x * y for x in [20, 40, 60] for y in [2, 4, 6]]
print(my_list)
'''
List comprehensions allow us to transform one list or other sequence into a new list.
They provide a concise syntax for completing this task, limiting our lines of code.
''' | true |
798da748346e83c63566d0a2c24d36aa5467b49e | rajeshkr2016/training | /senthil/primeFactor.py | 768 | 4.1875 | 4 | '''
Given int x, determine the set of prime factors
f(5) = [1,5]
f(6) = [2,3]
f(8) = [2,2,2]
f(10) = [2,5]
1) While n is divisible by 2, print 2 and divide n by 2.
2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n. While i divides n, print i and divide n by i, increment i by 2 and continue.
3) If n is a prime number and is greater than 2, then n will not become 1 by above two steps. So print n if it is greater than 2.
'''
def primefactor(n):
print(n)
if n < 2:
print("The number cannot have prime factors")
while n % 2 == 0:
print("while loop")
print(2)
n = n/2
for i in range(3, n+1, 2):
while (n % i) == 0:
print(i)
n = n / i
n = 10
primefactor(n)
| true |
0a72c3b845963090b651d57389478370565788c8 | rajeshkr2016/training | /chapter2_list_map_lambda_list_comprehension/10_list_comp_if.py | 669 | 4.3125 | 4 | '''
A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses.
The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
For example, this listcomp combines the elements of two lists if they are not equal:
'''
print("Generating List combo with regular method")
list1=[1,2,3]
list2=[3,1,4]
combs = []
for x in list1:
for y in list2:
if x !=y:
combs.append([x,y])
print(combs)
print("Generating List combo with list comprehension")
combs1=[[x, y] for x in list1 for y in list2 if x != y]
print(combs1) | true |
b62b52bbae9fc169f5a809824a2c188174c8101f | sujitdhamale/Python | /0805_slice.py | 1,077 | 4.5 | 4 | #!/usr/bin/python
#0805_slice.py by Sujit Dhamale
#to Understanding Operating on parts of a container with the slice operator
def main():
print("")
list = [1,2,3,4,5,6,7,8,9,10]
print(list)
print(list[0])
print(list[1])
#slice of first 5 item
print("\nSlice of first 5 item ")
print(list[0:5]) #Ranges in python are non inclusive , so 5th element will not print
#Ranges in python are non inclusive
print("\nRanges in python are non inclusive")
for i in range(0, 10):
print(i,end=" ")
list[:]=range(100)
print(list)
#first argument
print("First argument : list[25] :",list[25])
#Second argument in range in the slice is a range
print("Second argument : list[25:50] :",list[25:50])
#third argument will step
print("third argument : list[25:50:5] :",list[25:50:5])
print("We can assign value to slice")
list[25:50:5]=(99, 99, 99, 99, 99)
print("List : ",list)
if __name__ == "__main__": main()
| false |
918a5296584c4fa3192d8debf40cedd8260b4dbd | sujitdhamale/Python | /0802_bitwise_operator.py | 760 | 4.28125 | 4 | #!/usr/bin/python
#0802_bitwise_operator.py by Sujit Dhamale
#to Understanding 0802_bitwise_operator
def main():
print(5)
print(0b0101)
b(5)
x,y=0x55,0xaa
print("X==",end=" ")
b(x)
print("Y==",end=" ")
b(y)
#OR operator
print("\n#OR operator")
b(x | y)
#AND operator
print("\n#AND operator")
b(x & y)
#Exclusive OR operator
print("\n#OR operator")
b(x ^ y)
b(x ^ 0)
b(x ^ 0xff) # All bit's will be filpped
#Shift Operator
print("\n#Shift Operator")
b(x >> 3)
b(x << 3)
def b(n):
print('{:8b}'.format(n)) # {:8b} is format string
if __name__ == "__main__": main()
| false |
09300b989cf42a78381dfd25fa4011cb33f346a0 | sujitdhamale/Python | /0505_Aggregating_lists_and_tuples.py | 892 | 4.5 | 4 | #!/usr/bin/python
#0505_Aggregating_lists_and_tuples.py by SUjit Dhamale
def main():
print("Tuple ") #tuple is immutable object. we cannot insert, append, delete in tuple
x=(1,2,3,4)
print(type(x),x)
print("List") # list is mutable object
x=[1,2,3,4]
print(type(x),x)
#list is mutable object so we can insert, append, delete in list
x.append(5)
print(type(x),x)
x.insert(2,6)
print(type(x),x)
print("String ")
x='string'
print(type(x),x[2])
print(type(x),x[2:4]) # this is slices
#these sequence type can be used as iterators
print("these sequence type can be used as iterators")
x=(1,2,3,4)
for i in x:
print(i)
x=[1,2,3,4]
for i in x:
print(i)
x='string'
for i in x:
print(i)
if __name__ == "__main__": main()
| true |
34863bd0e6251e5a1b22cd2fb68b65747b6bd240 | liucheng2912/py | /leecode/easy/207/1603.py | 660 | 4.125 | 4 | '''
思路:
实现方式:
类定义和构造函数的定义
函数实现:
'''
class ParkingSystem:
def __init__(self,big,medium,small):
self.big=big
self.medium=medium
self.small=small
def addCar(self,carType):
if carType==1:
self.big-=1
return self.big>=0
elif carType==2:
self.medium-=1
return self.medium >=0
elif carType==3:
self.small-=1
return self.small>=0
else:
return False
park=ParkingSystem(1,1,0)
print(park.addCar(1))
print(park.addCar(2))
print(park.addCar(3))
print(park.addCar(1)) | false |
e281a51a657d101f2127c4800eb8c2077f434822 | BogartZZZ/Python-Word-Reverse | /WordReverse.py | 330 | 4.15625 | 4 | #my_string = input("Input a word to reverse: ")
#for char in range(len(my_string) -1, -1, -1):
# print(my_string[char], end="")
def reverseWord(Word):
words = Word.split(" ")
newWords = [word[::-1] for word in words]
newWord = " ".join(newWords)
return newWord
Word = "Can't stop me"
print(reverseWord(Word)) | true |
b999f987b9b161c094cec43815873c38d18d9c66 | PeturOA/2021-3-T-111-PROG | /assignments/while_loops/every_other_int.py | 273 | 4.40625 | 4 | num_int = int(input("Enter a number greater than or equal to 2: ")) # Do not change this line
counter = 2
# Fill in the missing code below
if num_int < 2:
print("The number is too small.")
else:
while counter <= num_int:
print(counter)
counter += 2 | true |
3bde34c682bb98342601b3961eea5df04c152181 | PeturOA/2021-3-T-111-PROG | /assignments/lists_and_tuples/fizzbuzz_sum.py | 289 | 4.15625 | 4 | def main():
max_num = int(input("What should max_num be?: "))
print(fizzbuzz_sum(max_num))
def fizzbuzz_sum(max_num):
return sum([i for i in range(max_num) if i % 3 == 0 and i % 5 == 0])
# Main program starts here - DO NOT change it
if __name__ == "__main__":
main()
| false |
4f6f89f04e828f5d548e1d5784a97e67d78561d3 | PeturOA/2021-3-T-111-PROG | /projects/p5/hex_decimal.py | 2,379 | 4.375 | 4 | PROMPT = "Enter option: "
HEX_LETTERS = 'ABCDEF'
DEC_TO_HEX_OPTION = 'd'
HEX_TO_DEC_OPTION = 'h'
EXIT_OPTION = 'x'
MENU_STR = f"\n{DEC_TO_HEX_OPTION}. Decimal to hex\n{HEX_TO_DEC_OPTION}. Hex to decimal\n{EXIT_OPTION}. Exit\n"
def main():
'''Displays menu, gets input from user and displays result'''
display_menu()
option = input(PROMPT)
while option != EXIT_OPTION:
if option == DEC_TO_HEX_OPTION:
dec_int = int(input("Decimal number: "))
print('The hex is {}'.format(decimal_to_hex_str(dec_int)))
elif option == HEX_TO_DEC_OPTION:
hex_str = input("Hex number: ")
print('The decimal is {}'.format(hex_str_to_decimal(hex_str)))
else:
print("Invalid option!")
display_menu()
option = input(PROMPT)
def display_menu():
'''Shows menu options to the user'''
print(MENU_STR)
def decimal_to_hex_str(dec_int):
'''Return the hex string corresponding to the given decimal number'''
hex_str = ""
while dec_int > 0:
hex_str += decimal_to_hex_chr(dec_int % 16)
dec_int = dec_int // 16
return hex_str[::-1] # reverses the string
def decimal_to_hex_chr(dec_int):
'''Returns the hex char corresponding to the given decimal, or None if invalid'''
if 0 <= dec_int <= 9:
return str(dec_int)
elif 10 <= dec_int <= 15:
return chr(55 + dec_int) # 'A' is chr(65)
return None # Not valid
def hex_str_to_decimal(hex_str):
'''Returns the decimal corresponding to the given hex string.
Return None if the hex string is invalid'''
dec_sum = 0
hex_len = len(hex_str)
for index, hex_chr in enumerate(hex_str):
dec_value = hex_chr_to_decimal(hex_chr)
if dec_value is None:
return None
dec_sum += dec_value * (16 ** (hex_len - index - 1))
return dec_sum
def hex_chr_to_decimal(hex_chr):
'''Returns the decimal corresponding to the given hexadecimal character or None if invalid'''
hex_chr = hex_chr.upper()
if hex_chr.isdigit():
return int(hex_chr)
elif hex_chr in HEX_LETTERS:
return ord(hex_chr) - 55 # ord('A') is 65 and 'A' is 10 in decimal
else:
return None # Not valid
# Main program starts here
if __name__ == "__main__":
main()
| false |
0e5f551d767c513eeaa4c14a635b798555d5d45a | tiannaparmar/Python-Level-2 | /Functions.py | 1,885 | 4.34375 | 4 | #Create new file
#Save as Functions.py
#Save in Python-Level-2 folder ---- repo(repository)
#Add two numbers
def AddNumbers(x,y,z): #Definition of the function
return x + y + z
def GetSquares(x):
return x * x
#Call our Function
Total = AddNumbers(4,9,100)
#Output the results
print(f"The sum total is = {Total}")
#Ask the user for inputs from the keyboard
num1 = int(input("Enter any number \n"))
num2 = int(input("Enter another number \n"))
num3 = int(input("Enter another number again \n"))
#Call the function once again
sum = AddNumbers(num1,num2,num3)
#Print the sum
print("The sum now of {0} plus {1} plus {2} is equal to {3}".format(num1, num2, num3, sum))
#Call the squares function
print(GetSquares(4))
square = GetSquares(16)
print("The square is", square)
#A function that calculates the area of a Circle
def AreaofCircle(r):
PI = 3.142 #declared a constant --- whose values don't change --- static -- uppercase
return (PI * r * r)
#function call
area = AreaofCircle(14)
#display the results
print("The area is =",area)
#function definition
def AreaOfRectangle(): #No parameters
l = eval(input("Enter the value for the length of your rectangle \n")) #prompt user inputs for the length
w = eval(input("Enter the value for the width of your rectangle \n")) #prompt user for width
Area = l * w
print("Area of rectangle is", Area)
#function call
AreaOfRectangle()
#Exercise write a function to calculate the perimeter of rectangle
#Push your code online
def PerimeterOfRectangle():
Length = eval(input("Enter the value for the length of your rectangle \n"))
Width = eval(input("Enter the value for the width of your rectangle \n"))
PerimeterOfRectangle = (Length + Width) * 2
print("Perimeter of rectangle is", PerimeterOfRectangle)
#function call
PerimeterOfRectangle()
| true |
115c846183893a1b02c883fe8418cd0190958d1d | kumarUjjawal/python_problems | /leap_year.py | 349 | 4.28125 | 4 | # Return true if the given input is a leap year else return false.
def leap_year(year):
leap = False
if (year % 4 == 0):
if (year % 100 == 0 and year % 400 == 0):
leap = True
else:
leap = False
else:
leap = False
return leap
years = int(input())
print(leap_year(years))
| true |
ab0a2984cc6b629a578c0e576bd6cd80bfc56ea3 | mharre/pythonds | /RandomExercises/26-Queue.py | 2,994 | 4.15625 | 4 | class Node:
def __init__(self, cargo=None, nextNode=None):
self.cargo = cargo
self.next = nextNode
def __str__(self):
return str(self.cargo)
def print_backward(self):
if self.next is not None:
tail = self.next
tail.print_backward()
print(self.cargo, end=" ")
class LinkedList:
def __init__(self):
self.length = 0
self.head = None
def print_backward(self):
print("[", end=" ")
if self.head is not None:
self.head.print_backward()
def add_first(self, cargo):
node = Node(cargo)
node.next = self.head
# print(self.head)
self.head = node
self.length += 1
# class Queue:
# def __init__(self):
# self.length = 0
# self.head = None
# def is_empty(self):
# return self.length == 0
# def insert(self, cargo):
# node = Node(cargo)
# if self.head is None:
# # If list is empty the new node goes first
# self.head = node
# else:
# # Find the last node in the list
# last = self.head
# while last.next:
# last = last.next
# # Append the new node
# last.next = node
# self.length += 1
# def remove(self):
# cargo = self.head.cargo
# self.head = self.head.next
# self.length -= 1
# return cargo
class Queue:
def __init__(self):
self.length = 0
self.head = None
self.last = None
def is_empty(self):
return self.length == 0
def insert(self, cargo):
node = Node(cargo)
if self.head is None:
# If list is empty the new node goes first
self.head = self.last = node
else:
# Find the last node in the list
last = self.last
#append new node
last.next = node
self.last = node
self.length += 1
def remove(self):
cargo = self.head.cargo
self.head = self.head.next
self.length -= 1
if self.length == 0:
self.last = None
return cargo
class PriorityQueue:
def __init__(self):
self.items = []
def is_empty(self):
return not self.items
def insert(self, item):
self.items.append(item)
def remove(self):
maxi = 0
for i in range(1, len(self.items)):
if self.items[i] > self.items[maxi]:
maxi = i
# print(f'--------------------{maxi}')
# print(f'--------------------{self.items[maxi]}')
item = self.items[maxi]
del self.items[maxi]
return item
q = PriorityQueue()
for num in [11,12,14,13]:
q.insert(num)
while not q.is_empty():
print(q.remove()) | false |
dd0f35d4cb92dafa898193df17b2ce18f21f37de | anaselmi/simple_python | /simple/talkingclock.py | 1,481 | 4.15625 | 4 | def talking_clock(time):
# Gives us hour and minute as ints
hour = int(time[0:2])
minute = int(time[3:])
minute_tens = int(time[3])
minute_ones = int(time[4])
if hour >= 12:
# Gives us our p.m hours in twelve hour time
hour = hour - 12
day_or_night = "pm" # Used to tell if am or p.m
else:
day_or_night = "am" # used to tell if am or pm
# Lists used to turn int to word
hour_list = ["twelve", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
"twelve"]
minute_tens_list = ["oh", "ten", "twenty", "thirty", "forty", "fifty"]
minute_ones_list = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
minute_teens_list = ["", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen"]
hour_word = hour_list[hour] # Hour in words
if minute_tens == 0 and minute_ones == 0:
minute_word = "" # Should be empty if there's no minute at all
elif minute_tens == 1 and minute_ones != 0:
minute_word = minute_teens_list[minute_ones] # This is for when minute is in the teens and not ten
else:
minute_word = minute_tens_list[minute_tens] + " " + minute_ones_list[
minute_ones] + " " # runs in all other scenarios
print("It's %s %s%s" % (hour_word, minute_word, day_or_night))
talking_clock("24:53")
| false |
b9cba0bc0de5e2ea45ab195ae4a756c419bfe1b4 | arbiben/cracking_the_coding_interview | /recursion_and_dynamic_programming/multiply_recursively.py | 1,445 | 4.46875 | 4 | # write a recursive function to multiply two positive integers without using
# the * operator. others are allowed, but you should minimize the number of operations
def recursive_multiply(a, b):
smaller = b if a > b else a
larger = a if a > b else b
print("recursing and decrementing: {}".format(multiply_decrement(larger, smaller)))
print("recursion with bit manipulation: {}".format(bit_manipulation(larger, smaller)))
print("better solution: {}".format(min_product(larger, smaller)))
def multiply_decrement(larger, smaller):
if smaller == 1:
return larger
return multiply_decrement(larger, smaller-1) + larger
def multiply_decrement(larger, smaller):
if smaller == 1:
return larger
return multiply_decrement(larger, smaller-1) + larger
def bit_manipulation(a, b):
if (a & a-1) == 0 or (b & b-1) == 0:
return multiply_with_bits(a, b)
return bit_manipulation(a, b - 1) + a
def multiply_with_bits(a, b):
perf_power = a if (a & a-1) == 0 else b
other_num = b if (a & a-1) ==0 else a
i = 0
while not perf_power & 1 << i:
i += 1
return other_num << i
def min_product(larger, smaller):
if smaller == 0:
return 0
if smaller == 1:
return larger
smaller = smaller >> 1
half = min_product(larger, smaller)
if half % 2 == 0:
return half + half
return half + half + larger
recursive_multiply(7, 33)
| true |
3fb55edd7992543a4459f4f2d399d21f8b3f45d0 | zzzzzz5530041/python_learning | /hello_world/HelloWorld.py | 1,452 | 4.21875 | 4 | # -*- coding:UTF-8 -*-
print('hello');
a = -1;
b = -2;
if a > b:
print(a) # if a larger than b ,then print a
else:
print(b);
# if statement
if a > b:
if a == 1:
print(a)
else:
if a == 0:
print(a)
else:
pass
elif a == b:
print(a, b);
else:
print(b)
# comment. use ''' or """ to comment
'''
if a>b:
if a==1:
print(a)
else:
if a==0:
print(a)
else:
pass
elif a==b:
print(a,b);
else:
print(b)
'''
"""
if a>b:
if a==1:
print(a)
else:
if a==0:
print(a)
else:
pass
elif a==b:
print(a,b);
else:
print(b)
"""
# use " '
a = "what's ur name?";
b = 'i say : "what is your name?"';
print(a, b);
# use \ to wrap
x = 1;
y = 2;
# below equals to z = x*2+y*3
z = x * 2 \
+ y \
* 3;
print(z);
# input function
# name = input('Input ur name here:');
# print(name)
# print
arr = [1, 2, 3]
print(arr)
arrStr = ['a', 'b']
print(arrStr)
# loop
for i in arrStr:
print(i)
print(" 你好,支持中文")
# encode string
str = '''
在python中使用中文
需要注意编码问题,可以使用的字符编码有:
UTF-8,CP936,GB2312,ISO-8859-1
''';
print(str)
# simple caculation
print(3 * 5 / 2)
print(2 ** 4); # equals to 2*2*2*2
# math module
# import math module
import math
print(math.sin(30))
print(math.tan(1))
# big integer suport
print(99 ** 999)
| false |
a3e35c2ef4501db0f733d10746df79993a226ffe | JeffreyYou55/cit | /TermProject/plotting.py | 960 | 4.15625 | 4 | from turtle import *
import coordinates
import square
import linear
import quadratic
border = {
"width" : 620,
"height" : 620
}
# draw square and coordinate
print("< Jeffrey's Plotting Software >")
print("drawing rectangular coordinates...")
square.draw_square(border["width"], border["height"], -310, -300)
penup()
setx(0)
sety(0)
pendown()
coordinates.draw_coordinate()
draw_finished = False
while not draw_finished :
function_type = int( input("linear : 1, quadratic : 2 ") )
if(function_type == 1) :
slope = int( input("type the slope : ") )
y_incpt = int( input("type the y intercept : ") )
linear.linear(slope, y_incpt)
if(function_type == 2) :
a = float( input("type a : ") )
b = int( input("type b : ") )
c = int( input("type c : ") )
quadratic.quadratic(a,b,c)
draw_ends = input("press N to finish drawing. ")
if (draw_ends == "N" ):
draw_finished = True
done()
| true |
c8257d92fba77a9b9c006c7b2277c393d546403f | cbain1/DataScience210 | /python/ListsQ2.py | 924 | 4.125 | 4 | import sys
import random
def beret(request):
total = 0
strings = 0
#Loops through all words in request
for elem in request:
count =0
#splits each word into its own string value
word = list(elem)
# this loops through each letter in each word to see the number of letters in each word
for elem in word:
count +=1
total += count
strings +=1
average = total/strings
return (average)
# Define main for loops, bro
def main():
request = ['lists', 'are', 'pretty', 'cool', 'well', 'as', 'cool', 'as', 'computer', 'science', 'gets', 'which', 'is', 'not', 'very', 'cool' ]
print("Your average number of letters is: ", beret(request))
if __name__ == '__main__':
main()
"""
catherinebain > python3 ListsQ2.py
Your average number of letters is: 4.1875
""" | true |
f23c5207a4cab807e897918fa84aea19db8023d9 | andrewnnov/100days | /guess_number/main.py | 1,530 | 4.15625 | 4 | import random
from art import logo
print(logo)
print("Welcome to the Number Guessing Game!")
def play_game():
guess_number = random.randint(1, 100)
print(guess_number)
result_of_guess = True
while result_of_guess:
attempts = 0
print("I'm thinking of number between 1 and 100")
level = input("Choose a difficulty. Type 'easy' or 'hard' : ")
if level == 'hard':
attempts = 5
print(f"You have {attempts} attempts to guess the number. ")
else:
attempts = 10
print(f"You have {attempts} attempts to guess the number. ")
# user_guess = int(input("Make a guess: "))
while attempts > 0:
user_guess = int(input("Make a guess: "))
if user_guess > guess_number:
attempts = attempts - 1
print("Less")
if attempts == 0:
print("You lose")
result_of_guess = False
elif user_guess < guess_number:
print("More")
attempts = attempts - 1
if attempts == 0:
print("You lose")
result_of_guess = False
else:
print("You guess")
result_of_guess = False
attempts = 0
play_again = input("Do you want to play again? y - yes, n - no: ")
if play_again == "y":
play_game()
else:
result_of_guess = False
play_game() | true |
dd4d23a9d9fd69b70eab37f78093d7e0a6756c4b | andrewnnov/100days | /rps.py | 1,055 | 4.15625 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
list_options = [rock, paper, scissors]
y_choose = int(input("Enter your choose: rock(0) or paper(1) or scissors(2): "))
if y_choose >= 0 and y_choose <= 2:
print(list_options[y_choose])
computer_choose = random.randint(0, len(list_options)-1)
print(list_options[computer_choose])
if y_choose != computer_choose:
if y_choose == 0 and computer_choose == 2:
print("You win")
elif y_choose == 1 and computer_choose == 0:
print("You win")
elif y_choose == 2 and computer_choose == 1:
print("You win")
else:
print("You lose")
else:
print("Please try again")
else:
print("You lose")
| false |
16ec5926aa96c5a92794b797f3a597b3e60dbe39 | mirielesilverio/cursoPython3 | /logicOperators/using_logic_operators.py | 337 | 4.21875 | 4 | name = input('What is your name? ')
age = int(input('How old are you? ') or 0)
if not name:
print('The name cannot be empty')
elif ' ' in name:
print('Very good! You entered your full name')
elif ' ' not in name:
print('You must enter your full name.')
if not age or age < 0:
print('Oh no! You entered an invalid age')
| true |
8b84715a6d780d92c3bd97fd0c92496f1c1e8c09 | iam-amitkumar/BridgeLabz | /AlgorithmPrograms/Problem1_Anagram.py | 605 | 4.21875 | 4 | """Anagram program checks whether the given user-input
strings are anagram or not.
@author Amit Kumar
@version 1.0
@since 02/01/2019
"""
# importing important modules
import utility.Utility
import util.Util
global s1, s2
try:
s1 = utility.Utility.get_string()
s2 = utility.Utility.get_string()
except Exception as e:
print(e)
res = util.Util.is_anagram(s1, s2)
if res is True: # checking whether the function returns true or not, of true then both the strings are anagram
print("\n", s1, "and ", s2, " are anagram string")
else:
print("\n", s1, "and ", s2, " are not anagram string")
| true |
6416fd722282681c9da97207183871b94cf9e51f | iam-amitkumar/BridgeLabz | /ObjectOrientedPrograms/Problem1_Inventory.py | 1,976 | 4.28125 | 4 | """In this program a JSON file is created having Inventory Details for
Rice, Pulse and Wheat with properties name, weight, price per kg. With
the help of 'json' module reading the JSON file.
@author Amit Kumar
@version 1.0
@since 10/01/2019
"""
# Importing important modules
import json
# Inventory class
class Inventory:
# run_inventory method read the JSON file and convert it to the Dictionary object printing each type of grains
# with their every keys and values and printing them
@staticmethod
def run_inventory():
global dataStore, type # declaring variables as a global variable
f = open('Problem1.json', 'r') # opening the JSON file and reading it
dataStore = json.load(f) # after reading the whole JSON file converting it to the Dictionary object
for i in range(len(dataStore)): # this loop access all the keys and values present in the dictionary
if i == 0: # here we are assigning the variable 'type' as Rice if the index of the Dictionary is 0(zero)
type = "Rice"
if i == 1:
type = "Pulse"
if i == 2:
type = "Wheat"
# printing each properties of each grain after Dictionary which we get after converting the JSON file
print("\nGrain Type: ", type, "\n-------------------")
for j in range(len(dataStore[type])):
print("Name: ", dataStore[type][j]['name'])
print("Weight: ", dataStore[type][j]['weight'])
print("Price per kg: ", dataStore[type][j]['price'])
print("Total Price: ", (dataStore[type][j]['weight'])*(dataStore[type][0]['price']))
print()
# from this python file only program will compile not from the imported file
if __name__ == '__main__':
obj = Inventory() # creating object of Inventory class
obj.run_inventory() # accessing 'run_inventory' method through object reference variable
| true |
b0574f764eb2af8d4e06fddc1c9781c13b7f73a2 | iam-amitkumar/BridgeLabz | /DataStructureProgram/Problem4_BankingCashCounter.py | 2,955 | 4.375 | 4 | """this program creates Banking Cash Counter where people
come in to deposit Cash and withdraw Cash. It have an input panel to add people
to Queue to either deposit or withdraw money and de-queue the people maintaining
the Cash Balance.
@author Amit Kumar
@version 1.0
@since 08/01/2019
"""
# importing important modules
from DataStructureProgram.Queue import *
# creating the object of Queue class
q1 = Queue()
global opinion, amount, size_of_queue # globalizing the variables
amt_of_money = 1000 # initializing the bank balance
print("\nYour cleared balance: ", amt_of_money)
try: # handling the invalid user input for "size of the queue"
size_of_queue = int(input("\nEnter the size of the queue: "))
except Exception as e:
print(e)
# initialing the queue
try:
for i in range(size_of_queue):
q1.enqueue(i)
except Exception as e:
print(e)
# processing the steps until the queue even a single element
while q1.is_empty() is False:
print("\nEnter your opinion: \n"
"1. Press 1 to deposit\n"
"2. Press 2 to withdraw\n")
try: # handling the invalid user input for "opinion of user"
opinion = int(input("Enter your opinion: "))
except Exception as e:
print(e)
try:
if opinion == 1: # checking for the input of the user, whether to deposit or withdraw
try: # handling the invalid user input for "amount to deposit"
amount = int(input("Enter the amount you want to deposit in the account: "))
except Exception as e:
print(e)
if amount < 0:
print("Enter a valid amount")
else:
amt_of_money += amount # adding the money to the account
print("Remaining balance: ", amt_of_money)
q1.de_queue()
elif opinion == 2: # checking for the input of the user, whether to deposit or withdraw
try: # handling the invalid user input for "amount to withdraw"
amount = int(input("Enter the amount you want to withdraw from the account: "))
except Exception as e:
print(e)
if amount < 0:
print("!!! Enter a valid amount !!!")
print("Remaining balance: ", amt_of_money)
else:
if (amt_of_money - amount) < 0:
print("\n>>> Don't have sufficient balance, reenter withdraw amount or Deposit first. <<<")
print("Remaining balance: ", amt_of_money)
else:
amt_of_money -= amount # deducting the amount of money from the account
print("Remaining balance: ", amt_of_money)
q1.de_queue()
else:
print("Invalid Input !!!")
except Exception as e:
print(e)
# printing final available balance present in the account
print("\n>>> Available Balance :", amt_of_money, " <<<")
| true |
e1a0391349896b3ab22365f4c9f295240dae6a9a | iam-amitkumar/BridgeLabz | /AlgorithmPrograms/Problem7_InsertionSort.py | 963 | 4.21875 | 4 | """This program reads in strings from standard input
and prints them in sorted order using insertion sort
algorithm
@author Amit Kumar
@version 1.0
@since 04/01/2019
"""
# importing important modules
import utility.Utility
import string
global u_string
try:
u_string = input("Enter the number of string you want to enter: ")
except Exception as e:
print(e)
list1 = u_string.split() # converting user-input string into string list
input_list = [word.strip(string.punctuation) for word in list1] # trimming commas/punctuation present in the user list
user_string = ' '.join(input_list) # converting trimmed list into string separated by space to print as unsorted string
print("\nYour string: \n%s" % user_string)
utility.Utility.insertion_sort(input_list) # sorting the trimmed list using user-defined insertion_sort method
res = ' '.join(input_list) # converting sorted list into string separated by space
print("\nYour sorted string: \n%s" % res)
| true |
8e1f1ee70acfa12c836eb7bc7274e1b424e5e747 | iam-amitkumar/BridgeLabz | /DataStructureProgram/Problem3_BalancedParentheses.py | 1,862 | 4.1875 | 4 | """Take an Arithmetic Expression where parentheses are used to order the
performance of operations. Ensure parentheses must appear in a balanced
fashion.
@author Amit Kumar
@version 1.0
@since 08/01/2019
"""
# importing important modules
from DataStructureProgram.Stack import *
s1 = Stack() # creating object of Stack class
# this function checks whether the string given by the user has balanced parentheses or not, on that basis return
# boolean value
def check_bal(exp1):
for i in range(0, len(exp1)):
if exp1[i] == '(' or exp1[i] == '{' or exp1[i] == '[': # pushing in stack if string contain open parentheses
s1.push(exp1[i])
try:
if exp1[i] == ')':
x = s1.pop() # popping the stored open parentheses if any close parentheses found in the string
if x != '(':
return False
elif exp1[i] == '}':
x = s1.pop() # popping the stored curly braces if any close curly braces found in the string
if x != '{':
return False
elif exp1[i] == ']':
x = s1.pop() # popping the stored brackets if any close brackets found in the string
if x != '[':
return False
except Exception as e1: # handling the exception of "Stack Underflow"
print(e1)
global exp
try:
exp = input("Please enter your expression")
except Exception as e:
print(e)
check = check_bal(exp)
if s1.is_empty() and check: # printing the result if function return True otherwise False
print("\n>>> Your expression is balanced <<<")
# elif s1.is_empty(): # if the user-input string don't has any parentheses then print "Balanced"
# print("\n>>> Your expression is balanced <<<")
else:
print("\n>>> Your expression is not balanced <<<")
| true |
e993fb4db905e0d672d59137c376cbb9368d93a0 | PhilipCastiglione/learning-machines | /uninformed_search/problems/travel.py | 2,072 | 4.28125 | 4 | from problems.dat.cities import cities
"""Travel is a puzzle where a list of cities in North America must be navigated
in order to find a goal city. The navigation approach presents a problem to be
solved using search algorithms of various strategies.
The distance between cities is provided and a heuristic, straight line distance
is provided to the goal city.
refer: ./cities.py
"""
class Travel:
"""Travel defines the search space, contents and rules for the conceptual
travel board, and makes itself available through state manipulation for
search algorithms.
"""
"""Instantiate with an initial state and the board cities."""
def __init__(self, initial_state):
self.cities = cities
self.current_city = initial_state
# the goal city is fixed as straight line distance data is supplied
self.goal_city = 'sault ste marie'
"""For debugging."""
def print(self):
print("CITIES:")
print(self.cities)
print("CURRENTLY IN: {}".format(self.current_city))
print("GOAL: {}".format(self.goal_city))
"""Returns the current state."""
def current_state(self):
return self.current_city
"""Returns the cost of moving from one state to another state. The move
is assumed to be legal.
"""
def move_cost(self, state1, state2):
return self.cities[state1]["neighbours"][state2]
"""Returns the heuristic cost of the current or provided state, determined
using the straight line distance to the goal city.
"""
def heuristic_cost(self, state=None):
# sld => Straight Line Distance
city = state or self.current_city
return self.cities[city]["sld"]
"""Returns the legal states available from the current state."""
def next_states(self):
return list(self.cities[self.current_city]["neighbours"].keys())
"""Sets the current state."""
def set_state(self, state):
self.current_city = state
"""Returns the goal state."""
def goal_state(self):
return self.goal_city
| true |
c8f4625094cc322c498da1b751ad70e838c98775 | namelessnerd/flaming-octo-sansa | /graphs/breadth_first_search.py | 1,609 | 4.25 | 4 |
def breadth_first_search(graph, starting_vertex):
# store the number of steps in which we can reach a starting_vertex
num_level= {starting_vertex:0,}
#store the parent of each starting_vertex
parent={starting_vertex:None,}
#current level
level= 1
#store unexplored vertices
unexplored=[starting_vertex]
print type(graph)
#while we have unexplored vertices, explore them
while unexplored:
#explore each unexplored vertices. We will keep a list of the next vertices to explore. This will be a list of
#all unexplored vertices that are reachable from the current unexplored vertices
next_vertices_to_explore=[]
for unexplored_vertex in unexplored:
#get all the nodes we can reach from this starting_vertex
for reachable_node in graph[unexplored_vertex]:
#see if have visited this vertex. If we have, we will have a level value for initialization
if reachable_node not in num_level:
#we have reached a previously unreachable node in level steps
num_level[reachable_node]= level
# the parent of this node is the current unexplored vertex
parent[reachable_node]= unexplored_vertex
#add this to the next_vertices_to_explore
next_vertices_to_explore.append(reachable_node)
#now we have explored all unexplored vertices
unexplored= next_vertices_to_explore
print unexplored
level+=1
print parent
print num_level
def main():
graph={'a':['s','z',], 'z':['a',], 's':['a','x',], 'd':['x','c','f'], 'f':['d','c','v',], 'v':['f','c'], 'c':['d','f','x','v'], 'x':['s','d','c'],}
breadth_first_search(graph,'s')
if __name__ == '__main__':
main() | true |
8800b16c4518c85952934c96ba8ccf04cb2d3fe7 | vaddanak/challenges | /mycode/fibonacci/fibonacci.py | 2,392 | 4.15625 | 4 | #!/usr/bin/env python
'''
Author: Vaddanak Seng
File: fibonacci.py
Purpose: Print out the first N numbers in the Fibonacci sequence.
Date: 2015/07/25
'''
from __future__ import print_function;
import sys;
import re;
sequence = [0,1];
'''
Calculate and collect first N numbers in Fibonacci number sequence.
Store result in global variable "sequence".
'''
def fibonacci(N):
global sequence;
if N>2:
sequence.append(sequence[len(sequence)-1] + sequence[len(sequence)-2]);
fibonacci(N-1);
N = int(raw_input());
fibonacci(N);
listStr = [str(sequence[x]) for x in range(N)];
#for x in listStr:
# print(x, end=''); #0112358132134 when N = 10; WRONG !!! WHY???
# still won't space correctly eventhough sequence element is str type ???
#for x in range(N):
# won't space correctly when sequence element is int type ??? WHY???
#print('%d' % sequence[x], end=''); #0112358132134 when N = 10; WRONG !!!
###option 1 -- using string join() function
mstr = ' '.join(listStr);
#print(mstr, end=''); #0 1 1 2 3 5 8 13 21 34 when N = 10; CORRECT spacing !!!
###option 2 -- using sys.stdout.write
#for x in range(N):
# sys.stdout.write('%d' % sequence[x]);
# if x < N-1: # alternative to force correct spacing
# sys.stdout.write(' '); #0 1 1 2 3 5 8 13 21 34 when N = 10; CORRECT !!!
###option 3 -- using regular expression
sequence = [sequence[x] for x in range(N)]; #ensures number of elements == N
mstr2 = str(sequence);
#print(mstr2); # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
#target string: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
reObject = re.compile(r'^(\[\s*){1}(\d+[, ]+)*\d+(\])$');#match whole string
reo1 = re.compile(r'^(\[ *){1}');#match left most [
reo2 = re.compile(r', +');#match each sequence of comma-followed-by-space
reo3 = re.compile(r'\]$');#match right most ]
matchObject = reObject.match(mstr2);
#if matchObject:
# print(matchObject.group(0));# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] when N=10
modifiedString = mstr2;
#print(modifiedString);# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] when N=10; original
modifiedString = reo1.sub('',modifiedString);
#print(modifiedString);# 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
modifiedString = reo3.sub('',modifiedString);
#print(modifiedString);# 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
modifiedString = reo2.sub(' ',modifiedString);
print(modifiedString, end='');# 0 1 1 2 3 5 8 13 21 34 ; CORRECT !!!
| true |
4296c919d465767998bee122b61e3cabc683d101 | officialtech/xPython | /static_variable | xpython.py | 2,954 | 4.125 | 4 | **********************************************# STATIC VARIABLES *****************************************
# The variables which are declared inside the class and outside the 'method' are called static variable.
# Static variables will holds common values for every object.
# Static variables will get memory for one time.
# To call static variables we use class name.
# Static variable will get memory at class loading time.
class Employee:
c_name = "official tech"
c_cno = 10010101000010
print(Employee.c_name)
print(Employee.c_cno)
*******************************************************************************************************************
# Using global and static variable in function
a = 1010
print(a)
class Employee():
c_name = "official tech"
c_cno = "10010101000010"
print(a)
print(Employee.c_name)
print(Employee.c_cno)
def function():
print(a)
print(Employee.c_name)
print(Employee.c_cno)
function()
**********************************************************************************************************************
# REMEMBER BELOW WE ARE CREATING TWO 'PYTHON FILES' OR MODULES
**********************************************************************************************************************
# Import a class to another class
--------------------# step 1: create a module, like
class Employee:
name = "official tech"
ctn = 1010
---------------------# step 2: save as whatever.py
---------------------# step 3: create annother module, like
from whatever import Employee
print(Employee.name)
print(Employee.ctn)
---------------------# step 4: save as what_so_ever.py and run
----------------------------------# Program on instance and static variable ----------------------------------------------
class Official_tech:
# static block start
comp_name = 'official tech Inc.'
comp_c_no = 10010101000010
# static block ends
def team_member(self, id, name, salary = 00.00): # Remember this is a method, not a function
# Instance block
self.i_d = id
self.n_m = name
self.sal = salary
def mess_disp(self):
print(Official_tech.comp_c_no) # printing Static variable using Class name
print(self.i_d) # printing instance variable
print(self.sal)
print(self.n_m)
print(Official_tech.comp_name)
obj_var = Official_tech() # 1.creating object and storing to variable
obj_var.team_member(808, 'tppa', 400000.00) # giving arg's to parameters
obj_var.mess_disp()
print("~ " * 10)
obj_var1 = Official_tech() # 2.creating another object and storing to variable
obj_var1.team_member(1010, 'sqst', 350000.00)
obj_var.mess_disp()
print("~ " * 10)
print(obj_var.comp_name) # calling static variable
print("~ " * 10)
print(obj_var1.i_d) # calling Instance variable
print(obj_var1.comp_c_no)
| true |
6da56124e837982d56bed013942e60fc9068692b | amersulieman/Simple-Encryption-Decryption | /Decryption.py | 1,552 | 4.15625 | 4 | '''@Author: Amer Sulieman
@Version: 10/07/2018
@Info: A decryption file'''
import sys
from pathlib import Path
#check arguments given for the script to work
if len(sys.argv)< 2:
sys.exit("Error!!!!\nProvide <fileName> to decrypt!!");
def decryption(file):
#File path to accomdate any running system
filePath = Path("./"+file);
#The file data will be copied to this variable encrypted
Decrypt1="";
Decrypt2="";
#Open the file
with open(filePath) as myFile:
#read the file data
readFile = myFile.read()
#every letter in the read data
for character in readFile:
#decrypt1 gets shifted back 2^2 places
Decrypt1+=chr(ord(character)>>2)
#Loop every letter in decrypt1
for letter in Decrypt1:
#If the letter is small 'a' to small 'z' shift it by 13 in alpha order
if ord(letter)>=97 and ord(letter)<=122:
#Replace the letter and concatnate to ENC variable
Decrypt2+=chr(((ord(letter)-97+13)%26)+97);
#If the letter is capital 'A' to capital 'Z' shoft it by 13 in alpha order
elif ord(letter)>=65 and ord(letter)<=90 :
#Replace the letter and concatnate to ENC variable
Decrypt2+=chr(((ord(letter)-65+13)%26)+65);
#If it is a line feed then add the line feed so i can keep the format
elif ord(letter)==10:
Decrypt2+="\n"
#Any other character shift its asic by 2 spots
else:
Decrypt2+=chr(ord(letter)>>2);
#Write the decrypted data back to the file
with open(filePath,"w") as myFile:
myFile.write(Decrypt2);
print(file +" Decrypted!!");
decryption(sys.argv[1]); | true |
323349df70f4586b2055c9ae5894a0195f1e79ba | vladn90/Algorithms | /Numbers/fibonacci.py | 1,940 | 4.125 | 4 | """ Comparison of different algorithms to calculate n-th Fibonacci number.
In this implemention Fibonacci sequence is gonna start with 0, i.e.
0, 1, 1, 2, 3, 5...
"""
from timeit import timeit
from functools import lru_cache
def fib_1(n):
""" Recursive algorithm. Very slow. Runs in exponential time.
"""
# base case 0th Fibonacci number = 0
if n == 0:
return 0
# base case 1st Fibonacci number = 1
elif n == 1:
return 1
return fib_1(n - 1) + fib_1(n - 2)
fib_cache = {0: 0, 1: 1} # Fib index: Fib number
def fib_2(n):
""" Improved algorithm using memoization, runs in linear time.
"""
if n in fib_cache:
return fib_cache[n]
fib_cache[n] = fib_2(n - 1) + fib_2(n - 2)
return fib_cache[n]
@lru_cache()
def fib_3(n):
""" Same logic as above but using cache function as a decorator.
"""
# base case 0th Fibonacci number = 0
if n == 0:
return 0
# base case 1st Fibonacci number = 1
elif n == 1:
return 1
return fib_3(n - 1) + fib_3(n - 2)
def fib_4(n):
""" Dynamic programming solution. Runs in O(n) time and uses O(1) space.
"""
if n < 2:
return n
prev, curr = 0, 1
for i in range(2, n + 1):
prev, curr = curr, prev + curr
return curr
if __name__ == "__main__":
# stress testing solutions against each other up to 20th Fibonacci number
for n in range(0, 21):
f1 = fib_1(n)
f2 = fib_2(n)
f3 = fib_3(n)
f4 = fib_4(n)
assert f1 == f2 == f3 == f4
# time comparison for n-th Fibonacci number
n = 30
t1 = timeit("fib_1(n)", number=1, globals=globals())
t3 = timeit("fib_2(n)", number=1, globals=globals())
t4 = timeit("fib_4(n)", number=1, globals=globals())
print(f"Recursive implemention: {t1}")
print(f"Recursive implemention with memoization: {t3}")
print(f"Dynamic programming solution: {t4}")
| true |
6b974c6dfc21b4d8aeea7cf2a9536b8a33b02929 | vladn90/Algorithms | /Sorting/insertion_sort.py | 1,207 | 4.4375 | 4 | """ Insertion sort algorithm description,
where n is a length of the input array:
1) Let array[0] be the sorted array.
2) Choose element i, where i from 1 to n.
3) Insert element i in the sorted array, which goes from i - 1 to 0.
Time complexity: O(n^2).
Space complexity: O(1).
"""
import random
def insertion_sort(array):
""" Sorts array in-place.
"""
for i in range(1, len(array)):
for j in range(i - 1, -1, -1):
if array[i] < array[j]:
array[i], array[j] = array[j], array[i]
i -= 1
else:
break
if __name__ == "__main__":
# stress testing insertion_sort by comparing with built-in sort()
while True:
nums = [random.randrange(10**3, 10**12)
for i in range(random.randrange(10**2, 10**3))]
nums_insert = nums[:]
nums.sort()
insertion_sort(nums_insert)
if nums == nums_insert:
print("OK")
print(f"size of the sorted array: {len(nums)}")
else:
print("Something went wrong.")
print(f"bult-in sort result: {nums}")
print(f"insertion sort result: {nums_insert}")
break
| true |
2f5ea417ad6f0ff70f0efcede02f9579c580533a | vladn90/Algorithms | /Sorting/bubble_sort.py | 1,196 | 4.375 | 4 | """ Bubble sort algorithm description,
where n is a length of the input array:
1) Compare consecutive elements in the list.
2) Swap elements if next element < current element.
4) Stop when no more swaps are needed.
Time complexity: O(n^2).
Space complexity: O(1).
"""
import random
def bubble_sort(array):
""" Sorts array in-place.
"""
need_swap = True
while need_swap:
need_swap = False
for i in range(len(array) - 1):
if array[i + 1] < array[i]:
array[i], array[i + 1] = array[i + 1], array[i]
need_swap = True
if __name__ == "__main__":
# stress testing bubble_sort by comparing with built-in sort()
while True:
nums = [random.randrange(10**3, 10**12)
for i in range(random.randrange(10**2, 10**3))]
nums_bubble = nums[:]
nums.sort()
bubble_sort(nums_bubble)
if nums == nums_bubble:
print("OK")
print(f"size of the sorted array: {len(nums)}")
else:
print("Something went wrong.")
print(f"bult-in sort result: {nums}")
print(f"bubble sort result: {nums_bubble}")
break
| true |
8c57f071fe179750c8be0d2b81ed023d94299ad7 | vladn90/Algorithms | /Matrix_problems/spiral_matrix.py | 2,011 | 4.25 | 4 | """ Problem description can be found here:
https://leetcode.com/problems/spiral-matrix/description/
Given a matrix of m x n elements,
return all elements of the matrix in spiral order.
For example, given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1, 2, 3, 6, 9, 8, 7, 4, 5].
"""
def spiral_order(matrix):
result = []
n = len(matrix) * len(matrix[0])
right = len(matrix[0])
left = -1
bottom = len(matrix)
top = 0
i, j = 0, -1
while len(result) < n:
j += 1
while j < right and len(result) < n:
result.append(matrix[i][j])
j += 1
j -= 1
right -= 1
i += 1
while i < bottom and len(result) < n:
result.append(matrix[i][j])
i += 1
i -= 1
bottom -= 1
j -= 1
while j > left and len(result) < n:
result.append(matrix[i][j])
j -= 1
j += 1
left += 1
i -= 1
while i > top and len(result) < n:
result.append(matrix[i][j])
i -= 1
i += 1
top += 1
return result
def display_matrix(matrix):
x = len(matrix) // 2
for i in matrix:
for j in i:
print(str(j).rjust(3), end=" ")
print()
if __name__ == "__main__":
# 3 x 3 matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
display_matrix(matrix)
result = spiral_order(matrix)
assert result == [1, 2, 3, 6, 9, 8, 7, 4, 5]
print(f"result: {result}")
print()
# 5 x 5 matrix
matrix = []
for i in range(1, 26, 5):
matrix.append(list(range(i, i + 5)))
display_matrix(matrix)
result = spiral_order(matrix)
print(f"result: {result}")
print()
# 10 x 10 matrix
matrix = []
for i in range(1, 101, 10):
matrix.append(list(range(i, i + 10)))
display_matrix(matrix)
result = spiral_order(matrix)
print(f"result: {result}")
| true |
cfadda58720b5b635c21235c4a73a91f6cffca40 | ayr0/numerical_computing | /Python/GettingStarted/solutions_GettingStarted.py | 2,065 | 4.375 | 4 | # Problem 1
'''
1. Integer Division returns the floor.
2. Imaginary numbers are written with a suffix of j or J.
Complex numbers can be created with the complex(real, imag) function.
To extract just the real part use .real
To extract just the imaginary part use .imag
3. float(x) where x is the integer.
4. //
'''
# problem 2
'''
1. A string is immutable because its content cannot be changed.
2. string[::2] returns every other letter of the string.
string[27:0:-1] returns the string in reverse - without the first character.
3. The entire string in reverse can be accessed by string[::-1]
'''
# problem 3
'''
1. Mutable objects can be changed in place after creation.
The value stored in memory is changed.
Immutable objects cannot be modified after creation.
2. a[4] = "yoga"
a[:] is a copy of the entire list
a[:] = [] clears the list (del a[:] is also an option)
len(a) returns the list size.
a[0], a[1] = "Peter Pan", "camelbak"
a.append("Jonathan, my pet fish")
3.
my_list = []
my_list = [i for i in xrange(5)]
my_list[3] = float(my_list[3])
del my_list[2]
my_list.sort(reverse=True)
'''
# Problem 4
'''
1.
set() (must be used to create an empty set) and {}
2.
union = set.union(setA, setB)
or union = setA | setB
3. trick questions! sets don't support indexing, slicing, or any other
sequence-like behavior. Works because sets are unordered and don't allow duplicates.
'''
# problem 5
'''
1. dict() and {} (must be used to create an empty dictionary)
2. sq = {x: x**2 for x in range(2,11,2)}
3. del(dict[key])
4. dict.values()
'''
#problem 6
'''
1. The print statement writes the value of the expression(s) it's given
to the standard output. The return statement allows a function to specify
a return value to be passed back to the calling function.
2. Grocery List cannot have a space. It is also important NOT to call your list "list".
Doing so shadows Python's built in list constructor.
for loop and if statement require a colon and nested indentation
i%2 == 0. Not an assignment.
Grocery List[i]. Needs brackets.
'''
| true |
9d251fbd12296040c32f4eb9346005da200ebf25 | pythagaurang/sort-analysis | /sorts/merge.py | 810 | 4.15625 | 4 | from main import main
def merge(array1,array2):
l_1=len(array1)
l_2=len(array2)
array3=[]
i=j=0
while(i<l_1 and j<l_2):
if array1[i]<array2[j]:
array3.append(array1[i])
i+=1
elif array1[i]>array2[j]:
array3.append(array2[j])
j+=1
else:
array3.append(array1[i])
array3.append(array2[j])
i+=1
j+=1
while i<l_1:
array3.append(array1[i])
i+=1
while j<l_2:
array3.append(array2[j])
j+=1
return array3
def merge_sort(array):
if len(array)<=1:
return array
else:
mid=len(array)//2
return merge(merge_sort(array[:mid]),merge_sort(array[mid:]))
if __name__=="__main__":
main(merge_sort)
| false |
7eb6f26a36fd55f437aef7510db2d9df1e055d2e | flyburi/python-study | /io_input.py | 223 | 4.375 | 4 | def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
sth = raw_input("Enter text:")
if is_palindrome(sth):
print "yes it is a palindrome"
else:
print "no it is not a palindrome"
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.