blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ef744c39487ff3f1ab08cd8a1dac5f254235aa3e | code-she/python-problems | /problem7.py | 300 | 4.25 | 4 | #The included code stub will read an integer,n , from STDIN.
#Without using any string methods, try to print the following: 1,2,3,..n
#Note that "..." represents the consecutive values in between.
if __name__ == '__main__':
n = int(input())
for i in range(1,n+1):
print (i,end='')
| true |
dacf7b25dd815ad77672f783210764f43c7cfded | eladshamailov/Codewars-solutions | /isograms.py | 437 | 4.125 | 4 | """
An isogram is a word that has no repeating letters, consecutive or non-consecutive.
Implement a function that determines whether a string that contains only letters
is an isogram. Assume the empty string is an isogram. Ignore letter case.
"""
def is_isogram(string):
letter_dict = {}
for c in string:
if c.lower() in letter_dict:
return False
else:
letter_dict[c] = 1
return True
| true |
185857a46f67f49fc786982905b828f07952a458 | IMDCGP105-1819/portfolio-RJRichmond | /ex10.py | 476 | 4.125 | 4 | def FizzBuzz(int):
number = 0
low = int(input("Input the starting number of the range "))
high = int(input("Input the ending number of the range "))
for numberCounter in range(low, high, 1):
number += 1
if (number%3 == 0 and number%5 == 0):
print ("FizzBuzz")
elif (number%5 == 0):
print ("Buzz")
elif (number%3 == 0):
print ("Fizz")
else:
print (number)
FizzBuzz(int);
| true |
122d86255b9cc64e58ce7ebc8b8f797a725b1d15 | swatia-code/data_structure_and_algorithm | /hashing/uncommon_characters.py | 1,452 | 4.15625 | 4 | '''
PROBLEM STATEMENT
-----------------
Find and print the uncommon characters of the two given strings S1 and S2. Here uncommon character means that either the character is present in one string or it is present in other string but not in both. The strings contains only lowercase characters and can contain duplicates.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains two strings in two subsequent lines.
Output:
For each testcase, in a new line, print the uncommon characters of the two given strings in sorted order.
Constraints:
1 <= T <= 100
1 <= |S1|, |S2| <= 105
Example:
Input:
1
characters
alphabets
Output:
bclpr
LOGIC
-----
SOURCE
------
geeksforgeeks
CODE
----
'''
def uncommon_characters(s1, s2):
freq1 = dict()
freq2 = dict()
for ele in s1:
if ele not in freq1:
freq1[ele] = True
for ele in s2:
if ele not in freq2:
freq2[ele] = True
res = ''
for ele in freq1:
if ele not in freq2:
res = res+ele
else:
freq1[ele] = False
freq2[ele] = False
for ele in freq2:
if freq2[ele]:
res = res+ ele
s = ''.join(sorted(res))
return s
t = int(input())
for _ in range(t):
s1 = input()
s2 = input()
print(uncommon_characters(s1, s2))
| true |
9fa221653cb871f16dc37077eefcbe1e543b018b | swatia-code/data_structure_and_algorithm | /hashing/count_distinct_elements_in_every_window.py | 2,496 | 4.21875 | 4 | '''
PROBLEM STATEMENT
-----------------
Given an array of integers and a number K. Find the count of distinct elements in every window of size K in the array.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains two integers N and K. Then in the next line are N space separated values of the array A[].
Output:
For each test case in a new line print the space separated values denoting counts of distinct numbers in all windows of size k in the array A[].
Your Task:
You don't need to read input or print anything. Your task is to complete the function countDistinct() which takes the array A[], the size of the array(N) and the window size(K) as inputs and returns an array containing the count of distinct elements in every contiguous window of size K in the array A[].
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= T <= 100
1 <= N <= K <= 105
1 <= A[i] <= 105 , for each valid i
Example:
Sample Input:
2
7 4
1 2 1 3 4 2 3
3 2
4 1 1
Sample Output:
3 4 4 3
2 1
Explanation:
Testcase 1 :
Window 1 of size k = 4 is 1 2 1 3. Number of distinct elements in this window are 3.
Window 2 of size k = 4 is 2 1 3 4. Number of distinct elements in this window are 4.
Window 3 of size k = 4 is 1 3 4 2. Number of distinct elements in this window are 4.
Window 4 of size k = 4 is 3 4 2 3. Number of distinct elements in this window are 3.
LOGIC
-----
SOURCE
------
geeksforgeeks
CODE
----
'''
# Code here
res = list()
freq = dict()
ind = 0
for ele in arr[:K]:
if ele in freq:
freq[ele] += 1
else:
freq[ele] = 1
res.append(len(freq))
for ele in arr[K:]:
#removing one index from start of window
if freq[arr[ind]] == 1:
freq.pop(arr[ind])
else:
freq[arr[ind]] -= 1
ind += 1
#adding next element to frequency dictionary
if ele in freq:
freq[ele] += 1
else:
freq[ele] = 1
res.append(len(freq))
return res
#{
# Driver Code Starts
if __name__=='__main__':
t = int(input())
for i in range(t):
n,k = list(map(int, input().strip().split()))
arr = list(map(int, input().strip().split()))
res = countDistinct(arr, n, k)
for i in res:
print (i, end = " ")
print ()
# } Driver Code Ends
| true |
8d29bd62361b076377375eb7283f12286c3f516f | swatia-code/data_structure_and_algorithm | /strings/group_anagrams_together.py | 1,338 | 4.34375 | 4 | """
PROBLEM STATEMENT
-----------------
Given an array of words, print the count of all anagrams together in sorted order (increasing order of counts).
For example, if the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then grouped anagrams are “(dog, god) (cat, tac, act)”. So the output will be 2 3.
Input:
First line consists of T test case. First line of every test case consists of N, denoting the number of words in array. Second line of every test case consists of words of array.
Output:
Single line output, print the counts of anagrams in increasing order.
Constraints:
1<=T<=100
1<=N<=50
Example:
Input:
2
5
act cat tac god dog
3
act cat tac
Output:
2 3
3
LOGIC
-----
Simple use of sorting and dictionary.
SOURCE
------
geeksforgeeks
CODE
----
"""
#code
def anagrams(l):
res = []
li = dict()
for ele in l:
lis = [s for s in ele]
lis.sort()
s = ""
for ele in lis:
s += ele
if s not in li:
li[s] = 1
else:
li[s] += 1
li = sorted(li.items(), key=lambda x: x[1])
for ele in li:
print(ele[1],end=" ")
print()
t = int(input())
for _ in range(t):
n = int(input())
l = [x for x in input().split()]
anagrams(l)
| true |
a72196b328bcf67d5be1ef498f30effdd285a46e | swatia-code/data_structure_and_algorithm | /array/run_length_encoding.py | 1,671 | 4.28125 | 4 | '''
PROBLEM STATEMENT
-----------------
Given a string, Your task is to complete the function encode that returns the run length encoded string for the given string.
eg if the input string is “wwwwaaadexxxxxx”, then the function should return “w4a3d1e1x6″.
You are required to complete the function encode that takes only one argument the string which is to be encoded and returns the encoded string.
Input:
The first line contains T denoting no of test cases . Then T test cases follow . Each test case contains a string str which is to be encoded .
Output:
For each test case output in a single line the so encoded string .
Your Task:
Complete the function encode() which takes a character array as a input parameter and returns the encoded string.
Expected Time Complexity: O(N), N = length of given string.
Expected Auxiliary Space: O(1)
Constraints:
1<=T<=100
1<=length of str<=100
Example:
Input(To be used only for expected output)
2
aaaabbbccc
abbbcdddd
Output
a4b3c3
a1b3c1d4
Explanation:
Test Case 1: a repeated 4 times consecutively, b 3 times, c also 3 times.
Test Case 2: a, b, c, d repeated consecutively 1, 3, 1, 4 respectively.
LOGIC
-----
SOURCE
------
geeksforgeeks
CODE
----
'''
def encode(arr):
# Code here
l = list()
ch = arr[0]
l.append(ch)
sum = 0
for ele in arr:
if ele == ch:
sum += 1
else:
l.append(sum)
l.append(ele)
ch = ele
sum = 1
l.append(sum)
return ''.join(str(ele) for ele in l)
if __name__=='__main__':
t=int(input())
for i in range(t):
arr=input().strip()
print (encode(arr))
| true |
237eaa02081291e28f0c2713a870d409a0e284d0 | swatia-code/data_structure_and_algorithm | /dynamic_programming/unbounded_knapsack.py | 1,262 | 4.125 | 4 | """
PROBLEM STATEMENT
------------------
Given a set of N items, each with a weight and a value, and a weight limit W. Find the maximum value of a collection containing
any of the N items any number of times so that the total weight is less than or equal to W.
Example 1:
Input: N = 2, W = 3
val[] = {1, 1}
wt[] = {2, 1}
Output: 3
Explaination: Pick the 2nd element thrice.
Example 2:
Input: N = 4, W = 8
val[] = {1, 4, 5, 7}
wt[] = {1, 3, 4, 5}
Output: 11
Explaination: The optimal choice is to
pick the 2nd and 4th element.
Your Task:
You do not need to read input or print anything. Your task is to complete the function knapSack() which takes the values N, W and
the arrays val[] and wt[] as input parameters and returns the maximum possible value.
Expected Time Complexity: O(N*W)
Expected Auxiliary Space: O(W)
Constraints:
1 ≤ N, W ≤ 1000
1 ≤ val[i], wt[i] ≤ 100
TIME COMPLEXITY
---------------
O(N * W)
CODE
----
"""
class Solution:
def knapSack(self, n, W, val, wt):
# code here
dp = [0 for i in range(W + 1)]
for i in range(W + 1):
for j in range(n):
if (wt[j] <= i):
dp[i] = max(dp[i], dp[i - wt[j]] + val[j])
return dp[W]
| true |
7eed80dfb2cc7e8c96a8260d1c72ca119dfe6abd | vova0808/Introduction-to-computer-science-and-programming-using-Python-MITx-6.00.1x- | /ps2.2.py | 2,120 | 4.5 | 4 | # Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a
# fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each
# month.
# In this problem, we will not be dealing with a minimum monthly payment rate.
# The following variables contain values as described below:
# balance - the outstanding balance on the credit card
# annualInterestRate - annual interest rate as a decimal
# The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example: Lowest Payment: 180
# Assume that the interest is compounded monthly according to the balance at the end of the month (after the payment for that month is made).
# The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative
# using this payment scheme, which is okay. A summary of the required math is found below:
# Monthly interest rate = (Annual interest rate) / 12.0
# Monthly unpaid balance = (Previous balance) - (Minimum fixed monthly payment)
# Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
balance = 3926
annualInterestRate = 0.2
fixedPayment = 0
def check_balance(balance, annualInterestRate, fixedPayment):
flag = False
month = 0
while month < 12:
monthlyInterestRate = annualInterestRate / 12.0
monthlyUnpaidBalance = balance - fixedPayment
balance = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance)
month += 1
if balance < 0:
flag = True
return flag
while not check_balance(balance, annualInterestRate, fixedPayment):
fixedPayment += 10
check_balance(balance, annualInterestRate, fixedPayment)
print("Lowest payment: ", fixedPayment)
| true |
3bd627ddc4c2720648e177e3c12d48d76519cd93 | manasjoshi1/PythonTraining | /student_read_display.py | 341 | 4.1875 | 4 | name=input("Enter Student Name: ")
roll=input("Enter Student roll: ")
std=input("Enter Student std: ")
div=input("Enter Student div: ")
student={
"name":name,
"roll":roll,
"std":std,
"div":div
}
print(student)
print("Roll no. {} {} is studying in {} {}".format(student["roll"],student["name"],student["std"],student["div"])) | false |
0bba0acdf2ff5dcd595686949646713f0ef43a8d | lucasgeb/programacion_1 | /Trabajo Práctico 2/TP2_E10.py | 515 | 4.125 | 4 | """
Ejercicio 10
Dado un número determinar si el mismo es múltiplo de 2 o de 5, de ser así mostrar dicho
Número elevado al cubo
"""
#* opcion 1
numero = int(input('ingrese un numero '))
if(numero % 2 == 0):
print(numero ** 3)
elif(numero % 5 == 0):
print(numero ** 3)
else:
print('no es multiplo de 2 ni de 5')
#* opcion 2
# numero = int(input('ingrese un numero '))
# if(numero % 2 == 0 or numero % 5 == 0):
# print(numero ** 3)
# else:
# print(' el número no es multiplo de 2 ni de 5') | false |
1db16b6233af5b3a46810abd63770ef9eb7d6bf3 | Kanino19/LearnPython | /18.10.2018.py | 844 | 4.1875 | 4 | #Tema Tuplas
# Las tuplas son muy similares a las listas
#recordar que si los elementos tienen corchetes
#es una lista pero si los elementos no están en
#corchetes entonces es una tupla
t = 1,True,"Hola mi amor"
print (t)
t = (3,"hola",False)
print (type(t))
print (t[1])
#la tupla es de una dimención fija
# a la lista se le puede agregar más elemntos
#pero a la tupla no se le puede agregar más elemntos
#No puedo modificar los elementos de una tupla
#intentaremos modificar asignar un valor nuevo a un elemento
t[0] = "Hola"
#no se puede por que es una tupla
#Tema Diccionaros
#no tienen índice sino una clave
d = {'Clave1':[1,2,3],
4: True
}
print (d['Clave1'])
#se les conoce como matricies asociativas
#Ojo en la
d[4] = "Hola"
print (d[4])
#las listas y tublas son secuencias
#por tanto no es psible hacer Slaisi
print (d[0:2])
| false |
a666ccdc61aa6b3db07a08e4f5f630ba50e34967 | luke0b1000/algorithms | /merge_sort.py | 1,614 | 4.1875 | 4 | ###splitting up the array til it becomes 1 which means it is sorted
def mergesort(myarray):
if len(myarray) == 1:
return myarray #[20]
midpoint = len(myarray)//2 #midpoint using integer divison so it does the Math.floor
leftside = myarray[:midpoint] #10 20 30 ... then 10 ... ...20
rightside = myarray[midpoint:] #40 50 80 ... then 20 30 ... then ...30
sortleft = mergesort(leftside) #so once the left side got sorted goes to next line
sortright = mergesort(rightside) # sort out the right side
myarray = merge(sortleft,sortright) #this is where the magic happens and starts combing the sorted list on each level
return myarray
def merge(leftarray, rightarray):
mergeresult = []
while len(leftarray) != 0 or len(rightarray) !=0: ###something exist on both sides
if len(leftarray) == 0:
mergeresult.extend(rightarray) ## so if nothing on left side, then just take the remaining right sided which is sorted and add to result
rightarray = [] ## empty out the right side
elif len(rightarray) == 0:
mergeresult.extend(leftarray)
leftarray = []
elif leftarray[0] < rightarray[0]:
mergeresult.append(leftarray.pop(0)) ###pop out the zero element to be appended to the merge result
elif leftarray[0] > rightarray[0]:
mergeresult.append(rightarray.pop(0))
return mergeresult #return the sorted list
myarray = [80,30,20,50,40,10, 5]
v = mergesort(myarray)
print(v)
| true |
ff454d4e4aca26d2c7ce85c1878f9254c2cf06d6 | leroypetersen2806/Python-Basics | /5_Conditionals-Booleans.py | 1,921 | 4.3125 | 4 | '''
# Comparisons:
Equal: ==
Not Equal: !=
Greater Than: >
Less Than: <
Greater or Equal: >=
Less or Equal: <=
Object Identity: is # Verifies if the objects are the same in memory (have the same id)
'''
if True:
print('Conditional was True') # Executes if condition after if statement is true
if False:
print('Conditional was True') # Will not execute as condition is False
language = "Python"
#- If, elif, else statement (Python does not have a switch case statement)
if language == "Python":
print('Langauge is Python')
elif language == "Java":
print('Langauge is Python')
else:
print("No match")
'''
# Boolean operations
and
or
not
'''
#- Using Boolean operations
user = "Admin"
loged_in = True
#- Using the 'and' keyword
if user == "Admin" and loged_in:
print("Admin Page")
else:
print("Bad Credentials!")
#-using the 'or' keyword
if user == "Admin" or loged_in:
print("Admin Page")
else:
print("Bad Credentials!")
#-using the 'not' keyword
if not loged_in: # If not false
print("Please Log In")
else:
print("Welcome")
# Object Identity - Test if two objects has the same id
a = [1, 2, 3]
b = [1, 2, 3]
print(id(a)) # Returns id of a (Memory address)
print(id(b)) # Returns id of a (Memory address)
print(a == b) # Evaluates to true
print(a is b) # Evaluates to False as it does not have the same address/id's
b = a
print(a is b) # Evaluates to True as it has the same address/id
print(id(a)) # Returns id of a (Memory address)
print(id(b)) # Returns id of a (Memory address)
print(id(a) == id(b)) # Evaluates to True as the id's match
'''
# False Values:
- False
- None
- Zero of any numeric type, all other values evaluates to True
- An empty sequence. E.g '', [], ()
- An empty mapping. E.g. {}
'''
condition = False
if condition:
print("Evaluates to True")
else:
print("Evaluates to False")
| true |
beaf6932b8cd878622b5707955fb595cc71a4924 | iamsarin/LearnDataStructuresWithPython | /M01-Search/BinarySearch.py | 734 | 4.125 | 4 | def binary_search(arr, search_key):
len_of_arr = len(arr)
left = 0
right = len_of_arr - 1
while left <= right:
mid = (right + left) // 2
# print('left ', left, '\tright ', right, '\tmid ', mid)
if search_key == arr[mid]:
return True
elif search_key > arr[mid]:
left = mid + 1
elif search_key < arr[mid]:
right = mid - 1
return False
print('This is Binary Search. I\' do search better than sequential search but my list must ordered')
print('Worst Case is O(log n)')
print('I have [1, 2, 3, 4, 5, 6, 7, 25]')
print('Has 3 ? ', binary_search([1, 2, 3, 4, 5, 6, 7, 25], 3))
print('Has 8 ? ', binary_search([1, 2, 3, 4, 5, 6, 7, 25], 8))
| false |
ec9a9f38afa698ebfd51bcc4565984ab1376d957 | curellich/guias | /guia000/guia000-ej6.py | 767 | 4.28125 | 4 | '''
6. Se necesita un programa que reciba por línea de comando una serie de palabras, hasta que reciba la palabra "exit".
Una vez recibida dicha instrucción, debe mostrar por salida standard las mismas palabras ingresadas, almacenadas en
una lista, pero ordenadas alfabéticamente y cada una debe estar capitalizada.
Resultado Esperado: El programa le solicita al usuario que ingrese y este escribe:
Ingrese palabra: hola
Ingrese palabra: QUE
Ingrese palabra: tal
Ingrese palabra: como
Ingrese palabra: estas
Ingrese palabra: exit
Se espera recibir el siguiente resultado: ['Como', 'Estas', 'Hola', 'Que', 'Tal']
'''
lista = []
texto = 'NULL'
while texto != 'Exit':
texto = input('Ingrese palabra: ').capitalize()
lista.append(texto)
print(sorted(lista))
| false |
f2eaceda4d3e9e3b431d80e2d64add481d2eea58 | curellich/guias | /Ejercicio Recursividad/fibonacci.py | 596 | 4.1875 | 4 | def fibonacci_recursiva(n):
if n == 0:
return 0
if n == 1:
return 1
if n > 1:
return (fibonacci_recursiva(n - 1) + fibonacci_recursiva(n - 2))
def fibonacci_iterativa(n):
if n == 0 or n == 1:
return 0;
ant2=0
ant1=1
for i in range(2,n+1):
fibn=ant1+ant2
ant2=ant1
ant1=fibn
return fibn
n = int(input("Ingrese un numero para calcular serie fibonacci\n"))
print(f"Recursiva- La serie fibonacci de {n} es {fibonacci_recursiva(n)}")
print(f"Iterativa- La serie fibonacci de {n} es {fibonacci_iterativa(n)}")
| false |
ef9152668ce87f7b093e15669b04f8367a1d3793 | gnsaddy/Python | /PythonDictionary.py | 927 | 4.21875 | 4 | dict0 = {1: 'a', 2: 'b'}
print(dict0)
dict1 = {} # empty dictionary
print(dict1)
# accessing the dict with the key value
print(dict0[1])
dict2 = {'name': 'aditya raj', 'address': 'new delhi', 'age': 20}
print("name:-", dict2['name'], "age:-", dict2['age'], "address:-", dict2['address'])
# adding a new key value
dict2['profession'] = 'Student'
print(dict2)
# checking the present key in a dict
print('address' in dict2) # in keyword return the boolean value
# getting the list of keys and value from a existng dict
print(list(dict2.keys())) # list of keys
print(list(dict2.values())) # list of values
# dictionary creation using the dict keyword
new_dict = dict(country='India', state=['Delhi', 'Bihar', 'Maharastra', 'Rajasthan'])
print(new_dict)
# deleting value from the dictionary
del new_dict['state']
print(new_dict)
# dict length
print(len(dict2))
dict3 = sorted(list(dict2))
print(dict3)
| true |
d1b45536b4717bec3f5f5efdc1f96e0fde33ba1a | Diviyansha/python-codes | /function.py | 278 | 4.34375 | 4 | #!/root/Desktop/python
def factorial(num):
if(num==1):
return num
else:
num*factorial(num-1)
num= int(raw_input("enter number"))
if num<0:
print "the factorial cannot be calculated"
elif num=0:
print " the factorial is 0"
else:
print "the factorial is",factorial(num)
| true |
801549f4361cd32021664cf98cb9245b9e48a288 | agerista/code-challenge-practice | /other_code_challenges/longest_word.py | 2,084 | 4.25 | 4 | def longest_word(str):
"""Return the length of the longest word in the a sentence
>>> longest_word("The quick brown fox jumped over the lazy dog")
6
>>> longest_word("May the force be with you")
5
>>> longest_word("What if we try a super-long word such as otorhinolaryngology")
19
"""
count = 0
phrase = str.split()
for word in phrase:
if len(word) > count:
count = len(word)
return count
def longest_word2(phrase):
"""
Return a list of all words in the phrase, along with the length of the
longest word in the phrase.
>>> longest_word2("The quick brown fox jumped over the lazy dog")
(6, ['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog'])
>>> longest_word2("May the force be with you")
(5, ['May', 'the', 'force', 'be', 'with', 'you'])
>>> longest_word2("What if we try a super-long word such as otorhinolaryngology")
(19, ['What', 'if', 'we', 'try', 'a', 'super-long', 'word', 'such', 'as', 'otorhinolaryngology'])
"""
length = 0
count = 0
len_list = []
for char in phrase:
if char != " ":
length += 1
elif char == " ":
len_list.append(phrase[:length])
phrase = phrase[length + 1:]
length = 0
if count < length:
count = length
len_list.append(phrase[:length])
return count, len_list
def longest_word_fancy(phrase):
"""Return the length of the longest word in the a sentence
>>> longest_word("The quick brown fox jumped over the lazy dog")
6
>>> longest_word("May the force be with you")
5
>>> longest_word("What if we try a super-long word such as otorhinolaryngology")
19
"""
phrase = sorted(phrase.split(), key=len)
return phrase[-1]
################################################################################
if __name__ == "__main__":
import doctest
result = doctest.testmod()
if not result.failed:
print "\nALL TESTS PASSED. GOOD WORK!\n"
| true |
016f32964ae01adad69bed785c479aae9073dd41 | ShreelataKandkoor/PYTHON | /dictionaries.py | 404 | 4.3125 | 4 | #Dictionaries
my_stuff = {'key1':"value",'key2':"value2"}
print(my_stuff['key2'])
my_stuff2 = {"key1":"value",'key2':"value2",'key3':{'123':[1,2,'grabMe']}}
print(my_stuff2['key3']['123'][2])
print(my_stuff2['key3']['123'][2].upper())
my_stuff3 = {'lunch':'pizza','bfast':'eggs'}
print(my_stuff3['lunch'])
my_stuff3['lunch'] = 'burger'
my_stuff3['dinner'] = 'pasta'
print(my_stuff3)
| false |
c7ab3c55cd058988d77c760a76cb591eeecd6401 | ChemistGoneRogue/PythonTheEasyWay | /ifStatements.py | 491 | 4.25 | 4 | number1=10 #we can give it any name, the previous examples used a as an example
mississippi=90 #see, the name can be anything, as long as it starts with a letter
a=91 #we can still use a
if number1+mississippi>=100: #IF the left side is greater or equal to the right
print ("number1+missisippi is at least 100") #do this (yes, it has to be indented)
if number1+a==100: #IF the left is exactly equal to the right
print ("number1+a is at least 100") #do this, unless the IF is not true
| true |
ff3618996afdfbcb34c09c1fc355919c7ae82338 | JonesQuito/estudos_de_python | /cursos/python_ufrn/dicionarios/metodos.py | 874 | 4.6875 | 5 | """
Os métodos são semelhantes às funções, porém a sintaxe é diferente.
Para usarmos funções, chamamos o nome da função e passamos os argumentos
para seus parâmetros, se houver.
No caso dos métodos, os mesmos são precedidos pelo objeto que o contém
Ex: nome_objeto.nome_metodo()
"""
ing2esp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
inventario = {'abacaxi': 430, 'banana': 312, 'laranja': 525, 'peras': 217}
print(inventario.keys()) # O método keys() retorna todas as chaves de um dicionário
print(inventario.values()) # O método values() retorna todos os valores de um dicionário
print(inventario.items()) # O método items() retorna todos os itens de um dicionário
print(ing2esp.__contains__('one')) # O método __contains__('chave') retorna True se a chave existe no dicionário | false |
02212ed5995c44504740364b7df4d8307ea0da0c | JonesQuito/estudos_de_python | /cursos/python_ufrn/dicionarios/operacoes_dicionario.py | 675 | 4.15625 | 4 | # o comando 'del' remove um par chave-valor do dicionario
inventario = {'abacaxi': 430, 'banana': 312, 'laranja': 525, 'peras': 217}
print(inventario)
# excluíndo o elemento peras do inventario
del inventario['peras']
print(inventario)
# reinserindo o elemento 'peras' no inventário
inventario['peras'] = 154
print(inventario)
# Alterando a quantidade de peras para zero
inventario['peras'] = 0
print(inventario)
# Adicionando uvas no inventário
inventario['uvas'] = 52
print(inventario)
# Para obtermos o número de pares chave-valor usamos a função len(nome_dicionario)
tamanho_inventario = len(inventario)
print('Tamanho do inventário:', tamanho_inventario) | false |
77dc562e5cd203153be9a449774b8160dd6b88ee | CameronSquires/primenumbers | /primenumbers.py | 566 | 4.21875 | 4 | userInput = int(input("Please input an integer to test if it is prime. "))
if userInput <= -1:
print("As the topic of negative prime numbers is still being debated today, I will not currently include them. Please try again later. ")
exit()
def checkPrimeValidity():
x = userInput
y = x
validityList = 0
while y > 0:
x=userInput%y
if x==0:
validityList += 1
y -= 1
if validityList == 2:
print("This number is prime.")
else:
print("This number is not prime.")
checkPrimeValidity() | true |
2253f6aabf1fde033546bae8a8f81ddaf4793376 | TiMusBhardwaj/pythonExample | /python-and-mongo-master/Tree/place-convert-given-binary-tree-to-doubly-linked-list.py | 1,703 | 4.125 | 4 |
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __repr__(self):
return str(self.data)
class List_Node:
# Constructor to create a node node in linked list
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
def __repr__(self):
return str(self.data)
# Print doubly linked List
def print_dll(head):
if not head:
return
while head.next:
print(head.data, end="<->")
head = head.next
print(head.data)
# This Method converts Tree into Doubly Linked List using reverse in order traversal
def convert(root, head):
if not root:
return None
# recursively convert right subtree
if root.right:
head = convert(root.right, head)
node = List_Node(root.data)
# Move head to newly created node, previous head will become next
if head:
node.next, head.prev = head, node
head = node
#recursivly convert left subtree
if root.left:
head = convert(root.left, head)
return head
# This Method converts Tree into Doubly Linked List using reverse in order traversal
def convert_and_print(root):
head = None
head = convert(root, head)
print_dll(head)
# Driver Program
if __name__ == '__main__':
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.left.right.left = Node(8)
root.left.right.left.left = Node(9)
root.left.right.left.left.left = Node(10)
root.right.right = Node(7)
convert_and_print(root) | true |
30f3fd974cfda71b334f7cf2fee07b37e33628ab | tuantla80/Data-Structure-and-Algorithm | /Array/unique_chars_in_str.py | 647 | 4.28125 | 4 | """
Problem:
Given a string, determine if it is comprised of all unique characters.
For example: The string 'abcdef' has all unique characters and should return True.
The string 'abcdefa' contains duplicate characters and should return False.
"""
def uni_chars_in_str(s):
"""
Solution using set() in Python
"""
return len(set(s)) == len(s)
if __name__ == "__main__":
s = 'abcdef'
print('string is: {} \nIs it unique characters in string? {}'.format(s, uni_chars_in_str(s)))
print('\n')
s = 'abcdefa'
print('string is: {} \nIs it unique characters in string? {}'.format(s, uni_chars_in_str(s)))
| true |
c24ccf5306855463127b4fa376341aa5c544bf7f | tuantla80/Data-Structure-and-Algorithm | /Array/sentence_reversal.py | 566 | 4.3125 | 4 | """
Problem:
Given a string of words, reverse all the words.
Example: Given: 'This is a nice place '
Return: 'place nice a is This'
"""
def sentence_reversal(s):
"""
Solution:
- Step 1: split string into a list of words
- Step 2: reverse the list
- Step 3: join all the words to be a sentence
Ref: split() refer to https://www.w3schools.com/python/ref_string_split.asp
"""
return ' '.join(reversed(s.split()))
if __name__ == "__main__":
print("reversed sentence: ", sentence_reversal(s='This is a nice place '))
| true |
0a3c94f151d1a41e810abc798a935df8816fe9a2 | tuantla80/Data-Structure-and-Algorithm | /Array/array_unique_pair_sum.py | 673 | 4.25 | 4 | """
Problem:
Given an integer array, output all the unique pairs that sum up to a specific value k.
So the input:
pair_sum([1, 5, 6, 3, 2, 7, 7], 8)
would return 2 pairs:
(1, 7), (5,3), (6, 2)
"""
def array_unique_pair_sum(arr, k):
lookup = set()
output = set()
for number in arr:
if (k - number) in lookup:
output.add((k - number, number))
else:
lookup.add(number)
return output
if __name__ == "__main__":
arr = [1, 5, 6, 3, 2, 7, 7]
k = 8
output = array_unique_pair_sum(arr, k)
print(" number of pairs = {} \n output = \n {}".format(len(output), '\n '.join(map(str, output))))
| true |
299e4ff5a3d4838b512865b8275c9ebb63b5c2ed | tuantla80/Data-Structure-and-Algorithm | /Searching and Sorting/insertion_sort.py | 660 | 4.1875 | 4 | """
Useful links
https://visualgo.net/en/sorting
https://www.toptal.com/developers/sorting-algorithms
Insertion sort:
O(n^2) but better than O(n^2) of bubble and selection sorts
"""
def insertion_sort(arr):
for i in range(1, len(arr)):
current_value = arr[i]
position = i
while position > 0 and arr[position - 1] > current_value:
arr[position] = arr[position - 1] # shift operation
position -= 1
# end of while
arr[position] = current_value
return arr
if __name__ == "__main__":
arr = [1, 2, 5, 0, 4]
new_arr = insertion_sort(arr)
print('after insertion sort', new_arr)
| true |
de4bb3047c49fc73c46752c232db2e586c368f3d | ralphSpencer/simple-python-projects-beginner | /NumberGuesser.py | 1,713 | 4.40625 | 4 | # Guess The Number
# Write a programme where the computer randomly generates a number between 0 and 20.
# The user needs to guess what the number is.
# If the user guesses wrong, tell them their guess is either too high, or too low.
import random # import random module
print("Welcome to \"Guess the Number\".") # title of the game
randAnswer = random.randrange(0,20) # system selects a number for user to guess
guessTry = 1 # initialized starting point of loop
while guessTry >= 1: # until guessTry is not 0 or a negative number the loop will continue
userGuess = int(input("\nSelect a number from 0-20: ")) # ask input from the user
if userGuess >= 0 & userGuess <= 20: # checks if user input is not greater that 20 or lower than 0
if userGuess != randAnswer: # if guess is incorrect
if userGuess > randAnswer+3: # if the guess is too far from the answer
print("Number is Too High")
elif userGuess >= randAnswer+1: # if the guess is closer but higher from the answer
print("Number is High")
elif userGuess < randAnswer-3: # if the guess is too low from the answer
print("Number is Too Low")
elif userGuess <= randAnswer-1: # if the guess is closer but lower from the answer
print("Number is Low")
elif userGuess == randAnswer: # if the answer is correct
print("You are correct")
break # breaks the loop
else: # if the guess is greater than 20 or lower than 0
print("Please select a number from 0-20 only \n")
guessTry += 1
print("The answer is " + str(randAnswer)) # shows the answer
| true |
f443dc4c0998fee46a828a684510733c6dfe8150 | codeART96/TDD-exercises-in-pyhton | /Simple Calculator/src/simple_calculator.py | 279 | 4.25 | 4 | # this function adds more than two numbers
def add(*args):
sum = 0
for i in args:
sum += i
return sum
# this function multiplies more than two numbers
def multiply(*args):
sum = 1
for i in args:
sum *= i
return sum
print(multiply(10, 5)) | true |
37dccb1a51c15ae5ebb12a028fdccccfbd6ea1ce | Ho-Jack/daily-note | /python-代码-笔记/lesson_03_流程控制语句/code/06.循环语句.py | 1,168 | 4.4375 | 4 | # 循环语句
# 循环语句可以使指定的代码块重复指定的次数
# 循环语句分成两种,while循环 和 for循环
# while循环
# 语法:
# while 条件表达式 :
# 代码块
# else :
# 代码块
# 执行流程:
# while语句在执行时,会先对while后的条件表达式进行求值判断,
# 如果判断结果为True,则执行循环体(代码块),
# 循环体执行完毕,继续对条件表达式进行求值判断,以此类推,
# 直到判断结果为False,则循环终止,如果循环有对应的else,则执行else后的代码块
# 条件表达式恒为True的循环语句,称为死循环,它会一直运行,慎用!
# while True :
# print('hello')
# 循环的三个要件(表达式)
# 初始化表达式,通过初始化表达式初始化一个变量
# i = 0
# # 条件表达式,条件表达式用来设置循环执行的条件
# while i < 10 :
# print(i)
# # 更新表达式,修改初始化变量的值
# i += 1
# 创建一个执行十次的循环
i = 0
while i < 10 :
i += 1
print(i,'hello')
else :
print('else中的代码块') | false |
1007a9e2a84dc838d3705a11b26f49bf03dcf8ca | OMR5221/python3_data_analysis | /1_dataStructs_algorithms/1.4_find_large_small_val.py | 1,298 | 4.3125 | 4 | # Issue: Want to make a list of the largest and smallest N items in a collection
# heapq: has 2 functions
# 1. nlargest()
# 2. nsmallest()
# Heap: orders elemtns of a list
# Good for instances in which we want only a few of a large N number of elements
# USE MIN OR MAX() IF YOU JUST NEED ONE Value
# uSE A SPLIT/SLICE IF YOU need a larger collection of the values in N: sorted(items)[:N]
import heapq
nums = [1,8,2,23,7,-4,18,23,42,37,2]
print(heapq.nlargest(3, nums))
print(heapq.nsmallest(3, nums))
# Can be used with a more complex data structure:
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.3},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheapest_stocks = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
print(cheapest_stocks)
expensive_stocks = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
print(expensive_stocks)
# Orders list: The heap[0] element is always the smallest
heap = list(nums)
heapq.heapify(heap)
print(heap)
# pop the element in 0 index
print(heapq.heappop(heap))
print(heapq.heappop(heap))
print(heapq.heappop(heap)) | true |
6f110a62ce3e947a30e522aa1ce67aa2a5fc62aa | golianil/911-call | /module1-2.py | 242 | 4.21875 | 4 | ''' sequence of words as input and prints the words in
a sequence after sorting them alphabetically. '''
sentence = input("Enter the sentence ")
word = sentence.split()
print(word)
#sort the word in ascending order
word.sort()
print(word)
| true |
809d153d3507bfbd99e5bded40504021de4bfa3b | nevepura/python3 | /python_tricks/3.1_first_class_functions.py | 1,353 | 4.25 | 4 | # Mantra: Evey function is an object!
def yell(text):
return text.upper()
def whisper(t):
return t.lower() + '...'
# functions can be passed as arguments
def greet(func):
greeting = func("Hello, stranger.")
print(greeting)
# inner functions == closures. Local state == text parameter, is kept and used outside this context, in the call in main()
# closure is like configuring with text parameter
def get_speak_func(text, volume):
def speak_quiet():
return text.lower() + '...'
def speak_loud():
return text.upper()
if volume > 0.5:
return speak_loud
else:
return speak_quiet
def make_chain(s):
def chain(x):
return s + ' ' + x
return chain
def main():
'''
# Greeting using yell or whisper as parameter
greet(yell)
greet(whisper)
# map, convert to list to see values
m = map(yell, ('apple', 'pear', 'berry'))
print(list(m))
# return inner function references and call function with '()'
speech = get_speak_func("I have a dream", 0.6)()
print(speech)
murmur = get_speak_func("I am Not SUre about THis", 0.1)()
print(murmur)
# chain strings
intro = make_chain("My name is")
intro_john = intro("John")
print(intro_john)
print(intro("Step"))
'''
if __name__ == "__main__":
main()
| true |
8c9c475776e47361319924d01bf45d62eb72da8f | stefan-solmundson/PythonTests | /for_loops.py | 602 | 4.25 | 4 | # https://www.w3schools.com/python/python_for_loops.asp
# range starts at the first value & ends BEFORE the last value
for a in range(0, 10): # for(i=0; i++; i<10)
print("a = {0}".format(a))
print()
for b in range(0, 1):
print("b = {0}".format(b))
print()
for c in range(1, 10):
print("c = {0}".format(c))
print()
# Error: NO RANGE
for d in range(1, 1):
print("d = {0}".format(d))
print()
for e in range(1, 2):
print("e = {0}".format(e))
print()
for f in range(0, 10, 2):
print("f = {0}".format(f))
print()
for g in [0, 4, 22, -5]:
print("g = {0}".format(g))
print()
| true |
324a440914426e0c9a5c8f1f4812efcf0383f866 | ahmettkara/class2-OOP-assigment-week06 | /OOP-assignment_2.py | 2,854 | 4.3125 | 4 | class MobilePhone():
model=[]
year=[]
price=[]
def __init__(self, model,year,price,phonebook={}):
self.model=model
self.year=year
self.price=price
self.phonebook=phonebook
MobilePhone.model.append(self.model)
MobilePhone.year.append(self.year)
MobilePhone.price.append(self.price)
def phone_data(self): # ayrı ayrı telefon bilgisi gösterme. instance method.
print(f"""
MODEL :{self.model}
YEAR :{self.year}
PRICE :{self.price}\n""")
def show_phonebook(self): #rehberi görüntüleme. instance method.
print(self.phonebook)
def search_name(self): #rehberde kişi sorgulama. instance method.
name = input("Enter a name you want to search: ").upper()
if name in self.phonebook:
print(f"{name} is in your phonebook")
else:
print(f"{name} is not in your phonebook")
def add_person(self): #rehbere kişi ekleme. instance method.
self.show_phonebook()
while True:
name=input("Enter a name you want to add: ").upper()
if name not in self.phonebook:
number = input("Enter the number: ")
self.phonebook[name]=number
print("The person is added.")
self.show_phonebook()
break
else:
print(f"{name} is already in the phonebook.")
again=input("Do you want to add different person? Y/N: ").upper()
if again=="N":
break
def remove_person(self): #rehberden kişi silme. instance method.
self.show_phonebook()
name=input("Enter the name you want to remove: ").upper()
if name in self.phonebook:
del self.phonebook[name]
print(f"{name} is removed from the phonebook")
self.show_phonebook()
else:
print(f"There is no {name} in the phonebook ")
@classmethod
def sorted_price(cls): #telefon fiyatlarını küçükten büyüğe sıralama. class method.
MobilePhone.price.sort()
print(MobilePhone.price)
@classmethod
def all_phones(cls): #tüm telefonların bilgisini gösterme. class method.
for i in range(len(MobilePhone.model)):
print(f"""
MODEL :{MobilePhone.model[i]}
YEAR :{MobilePhone.year[i]}
PRICE :{MobilePhone.price[i]}\n""")
siemens=MobilePhone("C45",2001,200,{"AHMET":"06123456", "ABDULLAH":"063528779"}) #
sony=MobilePhone("Xperia",2018,750,{"MUSTAFA":"0665897", "MAHMUT":"065631124"})
samsung=MobilePhone("Note5",2015,400,{"JACK":"06488221", "JOHN":"066633454"})
# MobilePhone.all_phones()
# samsung.phone_data()
# MobilePhone.sorted_price()
# siemens.show_phonebook()
# siemens.add_person()
# sony.remove_person()
# samsung.search_name() | false |
6e7f3b2c36995b0511398d4ef4f41f4c0a36e013 | Datagatherer2357/Gareth-Duffy-GMIT-Problem-sets-Python-scripts | /fib.py | 968 | 4.125 | 4 | # Gareth Duffy 22-1-2018
# A program that displays Fibonacci numbers. (Excercise 1 Programming & Scripting)
# https://en.wikipedia.org/wiki/Fibonacci_number
#"""This function returns the nth Fibonacci number.""" (Docstring)
# The point of functions is to take in inputs and return something.
def fib(n):
i = 0
j = 1
n = n - 1
while n >= 0: # while loop, condition that n is greater or equal to zero
i, j = j, i + j
n = n - 1
return i # The return statement is used when a function is ready to exit and return a value back to
# its caller, without it, the function returns nothing
# Test the fib function with the following value:
x = 15 # assigning the integer 15 to the new "x" variable
ans = fib(x) # calling fib function and assigning it to new "ans" variable
print("Fibonacci number", x, "is", ans)
# My name is Gareth, so the first and last letter of my name (G + H = 7 + 8) give the number 15. The 15th Fibonacci number is 610.
| true |
4c7a2b72a5c1666c2bb6affa431c54b2e0d74d0f | KaiserPhemi/python-101 | /scripts_examples/time_in_seconds.py | 708 | 4.3125 | 4 | # This program expreses time in seconds only. Input is in hours, minutes and seconds
print("This program expreses time in seconds only. Input is in hours, minutes and seconds.")
print("")
hour_time = float(input("Kindly input time in hours and hit 'Enter': "))
print("")
min_time = float(input("Input the minutes value and hit 'Enter': "))
print("")
sec_time = float(input("Input the seconds value and hit 'Enter': "))
def time_conv(hour_time, min_time, sec_time):
time_sec = ((hour_time * 3600)+(min_time*60)+sec_time)
return time_sec
print(str(hour_time)+" hours, "+str(min_time)+" minutes, "+str(sec_time)+" seconds is "+str(time_conv(hour_time, min_time, sec_time))+" seconds expressed in seconds") | true |
5f346011da849002f3e90d81f2771074caf3d920 | LeoceanY/Typical_Sort | /6_heap_sort.py | 932 | 4.15625 | 4 | # 堆排序
# http://blog.csdn.net/xiaoxiaoxuewen/article/details/7570621/
def adjust_heap(lists,i,size):
'''lists 是数组,i为根节点的下标,size为数组长度'''
#节点i的左右孩子
lchild = 2*i+1
rchild = 2*i+2
max = i
# size/2的长度限制,是因为所有的非叶子节点都在数组的前一半
if i <size/2:
#若左叶子大,则交换
if lchild<size and lists[lchild]>lists[max]:
max = lchild
if rchild<size and lists[rchild]>lists[max]:
max = rchild
if max != i:
lists[max],lists[i] = lists[i],lists[max]
#对于非叶子节点,递归调整
adjust_heap(lists,max,size)
def build_heap(lists,size):
#对于每个节点,都进行大顶堆调整
for i in range(0,size/2)[::-1]:
adjust_heap(lists,i,size)
def heap_sort(lists):
size = len(lists):
build_heap(lists,size)
for i in range(0,size)[::-1]:
lists[0],lists[i] = lists[i],lists[0]
adjust_heap(lists,0,i) | false |
ee972e7b4fa1a8e2cb756b8d574ae28fed0a7fb0 | jgullbrand/parsing_moviedata | /movie_reader.py | 1,098 | 4.15625 | 4 | # Taking movie data and printing 10 random titles based on release date
# JGullbrand - January 30th, 2019
import json
import random
with open("movies.json") as json_file:
movie_list = json.load(json_file)
#this data was pulled from the github acct mentioned in the readme file
movie_titles = []
#empty list to store the movie titles
while True:
#runs unless somenone types 'q' to break the loop
prompt = ("what year would you like to see a list of movies from? Please enter year as yyyy or type 'q' to exit \n> ")
#adding in a bit of interactivity
response = input(prompt)
try:
if response == 'q':
break
else:
for movie_info in movie_list:
if movie_info["year"] == int(response):
movie_titles.append(movie_info["title"])
random.shuffle(movie_titles)
#shuffles the list of movie_titles
for movies in movie_titles[:10]:
#taking 10 movies from the list
print(movies)
except ValueError:
# just in case someone types in 'two thousand and six' or another string, rather than 2006
print("Please enter in the year in the format yyyy (2018, for example)") | true |
7c46fb611145787e918e1120ccd160705a418d00 | masudiit/AppliedAi_Python_Assignment | /AppliedAI_Python_Assignment_1/4.Permutation_Combination.py | 1,675 | 4.25 | 4 | """
The number of permutations of n objects taken r at a time is determined by the following formula:
P(n,r)=n!(n−r)!
n! is read n factorial and means all numbers from 1 to n multiplied e.g.
5!=5⋅4⋅3⋅2⋅1
This is read five factorial. 0! Is defined as 1.
0!=1
Example
A code have 4 digits in a specific order, the digits are between 0-9.
How many different permutations are there if one digit may only be used once?
A four digit code could be anything between 0000 to 9999, hence there are 10,000 combinations
if every digit could be used more than one time but since we are told in the question that one digit
only may be used once it limits our number of combinations. In order to determine the correct number
of permutations we simply plug in our values into our formula:
P(n,r)=10!(10−4)!=10⋅9⋅8⋅7⋅6⋅5⋅4⋅3⋅2⋅16⋅5⋅4⋅3⋅2⋅1=5040
In our example the order of the digits were important, if the order didn't matter
we would have what is the definition of a combination. The number of combinations
of n objects taken r at a time is determined by the following formula:
C(n,r)=n!(n−r)!r!
"""
def factorial(n):
fact = 1;
for i in range(2,n+1):
fact = fact * i;
return fact;
# def to calculate permutation
def nPr(n, r):
pnr = factorial(n) / factorial(n - r);
return pnr;
# def to calculate combination
def nCr(n, r):
cnr = (factorial(n) / (factorial(r) * factorial(n - r)))
return cnr
if __name__ == '__main__':
n = 10
r = 4
print('Permutation> ' + str(int(nPr(n, r))))
print('Combination> ' + str(int(nCr(n, r))))
| true |
6457bee511d3c7f36e87d618d8e85e5d8ab9f313 | alvinsen/pycode | /leetcode/21_MergeTwoSortedLists.py | 2,560 | 4.21875 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
import time
"""
Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list.
The new list should be made by splicing together the nodes of the first two lists.
这道题主要是用到了归并排序的思想:
维护两个指针对应两个链表,因为一般会以一条链表为基准,比如说l1, 那么如果l1当前的元素比较小,那么直接移动l1即可,
否则将l2当前的元素插入到l1当前元素的前面。
算法时间复杂度是O(m+n),m和n分别是两条链表的长度,空间复杂度是O(1),代码如下:
这个题类似的有Merge Sorted Array: 对数组进行合并操作。
扩展题目Merge k Sorted Lists, 这是一个在分布式系统中比较有用的基本操作。
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __len__(self):
size = 0
while True:
size += 1
if self.next == None:
break
self = self.next
return size
def __str__(self):
result = []
while True:
result.append(str(self.val))
if self.next == None:
break
self = self.next
result_str = ' -> '.join(result)
return result_str
__repr__ = __str__
class Solution:
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def mergeTwoLists(self, l1, l2):
# 合并两个链表
last = dummy = ListNode(0)
dummy.next = l1
while l1 and l2:
if l1.val > l2.val:
node = l2.next
l2.next = last.next
last.next = l2
l2 = node
else:
l1 = l1.next
last = last.next
if l2:
last.next = l2
return dummy.next
if __name__ == '__main__':
sol = Solution()
l1 = ListNode(1)
l2 = ListNode(2)
l1_1 = ListNode(3)
l1_2 = ListNode(5)
l1_3 = ListNode(9)
l1.next = l1_1
l1_1.next = l1_2
l1_2.next = l1_3
l2_1 = ListNode(4)
l2_2 = ListNode(6)
l2_3 = ListNode(8)
l2.next = l2_1
l2_1.next = l2_2
l2_2.next = l2_3
start_time = time.time()
print u'原始链表为l1:%s, l2: %s,' % (l1, l2)
result = sol.mergeTwoLists(l1, l2)
use_time = time.time() - start_time
print u'合并后的链表为:%s' %(str(result))
print u'耗时:%s' %use_time
| false |
2bdba4db2b4738ab646071f740d58716f3532346 | swetabiradar/firstTrial | /unique_morse_code_simplified.py | 1,625 | 4.34375 | 4 | #!/usr/bin/env python
"""
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cba" can be written as "-.-..--...", (which is the concatenation "-.-." + "-..." + ".-"). We'll call such a concatenation, the transformation of a word.
Return the number of different transformations among all words we have.
Example:
Input: words = ["gin", "zen", "gig", "msg"]
Output: 2
Explanation:
The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
"""
class Solution:
def __init__(self, words=[]):
self.words = words
def toStr(self):
return self.words
def uniqueMorseRepresentations(self):
print(self.words)
morse_list = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
rep = {"".join(morse_list[ord(c)-ord('a')]for c in word)for word in self.words}
print(rep)
return (len(rep))
words = ["gin", "zen", "gig", "msg"]
a = Solution(words)
print(a.uniqueMorseRepresentations())
| true |
70f4e4b3d63c4cc3c3a9bd75d275f144d00f7051 | djping/learn-python | /one.py | 2,523 | 4.15625 | 4 | # True == 1 False == 0
print(True + 1) #the value is 2
# bool ->bool(a) == False => a = "" () {} [] 0 None
print(bool('')) #an eg
# format
print("This is knowledge about format!") #one
print("a is {},b is {}".format(2,"String")) #two
print("she likes {0},but he likes {1},and parents like {0}" #three
.format("apple","orange"))
a = "Her name is {name}".format(name="Lily") #four
print(a)
# s% d% f
print('it is %d years age,%s...'%(3,"that"))
name = 'aaaa'
print(f"what is {name}")
# is and ==
list1 = [1,2,3,4]
list2 = list1
print("This is about is and == operate: ")
print(list2 == list1) #is checks if two variables' object whether the same
print(list1 is list2) #== checks if values are the same
list2 = [1,2,3,4]
print(list2 is list1)
print(list2 == list1)
# None
# if
print("'Hello'" if 3 > 2 else 2)
print('\n')
# []{}()
print("Below is about Sequence!")
#list 切片
aList = [1,2,3,5]
c1 = aList[1:]
c2 = aList[:3]
c3 = aList[1:3]
c4 = aList[::] #copy aList
c5 = aList[:-1]
c6 = aList[::2] #步长为2
c7 = aList[::-1] #反向复制list
# c6 = aList[::]
print("c1:{},c2:{},c3:{},c4:{},c5:{}".format(c1,c2,c3,c4,c5))
#c1:[2, 3, 5],c2:[1, 2, 3],c3:[2, 3],c4:[1, 2, 3, 5],c5:[1, 2, 3]
print(aList)
#list 函数方法 will change list
bList = ["str",2,5,7,8]
bList.remove("str")
bList.append("end")
print("bList is :",bList)
cList = ["a","b","c"]
cList.pop()
print("cList is :",cList)
bList.extend(cList)
print("bList is :",bList)
# bList.index(7)
# bList.insert(1,3)
#tuple ()
q,w,e = (1,2,3) # q=1,w=2,c=3
# q,w,e = 3,2,1
t = ("s","b")
length1 = len(t)
length2 = len(bList)
print("t's len is {} and bList's len is {}".format(length1,length2))
print('\n')
#dictionary {} .values()/.keys()/.get/.setDefault()
d = {
"name":'djp',
"age":18,
"grade":3
}
d["name"] #djp
v = d.values()
k = d.keys()
print("d's values are {} type {} ,d's keys are {} type {}"
.format(v,type(v),k,type(k)))
# a = input("your input is: ")
# print("a is ",a)
print('\n')
#iterable
for i in k: #第一种
print(i)
ite_d = iter(k)
print(next(ite_d))
print(list(k)) #third method
#对list、tuple,dict的补充
p = (1)
type(p) #int
p = (1,)
type(p) #tuple
l = [7,9,0]
l.index(0) #2
l.insert(1,3) #7,3,9,0
del l[2] #此处2为索引,即删除第三个数
dd = {
"one":1,
"two":2,
"three":3
}
# dd["four"] #报错
dd.get("four") #不会报错
dd.setdefault("four",4)#dd{'one': 1, 'two': 2, 'three': 3, 'four': 5}
del dd["one"] #删除one
#modules
# from math import ceil
# dir(math)
#this line is just for test git aaaaaabb | false |
8d8a839251fddbe5c1c7ed3e97970be77cf0adb0 | mercadder/python | /polygones_rose_v7_toto.py | 1,150 | 4.25 | 4 | import turtle #module tha drawn things
def draw_square():
turtle.setworldcoordinates(-300, -300, 600, 600)
background = turtle.Screen() #create the background
background.bgcolor ("#084B8A") #background color
titi = turtle.Turtle() #titi is an intance of Turtle class
titi.shape("arrow")
titi.color("#084B8A","black")
titi.speed(200)
toto = turtle.Turtle() #titi is an intance of Turtle class
toto.shape("arrow")
toto.color("#084B8A","red")
toto.speed(200)
s = 10 #number of polygon sides
n = s #counter
x = 36 # counter of polygons
d = 360/s #degrees in angle
while x > 0: #to draw in each degree of a circle
while s > 0:
titi.begin_fill()
titi.left(d)
titi.forward(105)
titi.circle(25)
toto.begin_fill()
toto.left(d)
toto.forward(100)
toto.circle(25)
s = s - 1
x = x - 1
s = n
titi.right(10)
titi.end_fill()
toto.left(10)
toto.end_fill()
background.exitonclick() #close background
draw_square()
| false |
5d776f9f1fea9fd9ca3403fffcd4f36cc22df551 | BrunoCesarAngst/aprendendo_python | /praticas/pr008.py | 584 | 4.125 | 4 | #import math
#num = int(input('Digite um número: '))
#raiz = math.sqrt(num)
#print('A raiz de um {} é igual a {}'.format(num,raiz)) - normal
#print('A raiz de um {} é igual a {}'.format(num, math.ceil(raiz))) - arredondado para cima
#print('A raiz de um {} é igual a {}'.format(num, math.floor(raiz)))
from math import sqrt, floor, ceil
num = int(input("Digite um número: "))
raiz = sqrt(num)
print('A raiz de um {} é igual a {}'.format(num, raiz))
print('A raiz de um {} é igual a {}'.format(num, ceil(raiz)))
print('A raiz de um {} é igual a {}'.format(num, floor(raiz)))
| false |
890e2b5008abedbfe21b886f792fdf23428f22b4 | SharinaS/Interview_Problems_and_Solutions | /classes_oop_recursion_DP_functions/args_and_kwargs.py | 1,068 | 4.1875 | 4 | '''
This .py file contains examples of OOP
From Udemy's "Rest API Flask and Python" class:
Chapter: @classmethod and @staticmethod
'''
# *args
# *args allow you to input numbers, which are then transformed into a list. In this case, technically the type is a tuple. You can then use list methods on *args!
def arg_things(*args):
print(type(args))
print(args)
return sum(args)
print(arg_things(3,5,7,12,14,55))
# kwargs allow input to be put into a dictionary. Solo elements will be ignored. You must have args and kwargs written next to each other, weirdly, otherwise, it will say there are too many arguments when there's only room for 0.
def kwarg_things(*args,**kwargs):
print(kwargs)
kwarg_things(23,34,34,50, name="Trevor", location="Seattle" )
########################################
# By the way, You can set up the arguments so that the order in which you enter the arguments does not matter
def no_order(name, location):
print(name)
print(location)
no_order(location='Seattle', name='Trevor')
| true |
d695a0b1aba4e055d976754b47004e8776954adb | Magpiny/pyAutomate | /oop.py | 1,533 | 4.46875 | 4 | """
@author : Samuel Okoth
@filetype : python OOP
# Object Oriented Development in python
# In OOP we have a class and a class in turn has properties and methods
# Properties describe the appearance while methods describes the functionality
# A class has objects
BENEFITS OF OOP
# Code Reusability (Using objects)
# Data hiding
# Extendable code
# Modular Structure
Checkout example below
"""
class School:
def __init__(self, name, population, color):
self.name = name
self.population = population
self.color = color
def learn(self):
print("We go to school to learn")
def play(self):
print("We go to school to play several games")
def calculate(self):
print("Please enter your favourite number : ", end=" ")
namba = int(input())
print(f"We also calculate squares of {namba} in school...")
sqr = namba ** 2
print(f"And the square of {namba} is {sqr}")
school = School("Mulaha Pri School", 896, "Maroon")
print(f"We are from {school.name}", end=" ")
print(f"And our school population is : {school.population}", end=" ")
print(f"And our brand color is {school.color}")
school.play()
school.learn()
school.calculate()
# END OF DISCUSSION
# INHERITANCE IN OOP Python
class AnotherSchool(School):
pass
school_a = AnotherSchool("Siaya Township Pri School", 1050, "blue")
print(f"{school_a.name} has {school_a.population} students and their brand color is {school_a.color}")
| true |
e3c96fbdb6e5243e56d13f6dfdda17c033f4eb84 | fahadkhisaf/eng-57_oop | /cat_object_constructor.py | 1,277 | 4.53125 | 5 | # abstract and create the class dog
class Cat():
# this is a special method
# it comes defined either way but we can polymorth it and re-write it
# this methods stands for intialize class object AKA the constractor in other languages.
# allows us to set attributes to our dog objects
# ...like.. the poor thing doesnt even has a name
# self refers to the instance of the object
def __init__(self, name = 'Garfeild'):
# setting attribute name to instances Cat class
self.name = name
self.age = 12
self.paws = 4
self.fur = 'luxurious orange fur'
self.breed = 'ginger cat'
# this is a method that can be used by a Cat instance
def meow(self, person = ''):
return 'meow, meow, i see you there' + person
def meow_print(self):
print('meow, meow')
def eat(self, food):
return 'nom nom nom' + food
def sleep(self):
return 'zzzzZZZzzzz ZZZzzzZZZ'
def make_lasagne(self):
return 'This lasagne is delicous'
def potty(self):
return "UHHHHHHH!!!!! AHHHH!!!!"
# this print should not be here
# in this file you define the class cat and add attributes and method to the class.
# that is it
# print('This is a very nice cat')
| true |
ab96f74e16ffbe0d3b36523c3c2af56244886501 | AGolunski87/Weather-App | /temperature.py | 353 | 4.15625 | 4 | #funtion that takes a temperature as an argument and then decides if it is warm or not.
def myTemp (temp):
if temp < 0:
print("It a frrezing cold", temp)
elif 1 <= temp <= 10:
print("It is a chilly", temp)
elif 11 <= temp <= 18 :
print("It is a warm", temp)
elif temp >= 19 :
print("It is a hot", temp)
| true |
201a60bb11b9174c5bbebf371a8a3372a8bcf971 | rohithdara/CPE101-Labs | /LAB7/groups.py | 391 | 4.25 | 4 | #Lab 7 Groups
#
#Name: Rohith Dara
#Instructor: S. Einakian
#Section: 01
#This function takes a single list and returns a nested list with each sublist having 3 items (if the end doesn't have enough for 3 items, make a sublist with however many there are left)
#list->list
def groups_of_3(l1):
i = 0
final = []
while i < len(l1):
final.append(l1[i:i+3])
i += 3
return final
| true |
9c5d189b03a5845dd2ac6fb4382915a6cf5ca424 | prashubarry/PyhtonWorkspace | /venv/GeeksForGeeks/MajorityElement.py | 653 | 4.1875 | 4 | def find_majority(arr, n):
max_count = 0
index = -1
# Two Loops for counting the frequency of each element in the array
for i in range(n):
count = 0
for j in range(n):
if arr[i]==arr[j]:
count+=1
if(count > max_count):
max_count = count
index = i
# if max_count is greater than n/2
if(max_count > n//2):
print(arr[index])
else:
print("There are no majority array")
if __name__=='__main__':
n = int(input())
array = list(map(int,input().strip().split()))[:n]
find_majority(array, n)
| true |
a8f9507bd2ee875139d701da2b032bfe1128ecdc | SelinaJiang321/Python-Made-Leetcode-Easy | /easy/from 1 to 100/88. Merge Sorted Array.py | 1,424 | 4.34375 | 4 | """
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2.
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Example 2:
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Constraints:
nums1.length == m + n
nums2.length == n
0 <= m, n <= 200
1 <= m + n <= 200
-109 <= nums1[i], nums2[i] <= 109
"""
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
while m > 0 and n > 0:
# we traverse the arrays from backwards
if nums1[m-1] > nums2[n-1]:
nums1[m+n-1] = nums1[m-1]
m -= 1
else:
nums1[m+n-1] = nums2[n-1]
n -= 1
# if only m > 0 then there is no need to copy the value again, we can only handle the condition when m == 0
while n > 0:
nums1[n-1] = nums2[n-1]
n -= 1
#Time complexity: O(1)
#Space complexty: O(1)
| true |
991d8755c8c5851168dc040d3afbf4f4c6c44be2 | SelinaJiang321/Python-Made-Leetcode-Easy | /medium/from 601 to 700/624. Maximum Distance in Arrays.py | 1,369 | 4.4375 | 4 | """
You are given m arrays, where each array is sorted in ascending order.
You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a and b to be their absolute difference |a - b|.
Return the maximum distance.
Example 1:
Input: arrays = [[1,2,3],[4,5],[1,2,3]]
Output: 4
Explanation: One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.
Example 2:
Input: arrays = [[1],[1]]
Output: 0
Example 3:
Input: arrays = [[1],[2]]
Output: 1
Example 4:
Input: arrays = [[1,4],[0,5]]
Output: 4
Constraints:
m == arrays.length
2 <= m <= 105
1 <= arrays[i].length <= 500
-104 <= arrays[i][j] <= 104
arrays[i] is sorted in ascending order.
There will be at most 105 integers in all the arrays.
"""
class Solution(object):
def maxDistance(self, arrays):
"""
:type arrays: List[List[int]]
:rtype: int
"""
mn, mx = arrays[0][0], arrays[0][-1]
diff = -float("inf")
for ar in arrays[1:]:
mx_diff = abs(mx - ar[0])
mn_diff = abs(mn - ar[-1])
diff = max(diff, mn_diff, mx_diff)
if ar[0] < mn:
mn = ar[0]
if ar[-1] > mx:
mx = ar[-1]
return diff
| true |
7db8dcbb8d16ba89a14dc21ce04df0ef4be4c1d0 | SelinaJiang321/Python-Made-Leetcode-Easy | /easy/from 901 to 1000/917. Reverse Only Letters.py | 1,199 | 4.125 | 4 | """
Given a string s, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: s = "ab-cd"
Output: "dc-ba"
Example 2:
Input: s = "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:
Input: s = "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"
Note:
s.length <= 100
33 <= s[i].ASCIIcode <= 122
s doesn't contain \ or "
"""
class Solution(object):
def reverseOnlyLetters(self, s):
"""
:type s: str
:rtype: str
"""
# convert the string to a list of characters
words = list(s)
# store the reversed of the characters
res_one = list(reversed(words))
res = []
# loop through the two list of characters
#
count = 0;
for value in words :
if value.isalpha() :
while not res_one[count].isalpha():
count += 1
res.append(res_one[count])
count += 1
else:
res.append(value)
res = "".join(res)
return res
| true |
9c057c0705e076de7898256f3f0ac353be19965e | SelinaJiang321/Python-Made-Leetcode-Easy | /easy/from 1101 to 1200/1154. Day of the Year.py | 1,206 | 4.3125 | 4 | """
Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.
Example 1:
Input: date = "2019-01-09"
Output: 9
Explanation: Given date is the 9th day of the year in 2019.
Example 2:
Input: date = "2019-02-10"
Output: 41
Example 3:
Input: date = "2003-03-01"
Output: 60
Example 4:
Input: date = "2004-03-01"
Output: 61
Constraints:
date.length == 10
date[4] == date[7] == '-', and all other date[i]'s are digits
date represents a calendar date between Jan 1st, 1900 and Dec 31, 2019.
"""
class Solution(object):
def is_leap(self, year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def dayOfYear(self, date):
"""
:type date: str
:rtype: int
"""
year, month, day = map(int, date.split('-'))
months_to_days = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
months_to_days[2] += self.is_leap(year)
day_of_year = sum(months_to_days[i] for i in range(1, month)) + day
return day_of_year
# Take away: 1. Processing Multiple Input Iterables 2. With Different Kinds of Functions 3.Transforming Iterables of Strings
| true |
a34280d5d8b2013585b67635cd316904e46a21a7 | SelinaJiang321/Python-Made-Leetcode-Easy | /easy/from 200 to 300/231. Power of Two.py | 786 | 4.21875 | 4 | """
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2x.
Example 1:
Input: n = 1
Output: true
Explanation: 20 = 1
Example 2:
Input: n = 16
Output: true
Explanation: 24 = 16
Example 3:
Input: n = 3
Output: false
Example 4:
Input: n = 4
Output: true
Example 5:
Input: n = 5
Output: false
Constraints:
-231 <= n <= 231 - 1
"""
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
# n > 0 so there is at least one.
# n & (n-1) == 0 is to check that there this number is the power of two
return n > 0 and (n & (n-1) == 0)
# Any comments?
| true |
57a06c9dca230123f413f2b546aef361b3f82ec1 | SelinaJiang321/Python-Made-Leetcode-Easy | /easy/from 200 to 300/257. Binary Tree Paths.py | 1,025 | 4.15625 | 4 | """
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
# recursive version
if not root: return []
if not root.right and not root.left: return [str(root.val)]
treepath = [str(root.val) + '->' + path for path in self.binaryTreePaths(root.left)]
treepath += [str(root.val) + '->' + path for path in self.binaryTreePaths(root.right)]
return treepath
# Maybe it's easier to use stack
# Any comments?
| true |
ae1714163ddec159c9be8bcdb37eedd197235033 | SelinaJiang321/Python-Made-Leetcode-Easy | /medium/from 1 to 100/73. Set Matrix Zeroes.py | 1,364 | 4.15625 | 4 | """
Given an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place.
Follow up:
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
Example 1:
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Example 2:
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Constraints:
m == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-231 <= matrix[i][j] <= 231 - 1
"""
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
# input validation
if not matrix:
return []
m = len(matrix)
n = len(matrix[0])
zeroes_row = [False] * m
zeroes_col = [False] * n
for row in range(m):
for col in range(n):
if matrix[row][col] == 0:
zeroes_row[row] = True
zeroes_col[col] = True
for row in range(m):
for col in range(n):
if zeroes_row[row] or zeroes_col[col]:
matrix[row][col] = 0
| true |
ca890f664f78844b8fcb1370a528c8867ad1091d | hmdshfq/Learn-Python-The-Hard-Way | /bin/ex44b.py | 719 | 4.625 | 5 | # Exercise 44b - Override explicitly
# Sometimes you don't want the child to have a specific features
# that is different from the parent so you create that feature
# in the child class explicitly. This is called overriding and
# this is how we override explicitly.
# parent class with override function
class Parent(object):
def override(self):
print("PARENT override()")
# child class with a different override function
class Child(Parent):
def override(self):
print("CHILD override()")
# creating a dad instance of Parent class
dad = Parent()
# creating a son instance of Child class
child = Child()
# both override functions will print different things
dad.override()
child.override()
| true |
01f782e435787fb6ad8e9cd26dcb1111c8b822da | hmdshfq/Learn-Python-The-Hard-Way | /bin/ex13.py | 779 | 4.5 | 4 | # Exercise 13 - Parameters, unpacking, variables
# importing from sys module argv (argument variable)
# The argv is used to take input from the user while opening/running the script
# It is similar to input() but input takes the input from user during
# the execution of the program
from sys import argv
# To run this script do the following:
# python ex13.py first second third OR
# python ex13.py Monkey Gorilla Chimpanzee
# Important note - All the command line arguments that are entered by the user
# will be strings. We will have convert them, for example in case of integers,
# by using int()
script, first, second, third = argv
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
| true |
f6334e0c4450486c8f4e11d60548009f35be1e68 | utaminuk/effectivepython | /chapter03/sec23_callable_class.py | 1,119 | 4.3125 | 4 | """
項目23: クラス型ではなく関数型で単純なインターフェースでシンプルに
Accept Functions for Simple Interfaces Instead of Classes
- コンポーネント間の単純なインターフェースは、大抵インスタンス化せずに関数で済む
- 特殊メソッド __call__ は、インスタンスが通常の関数として呼び出される事を可能にする
- 状態をもつクロージャを定義する代わりに __call__ メソッドを提供することを考える
"""
class CountMissing(object):
"""
内部カウントをするためのクラス
"""
def __init__(self):
"""
コンストラクタ
"""
self.added = 0
def __call__(self):
"""
関数として呼ばれた場合の処理
added をインクリメントする
>>> counter = CountMissing()
>>> counter()
0
>>> counter.added
1
>>> counter()
0
>>> counter.added
2
"""
self.added += 1
return 0
if __name__ == "__main__":
pass
| false |
99158db9bdd72a5103bf65411d9b5a55a7c12838 | adriano2004/Operadores_Aritmeticos | /calculos.py | 311 | 4.125 | 4 | n1=int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
so= n1+n2
su = n1 - n2
m= n1*n2
d= n1/n2
di= n1//n2
e=n1**n2
print(' A soma é {} \n A subtração é {} \n A multiplicação é {} \n A divisão é {:.2f} \n A divisão inteira é {} \n A potência é {}'.format(so,su,m,d,di,e))
| false |
2abb86e4069a8643e785e1505e333ba78f8669bb | sb17ho/Sorting-Algorithms | /Python/ShellSort/ShellSort.py | 978 | 4.1875 | 4 | def ShellSort(array):
gap = int(len(array) / 2)
# Keep looping while the size of gap reduces to zero
while gap > 0:
# Start from i = gap
for i in range(gap, len(array)):
temp = array[i] # Save the i th element
j = i
# While j is greater than or equal to gap and the element at index j-gap is greater than element at index j
while j >= gap and array[j - gap] > temp:
array[j] = array[j - gap] # Swap the elements
j = j - gap # reduce the gap
# Place the temp at the original position
array[j] = temp
# reduce the gap with each iteration
gap = int(gap / 2)
# Print the sorted array
def printList(array):
for i in range(0, len(array)):
print(array[i])
if __name__ == "__main__":
# Example
array = [170, 45, 75, 90, 802, 24, 2, 66]
ShellSort(array)
printList(array)
| true |
fd968d168923355e10f0f15cbbe3dcf595ed85a5 | JumarAlam/CSE-327 | /327_doc/mathClass/math.py | 957 | 4.21875 | 4 | class Math:
"""
This is a dummmy Math Class.
There are two functions for this class.
"""
def __inin__(self):
pass
def primeCheck(self, val):
"""
This function will check if the given number is
prime or not.
Args:
val(int): The value to check primality
Return:
Bool: It'll return true of false value
"""
flag = 1
if val > 1:
for x in range(2,val):
if (num % x) == 0:
flag = 0
break
else:
flag = 1
if (flag == 0):
return False
else:
return True
def maxValue(self, arr, n):
"""
This function will find the max value from a given array.
Args:
arr(int): An integer array with elements
n(int): n is the length of the given array
Returns:
max(int): It will return max containing the maximum value within the array.
"""
max = arr[0]
for x in range(1,n):
if (max < arr[x]):
max = arr[x]
return max
| true |
3ae820443b5d3e06c34a864e77c9aae6e18a97b1 | kunalb123/grade_calculator | /course_grade.py | 1,444 | 4.34375 | 4 |
# this script calculates the percentage grade for a particular course given user inputs
# output welcome message
print "\nWelcome to Course Percentage Calculator"
# a dictionary to hold information about weightage and percent earned
percents = dict()
course = raw_input("What course grade would you like to calculate? ") # store the course name
# loop through the categories of the course
runner = "y"
while runner == "y":
try:
category = raw_input("\nEnter a grade category: ")
weight = input("Enter a weightage for {} as a decimal: ".format(category))
earned = input("Enter percentage of {} earned: ".format(category))
print "{}\t: {}\t: {}".format(category, weight, earned)
percents[weight] = earned
except:
print "Something went wrong. The weightage must be a decimal and percentage must be <= 100"
runner = raw_input("Are there more categories to add (y/n)? ")
# display results
print "\n\nHere's what I've calculated:\n"
if sum(percents.keys()) != 1:
print "There seems to be some categories incorrectly inputted"
print "The sum of all the weightages should be 1, but it's {}".format(sum(percents.keys()))
else:
overall_percentage = 0
for weight, earned in percents.items():
overall_percentage = overall_percentage + (weight * earned)
print "Your overall percentage in {} is {}".format(course, overall_percentage)
print ""
| true |
8f6111558c00fed21ba77d646cc4ef5f246a8dbb | J-Cook-jr/python-102 | /exercise6.py | 281 | 4.28125 | 4 | #1. Prompt user for temp. in celsius
celsius = input('Temperature in c? ')
#2. Calculates the user's input
celsius = int(celsius)* 9 / 5 + 32
#3. Converts celsius to Farenheit
farenheit = celsius
#4. prints the result of celsius to farenheit calculation
print (farenheit)
| true |
ea106b76bd2121e5447d8643099dc2daf7000f91 | meliassilva/pythonprograms | /isLeapYear.py | 1,515 | 4.25 | 4 | # To get year (integer input) from the user
# year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
# Python code to demonstrate the working of isleap()
# importing calendar module for calendar operations
import calendar
year = 2017
# calling isleap() method to verify
val = calendar.isleap(year)
# checking the condition is True or not
if val == True:
# print 4th month of given leap year
calendar.prmonth(year, 4, 2, 1)
# Returned False, year is not a leap
else:
print("% s is not a leap year" % year)
# User enters the year
year = int(input("Enter Year: "))
# Leap Year Check
if year % 4 == 0 and year % 100 != 0:
print(year, "is a Leap Year")
elif year % 100 == 0:
print(year, "is not a Leap Year")
elif year % 400 == 0:
print(year, "is a Leap Year")
else:
print(year, "is not a Leap Year")
def LeapYear(year):
if year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True
else:
return False
year % 4 == 0 and not (year % 100 == 0 and not year % 400 == 0)
def is_leap(year):
return year % 4 == 0 and not (year % 100 == 0 and not year % 400 == 0)
year = int(input())
print(is_leap(year))
| true |
41903211a3bc4d4b96ba076a998845d6988b4a23 | bonifasiustrg/Hacktoberfest-4 | /Python/Number Guessing.py | 870 | 4.21875 | 4 | # Number Guessing
# Importing Libraries
import random
# Generating a random number
lower = int(input("Enter Lower Value: "))
upper = int(input("Enter Upper Value: "))
# Declaring Variables
count = 1
chance = 3
random_number = random.randint(lower, upper)
print("You have "+ str(chance) + " chances.")
while True:
if count > 3:
print("The number is " + str(random_number) + ".")
print("Better luck next time!")
break
guess = int(input("Enter Your Guess: "))
if guess != random_number:
count += 1
chance -= 1
print("You have " + str(chance) + " chances left.")
elif guess == random_number:
print("You guessed it right in " + str(count) + " times.")
break
elif guess > upper:
print("You guessed too high!")
elif guess < lower:
print("You guessed too small!")
| true |
5a18104584e2eae5cc014b4bbedd6508ece12193 | bonifasiustrg/Hacktoberfest-4 | /Python/Strong Number.py | 620 | 4.375 | 4 | # Checking whether a given number is Strong or Not
def factorial(number):
if number <= 1:
return 1
else:
return number * factorial(number - 1)
def strong(number):
temp = number
sum = 0
while number > 0:
r = number % 10
sum += factorial(r)
number //= 10
if sum == temp:
return True
else:
return False
def main():
num = int(input("Enter a Number: "))
if strong(num):
print(f"{num} is a Strong Number")
else:
print(f"{num} is not a Strong Number")
print("Checking Strong Number")
while True:
main()
| true |
7bc9d8674ffa37cd1de1ff9d2726dd4d4d5d3365 | melihozaydin/notes-references | /Python/corey schafer tutorials/29-Namedtuple.py | 917 | 4.40625 | 4 | from collections import namedtuple
# Lightweight object that works like a tuple but more readable
# RGB
# Regular tuple version
color = (55, 155, 255)
print('Tuple red ', color[0]) # Red
"""
This is not very readable or sharable
So you might think about using a dictionary to better explain the variables
The problem with that is you might need the color to be immutable
Namedtuple is the solution
"""
# Dictionary version
color = {'red': 55, 'green': 155, 'blue': 255}
print('Dict red ', color['red'])
# Namedtuple version
# import it first
# then we define a namedtuple
# namedtuple('Name of the namedtuple', ['values', 'for the', 'tuple'])
Color = namedtuple('Color', ['red', 'green', 'blue'])
color = Color(55, 155, 255)
# note that we can stil use it like a normal tuple
print('Namedtuple red:', color[0])
# We can also call it like so
print('Namedtuple red:', color.red)
| true |
c9abf8e17eb8e89d2311dd15cc5252e6118fb660 | melihozaydin/notes-references | /Python/corey schafer tutorials/4-Dictionary.py | 1,710 | 4.59375 | 5 | # Key value pairs. Which are like a real dictionary whre the
# word itself is key and its definition is the value
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci'],
3.14: 'pi'}
print(student['age'])
print(student['name'])
print(student['courses']) # Keys can be any datatype
print(student[3.14]) # Like here it is a float
"""
if we try to call a non existent key we get an error
print(student['phone'])
to avoid this we can define a default return value
by callingg the key with the get() method
"""
# get() method
print(student.get('phone', 'not found'))
print()
print()
# add an entry to dict
student['phone'] = '555-555-5555'
# If the key already exists it will update
student['name'] = 'Tayfun'
# Alternatively you can use update() method to update or add entries to dict
student.update({'name': 'Kamil', 'age': 21, 'gender': 'Male'})
print(student)
print()
# Removing entries
del student['age']
print(student)
student.update({'name': 'Kamil', 'age': 21, 'gender': 'Male'})
# this can be used to save the removed value elsewhere
age = student.pop('age')
print()
print('Removed value ', age, ' \n__ Dict --->> ', student)
student.update({'name': 'Kamil', 'age': 21, 'gender': 'Male'})
print()
print()
# Dict length
print('Entry count >>', len(student))
# List keys
print(student.keys)
print()
# List Values
print(student.values())
print()
# List every entry
print(student.items())
print()
# loop through items
# This only gets keys
for key in student:
print(key)
print()
# This will get'em all
for key, value in student.items():
print(key, value)
| true |
be3fe8d075ff0196e928a81641085ad14c7dbdc0 | rayandas/100Python | /Day2/9.py | 415 | 4.15625 | 4 | '''
Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.
Suppose the following input is supplied to the program:
Hello world
Practice makes perfect
output:
HELLO WORLD
PRACTICE MAKES PERFECT
'''
lst = []
while True:
w = input()
if len(w)==0:
break
lst.append(w.upper())
for lines in lst:
print(lines)
| true |
2ab4448f40fbb1ea55f8ca9577e445e1bc8360b1 | rayandas/100Python | /Day10/33.py | 250 | 4.125 | 4 | '''
Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included).
'''
def newlist():
lst = []
for i in range(1,21):
lst.append(i**2)
print(lst)
newlist()
| true |
5ac62fed38dc7796a4c6f9b6ccbebfad962af564 | rayandas/100Python | /Day9/28.py | 272 | 4.15625 | 4 | '''
Define a function that can receive two integer numbers in string form and compute their sum and then print it in console.
'''
sum = lambda str1, str2 : int(str1) + int(str2)
str1 = input("enter the input1:")
str2 = input("enter the input2:")
print(sum(str1,str2))
| true |
25c70506d6acf06ce4d7b4afdeb6d1833587d195 | rayandas/100Python | /Day11/38.py | 281 | 4.125 | 4 | '''
With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line.
'''
tup = (1,2,3,4,5,6,7,8,9,10)
for i in range(0,5):
print(tup[i],end='')
print()
for i in range(5,10):
print(tup[i],end='')
| true |
5fee570c54f7f6fa33f2cc7b3626c36891974ec2 | swooton/Network-Automation | /6_final.py | 971 | 4.40625 | 4 | #This is your first Python Subscription
# After each step save your script as "6.py" and run it in a virtual environment
# 1. Create a list with the following values in this order
# - cats
# - dogs
# - 17
# - [1,2,3]
# 2. Use a for loop to print the contents of the list
# 3. Create a variable that is set to 17
# 4. Use if/elif/else to determine if the number is > 20, >10 or 10 or less
# 5. Print to the screen what range the number falls within
# 6. change the variable to a number greater than 20 and make sure it works
# 7. Use a while loop to go thru and print the contents of you list, make the index number the counter
# Good Luck
mylist=["cats","dogs",17,[1,2,3]]
for item in mylist:
print (item)
a = 17
if a > 20:
print ("The number is greater than 20")
elif a > 10:
print ("The number is between 11 and 20")
else:
print ("Then number is 10 or less")
index = 0
while index < len(mylist):
print(mylist[index])
index = index + 1
| true |
4b534a74140e2912c57e01ddde8ad473871d2d41 | swooton/Network-Automation | /2_final.py | 1,971 | 4.15625 | 4 | # Lab 2
# After each step save your script as "2.py" and run it in a virtual environment
# 1. Make a string variable with the Months of the year,
# - Insert carriage returns after each month
# - Print the variable to ensure the output is correct
# 2. Make a string variable that contains a short paragraph
# - Indent the fisrt line with a tab
# - Print the paragraph to the screen and verify output
# 3. Print the value between the stars *Jed's mom said "Hello World!"*
# 4. Have the scrip prmopt and collect the 4 following values:
# - Your favorite color
# - Your favorite food
# - Your favorite drink
# - Your favorite animal
# 5. Print these 4 variables to the screen
# Good Luck
months ="Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\nSep\nOct\nNov\nDec"
print (months)
paragraph = "\tBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!"
print (paragraph)
print ("Jed's mom said \"Hello World\"")
color = input("What is your favorite color?")
food = input("What is your favorite food?")
drink = input("What is your favorite drink?")
animal = input("What is your favorite animal?")
answers = "{} {} {} {}"
print (answers.format(color, food, drink, animal))
| true |
db4da9a86fd4c2a20f12dccc8645ef1bee6a66ec | Danielkhakbaz/Python-Fundamental | /Calculator/app.py | 1,528 | 4.5 | 4 | OPERATORS = ["+", "-", "*", "/"]
again = "y"
def calculate(first_number: float, operation: str, second_number: float) -> float:
"""
Calculate the numbers based on the operation which user entered.
Parameters:
first_number (num): The first number which is going to be calculated
operation (str): The operation that user enter based on their needs
second_number (num): The second number which is going to be calculated
Returns
num: The result of the operated numbers
"""
if operation == "+":
return first_number + second_number
elif operation == "-":
return first_number - second_number
elif operation == "*":
return first_number * second_number
elif operation == "/":
return first_number / second_number
first_number = int(input("Enter the first number: "))
while again == "y":
for operator in OPERATORS:
print(operator)
operation = input("Pick an operation: ")
if operation not in OPERATORS:
break
second_number = int(input("Enter the second number: "))
print(f"{first_number} {operation} {second_number} = {calculate(first_number, operation, second_number)}")
again = input(
f"Type 'y' to continue calculating with {calculate(first_number, operation, second_number)}, or type 'n' to stop the calculator: ").lower()
if again == "y":
first_number = calculate(first_number, operation, second_number)
if again == "n":
quit()
print("You entered an unvalid choice!")
| true |
b98780a085b2aa8a746ffba9cdd09cf08b8a5863 | briantaylorjohnson/python-practice | /parrot2.py | 943 | 4.5 | 4 | ### Chapter 7
## Using the while loop to let the user choose when to quit
prompt = "\nTell me something and I will repeat it back to you."
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != "quit": # While loop will run as long as message is not equal to 'quit'
message = input(prompt)
if message != "quit": # Only outputs the message if message is not equal to 'quit'
print(message) # Outputs the message
else:
print("\n") # Creates a new line before quitting the program
## Using a flag to exit a loop
active = True
while active: # While loop only runs when active equals True
message = input(prompt)
if message == "quit": # Sets active to False if 'quit' is entered by the user and exits the loop to end the program
active = False
else:
print(message) # Outputs the message if anything other than 'quit' is entered by the user
| true |
710f2e94b8ae0009429a4c0503e6bbdacf365db5 | briantaylorjohnson/python-practice | /name.py | 2,053 | 4.3125 | 4 | # Chapter 2
name = "ada lovelace"
print(name.title()) # Title case
print(name.upper()) # Upper case
print(name.lower()) # Lower case
first_name = "tom"
last_name = "thumb"
full_name = f"{first_name} {last_name}" # F-strings
print(full_name.title())
print(f"Hello there, {full_name.title()}!") # F-strings in print function
message = f"My name is {name.title()}." # F-strings in variable
print(message)
print("Python")
print("\tPython") # Adding a tab
print("\nPython\n") # Adding a new line
print("Languages:\nPython\nC\nJavaScript\n") # Adding new lines
print("Languages:\n\tPython\n\tC\n\tJavaScript\n") # Adding new lines and tabs
favorite_language = "Python " # Whitespace on right side
print(favorite_language)
print(favorite_language.rstrip()) # Whitespace on right side stripped in output
favorite_language = favorite_language.rstrip() # Whitespace on right side stripped in variable
print(favorite_language)
favorite_language = " Python3 " # Whitespace on both sides
print(favorite_language.rstrip()) # Whitespace on right side stripped
print(favorite_language.lstrip()) # Whitespace on left side stripped
print(favorite_language.strip()) # Whitespace on both sides stripped
print("\n\n")
addition = 2 + 3 # Addition
print(addition)
subtraction = 2 - 3 # Subtraction
print(subtraction)
multiplication = 9 * 9 # Multiplication
print(multiplication)
division = 9 / 4 # Division
print(division)
exponents = 9 ** 2 # Exponents
print(exponents)
exponents = 9 ** 3 # Exponents
print(exponents)
order_of_ops = ((9 * 8) / 2) ** 2 # Order of Operations
print(order_of_ops)
floats = 0.2 + 0.1 # Watch out for floats and lots of decimal places
print(floats)
universe_age = 14_000_000_000 # Using underscores to make big numbers more readable
print(universe_age)
x, y, z = 0, 1, 2 # Assigning values to more than one variable in a single line
print(x)
print(y)
print(z)
MAX_CONNECTIONS = 5000 # Using all caps to indicate a constant in Python is a common practice
print(MAX_CONNECTIONS)
import this # Displays "The Zen of Python" by Tim Peters
| true |
626c642e535beab46e4ac2e160a7582c9c6ca3c2 | briantaylorjohnson/python-practice | /cars.py | 1,013 | 4.71875 | 5 | # Chapter 3
cars = ['bmw', 'audi', 'toyota', 'subaru'] # Initial list of cars
print(cars)
cars.sort() # Sorts elements in list alphabetically -- upper and lower case are different!
print(cars)
cars.sort(reverse=True) # Sorts elements in reverse alphabetically -- upper and lower case are different!
print(cars)
cars = ['bmw', 'audi', 'toyota', 'subaru'] # Initial list of cars
print("\nHere is the original list of cars:")
print(cars)
print("\nHere is the sorted list of cars:")
print(sorted(cars)) # This sorts the list of cars temporarily
print("\nHere is the reverse sorted list of cars:")
print(sorted(cars, reverse=True)) # This reverse sorts the list of cars temporarily
print("\nHere is the original list of cars again:")
print(cars)
print("\n")
cars = ['bmw', 'audi', 'toyota', 'subaru'] # Initial list of cars
print(cars)
cars.reverse() # Reverses the order of the elements in the list
print(cars)
print("\nLength of the list of cars:")
print(len(cars)) # Finds the length of the list of cars
| true |
896ef34561e0de8d1497e8570aceff27c243d633 | briantaylorjohnson/python-practice | /toppings2.py | 1,493 | 4.25 | 4 | ### Chapter 5
## IF Statements
# Checking Multiple IF Statements
requested_toppings = ['mushrooms', 'extra cheese', 'green peppers']
if 'mushrooms' in requested_toppings:
print('Adding mushrooms for you, sir...')
if 'pepperonis' in requested_toppings:
print('Adding pepperonis for you, sir...')
if 'extra cheese' in requested_toppings:
print('Adding extra cheese for you, sir...')
print('Finished making your pizza! Voila!\n')
## Using IF Statements with Lists
# Checking for Special Items
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print(f"Oh no, I'm sorry. We are out of {requested_topping}.")
else:
print(f'Adding {requested_topping}...')
print('Finished making your pizza. Voila!\n')
# Checking If a List is Empty
empty_request = []
if empty_request:
for requested_topping in empty_request:
print(f'Adding {requested_topping}...')
else:
print('Are you sure you want a plain pizza?\n')
# Using Multiple Lists
available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print(f'Adding {requested_topping}... Smells so good!')
else:
print(f'Sorry! We are out of {requested_topping}. Try again another day."')
print('Finished making your pizza!')
| true |
96438d66780fc830f7bee01ecafac68cd699612a | briantaylorjohnson/python-practice | /motorcycles.py | 1,850 | 4.53125 | 5 | # Chapter 3
motorcycles = ['honda', 'yamaha', 'suzuki'] # Initial list of motorcycles
print(motorcycles)
motorcycles[0] = 'ducati' # Changes the value of element in list with index of 0
print(motorcycles)
motorcycles.append('honda') # Adds a new element to the list of motorcycles
print(motorcycles)
motorcycles = [] # Creates an empty list of motorcycles
print(motorcycles)
motorcycles.append('honda') # Appends Honda
motorcycles.append('yamaha') # Appends Yamaha
motorcycles.append('suzuki') # Appends Suzuki
print(motorcycles)
motorcycles.insert(0, 'ducati') # Inserts a new element into the list at the specified index
print(motorcycles)
del motorcycles[0] # Removes element in the list at index 0
print(motorcycles)
del motorcycles[1] # Removes element in the list at index 1
print(motorcycles)
motorcycles = ['honda', 'yamaha', 'suzuki'] # Initial list of motorcycles
print(motorcycles)
popped_motorcycle = motorcycles.pop() # Pops the last element in the list - assigning it to a variable and then removing it from the list
print(motorcycles)
print(popped_motorcycle)
motorcycles = ['honda', 'yamaha', 'suzuki'] # Initial list of motorcycles
print(motorcycles)
popped_motorcycle = motorcycles.pop(1) # Pops the list element at index of 1
print(motorcycles)
print(popped_motorcycle)
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] # Initial list of motorcycles
print(motorcycles)
motorcycles.remove('ducati') # Removes first occurrence of list element with value of 'ducati'
print(motorcycles)
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] # Initial list of motorcycles
print(motorcycles)
too_expensive = 'ducati' # Set variable to motorcycle which is too expensive
motorcycles.remove(too_expensive) # Removes first occurrence expensive motorcycle from list using variable
print(too_expensive)
print(motorcycles)
| true |
0c37ec396ffa01ba5fe5e7ed11a06409df94ddba | haedalprogramming/2021KNUPythonStep1 | /3.recursion+condition/for_recursion.py | 624 | 4.125 | 4 | # for문 무작정 따라해보기
for i in range(1, 11):
if (i%2 == 0):
print(i, "은/는 짝수입니다.")
else:
print(i, "은/는 홀수입니다.")
# for문의 구조
# for i in 범위:
# 반복할 명령어1
# 반복할 명령어2
# for문 with list
mylist = ['해달이', '사스미', '메기']
for i in mylist:
print(i)
print("반복 끝")
# print list with range
print(list(range(10))) # start 기본값은 0
print(list(range(1,11))) # step 기본값은 1
print(list(range(1,20,3)))
print(list(range(20,0,-3)))
# for문 with range
for i in range(1,11):
print(i, end=" ")
print('반복 끝')
| false |
e011c6130e325dfbb998147e3ea05d28a042a63d | Afuwamusa/Pyt | /lists2.py | 1,442 | 4.4375 | 4 | countries = ["Canada", "France", "Belgium", "Ireland", "Italy"]
print(countries)
print(sorted(countries))
print(countries)
countries.sort(reverse = True)
print(countries)
countries.reverse()
print(countries)
countries.sort()
print(countries)
print(sorted(countries))
print(countries)
print(len(countries))
languages = ["English","Arabic","French","Swahili","Gujurati"]
print(languages)
print(languages[0])
print(languages[4])
languages.append("Chinese")
print(languages)
languages.insert(2,"Hindi")
languages.insert(3,"Spanish")
print(languages)
languages.append("Russian")
print(languages)
print(len(languages))
languages.pop(8)
print(languages)
languages.reverse()
print(languages)
print(sorted(languages))
print(languages)
languages.sort(reverse = True)
print(languages)
for language in languages:
print(language.title() + ",is an international language.")
print("i really wish, i could learn all these languages in a month!")
animals = ["cows","camels","goats"]
for animal in animals:
print(animal.title() + ", produce milk and have a body thats covered by fur.")
print("All these animals would make a great pet.")
for values in range(1,21):
print(values)
numbers = list(range(1,1000000))
for numbers in range(1,1000000):
print(numbers)
numbers = list(range(1,1000000))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
odd_numbers = list(range(1,20,1))
for odd_numbres in range(1,20,1):
print(odd_numbers)
| false |
a97a05dc56a2130bcdb11b190815e4f1d32582d7 | casemmajd/AlgorithmSamples1-10 | /C011_Reverse.py | 280 | 4.28125 | 4 | #!/usr/bin/env python36
def reverse(str):
copy = ""
for i in range(len(str)-1, -1, -1):
copy = copy + str[i]
return copy;
print(reverse("Hello World!"))
word = "radar"
if (word == reverse(word)):
print("The word", word, "is a palindrome!")
| true |
a9fa1c604ecf932f5d01c8e1634fac8abcb9fc63 | casemmajd/AlgorithmSamples1-10 | /C010_IsPrime.py | 260 | 4.125 | 4 | #!/usr/bin/env python36
import math
def isPrime(N):
if (N <= 1):
return 'false'
maxToTry = int(math.sqrt(N))
for divisor in range(maxToTry):
if ( N % (divisor+2) == 0 ):
return 'false'
return 'true'
print(isPrime(5))
| false |
18cf9b79272b8472e458f521a5cb50b1694e6fc6 | nberger62/python-udemy-bootcamp | /Dictionaries/Dict_Loops.py | 494 | 4.21875 | 4 | instructor = {
"name": "Colt",
"owns_dog": True,
"num_courses": 4,
"favorite_language": "Python",
"is_hilarious": False,
44: "my favorite number!"}
print(instructor["name"])
#Colt
#forloops
for value in instructor.values():
print(value)
#forloops in dict.s for values or left column
for keys in instructor.keys():
print(keys)
#for loops for values in right column
#BOTH!!!!!!!!!!!!!!!!!!!!!!!
for key,value in instructor.items():
print(key,value)
break | true |
0f05ba893ea83e51306a93e848712de1ccdb1933 | anilkumarcc/python-programs | /anil5.py | 268 | 4.125 | 4 | # python program to swapping two variables
# To take input from the user
x = input('enter value of x:')
y = input('enter value of y:')
temp = x
x = y
y = temp
print ('The value of x ofter swapping:{}'.format(x))
print ('The value of y ofter swapping:{}'.format(y)) | true |
6f5891e402a34b4f03492223e230d2bc19219125 | fyx-ll/test | /mypython/myobj/myoop012.py | 1,414 | 4.3125 | 4 | # -*- coding: utf-8 -*-
'''@property 装饰器的用法'''
class Employee:
def __init__(self, name, salary):
self.__name = name #私有方法
self.__salary = salary #私有方法
# python 通过装饰器的写法
@property # 实现get方法,把方法当做是属性,只能看不能修改
def salary(self):
return self.__salary
@salary.setter # 通过装饰器修饰过的setter方法来修改属性
def salary(self, salary):
if 1000 < salary < 300000:
self.__salary = salary
else:
print('输入错误,{0}不在1000--300000之间'.format(salary))
''' #类似java的写法 set,get 方法
def get_salary(self):
return self.__salary
def set_salary(self, salary):
if 1000< salary <300000:
self.__salary = salary
else:
print('输入错误,{0}不在1000--300000之间'.format(salary))
'''
e = Employee('fanwei', 20000)
print(dir(e))
print('------------------------------------')
#python装饰器的写法的调用
print(e.salary) #调用 get
e.salary = 2000 #设置 set
print(e.salary) #调用
e.salary = -2000 #设置 set
print(e.salary) #调用
''' #类似java的写法的调用
print(e.get_salary())
e.set_salary(2000)
print(e.get_salary())
e.set_salary(-2000) #输入值不在范围,修改失败,值不变
print(e.get_salary())
'''
| false |
3547cee139aac9373efa9a450295aecc876f41a5 | SrikanthSrigakolapu/pythonpractise | /basics/pythonCalculator.py | 1,062 | 4.46875 | 4 | print("1.simple addition 2 + 2 is ", 2 + 2)
print("2.normal division 19/3 is ", 19/3)
print("3.with no decimal values: division 19//3 is ", 19//3)
print("4.with Remainder as value: divison 19%3 is ", 19%3)
#if we dont want to character prefaced by \ to be interpreted as special characters
#Then we can simply specify the raw string
# format of raw string is r'hello \n what '
print("5.With out raw string ")
print("hello \n world ")
print("6.With raw string ")
print(r'hello \n world ')
print("\n7.use of ''' <string> ''' in python \n")
#we can use ''' <string> ''' to print multiple lines in the same format that is given in print
print('''hello
what is this man
It is fantastic''')
#multiple the string literal
print("\n8. multiple the string literal 3 * 'Value ' ")
print(3 * 'Value ')
print("Note: Cannot be used with variable names")
#string auto concatenation between strings with space gap
print("\n9. string auto concatenation between strings with space gap \"val\" \"ue\" ")
print("val" "ue")
print("Note: Cannot be used with variable names") | true |
0e54268c9b32111afc68cdab0cb6e2039612007c | ekselan/Graphs | /whiteboard/practice.py | 216 | 4.40625 | 4 | # Given the following array of values, print out all the elements in reverse order, with each element on a new line.
# For example, given the list
# [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
arr = [1,2,3,4]
arr.reverse() | true |
aa913b7c9e6290b20393d1aa59a54312970f242d | Sashok15/GeekHub_python | /HT_2/Task_6.py | 332 | 4.125 | 4 | # The function takes the function into the parameters and multiplies the value five times.
def decorator(func):
def wrapper(name):
print("//////////////////")
result = 'Your name: ' + name
return result
return wrapper
@decorator
def is_my_name(name):
print(name)
print(is_my_name('sashka'))
| true |
9ae3181915ee67df24f1887dbc7101c34cc09837 | kmunge/Password-locker | /user.py | 1,503 | 4.28125 | 4 | import pyperclip
class User:
'''
Class that generates new instances of the user
'''
user_list = []
def __init__(self,first_name,last_name,user_name,password):
'''
init__helps to define our user's properties
Args:
first_name:New contact first name
last_name:New contact last_name
user_name:New user's login username
password:New user's login password
'''
self.first_name = first_name
self.last_name = last_name
self.user_name = user_name
self.password = password
def save_user(self):
'''
Method saves user objects into the user_list
'''
User.user_list.append(self)
def find_by_user_name(self, name):
'''
Method that takes in a user_name and returns the user details that match that user_name
Args:
user_name: User_name to search
Returns:
User details that match the search
'''
for user in self.user_list:
if user.user_name == name:
return user
def user_exists(self, user_name):
'''
Method to check if user exists in the user_list
Args:
user_name: User_name to search from the user_list
returns:
boolean: true or false depending on existance of user
'''
for user in self.user_list:
if user.user_name==user_name:
return True | true |
386a908818a737d033b5e6ef334203a3778b0d02 | paulgrote/python-practice | /python-workbook/Exercise-111.py | 581 | 4.28125 | 4 | # Exercise 111:
# Write a program that reads integers from the user and stores them in a list.
# Use 0 as a sentinel value to mark the end of the input.
# Once all of the values have been read, your program should display them
# (except for the 0) in reverse order, with one value appearing on each line.
the_integers = []
answer = int(input("Please enter an integer, or enter '0' to quit."))
while answer != 0:
the_integers.append(answer)
answer = int(input("Please enter an integer, or enter '0' to quit."))
the_integers.reverse()
for i in the_integers:
print(i) | true |
5b32ce0f74d55cba9ac1c7a346b55bba179d9473 | paulgrote/python-practice | /python-workbook/Exercise-010.py | 593 | 4.21875 | 4 | # Exercise 10
# Create a program that reads two integers, a and b, from the user.
# Compute and display:
# - the sum of a and b
# - the difference when b is subtracted from a
# - the product of a and b
# - the quotient when a is divided by b
# - the remainder when a is divided by b
# - the result of log10a
# - the result of a^b
import math
a = int(input("Enter a number, a: "))
b = int(input("Enter a number, b: "))
print("a + b:", a + b)
print("a - b:", a - b)
print("a * b:", a * b)
print("a / b:", a / b)
print("a % b:", a % b)
print("log10a:", math.log10(a))
print("a ** b:", a ** b)
| true |
9afbad5fe4bd9951d0a6e0ae73f6bf0fbc32c063 | paulgrote/python-practice | /misc/odd_even.py | 234 | 4.40625 | 4 | #Ask the user for a number
number = input("Enter a number: ")
#Calculate even or odd
x = int(number) % 2
#Tell the user whether the number is even or odd
if x == 0:
print("The number is even.")
else:
print("The number is odd.")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.