blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
79543754148fb145283cd19bd358b416461738ae | Electron847/MasterFile | /IntroToProgramming/Seth_Weber_a6.py | 1,194 | 4.21875 | 4 | def generateDict():
'function generates the dictionary based on file cities_by_continent.csv.txt'
try:
file=open('cities_by_continent.csv.txt','r',encoding='utf-8')
except FileNotFoundError:
print('Could not find this file')
except IOError:
print('Could not open this file')
content=file.read()
text=content.split('\n')
mydict={}
countries_global=[]
#text.split(',')
text.remove('')
for line in text:
spot=line.split(',')
for index in spot:
continents=spot[0]
countries=spot[1:(len(spot))]
countries_global.append(countries)
mydict[continents]=countries
return mydict
def getContinentChoice(dictionary):
'function asks user for continent choice and prints out cities within that continent based on file cities_by_continent.csv.txt'
for key in d:
print(key)
user_choice=input('Choose a continent from the list above:')
if user_choice in d:
var1=d[user_choice]
print('Some important countries in this continent are',var1[0],',',var1[1],',and',var1[2])
d=generateDict()
s=getContinentChoice(d)
| true |
94c0885e2461e0eef760825a768c3fdacdfd50a7 | trgeiger/algorithms | /reverse_ll.py | 584 | 4.3125 | 4 | """
Reverse a linked list
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the reversed linked list in the below method.
"""
def Reverse(head):
current = head
prev = None
while current:
if not current.next:
newh = current
current.next = prev
return newh
next = current.next
current.next = prev
prev = current
current = next
| true |
11979f52b301753081b217c6161a85db81038db5 | arindam-1521/python-course | /python practise problem solving/tute4(copied).py | 649 | 4.15625 | 4 | n = 12
guess = 1
print("Number of guesses is limited to 9")
while guess <= 9:
guess_number = int(input("Enter your number to start the game:"))
if guess_number < n:
print("You have written a smaller number try something bigger.")
elif guess_number > n:
print("You have written a larger number try something")
else:
print("You have won the game.yay!!!!!!!")
print(guess, "no of guesses you took to finish the game")
break
print(9 - guess, "no of guesses you have")
guess = guess + 1
if guess > 9:
print("You lost the game")
print("Try again for the next time to win the game.")
| true |
3f784c01b3a62664ec44940e9bdf2a8faa9b6f89 | jstloyal/Python | /mycinema.py | 1,071 | 4.3125 | 4 | #Cinema application
#Creating movie dictionary
films = {
"Roots":[18,5],
"Shaft":[15,5],
"The Dictator":[5,5],
"Polar":[15,5],
"Green Lantern":[12,5],
"Mind The Baby":[3,5]
}
print(films)
while True:
#choose a movie to see
choice = input("What movie will you like to see?: ").strip().title()
if choice in films:
#check user's age
age = int(input("How old are you?: ").strip())
if age >= films[choice][0]:
#check enough seats
num_seats = films[choice][1]
if num_seats >0:
print("Enjoy your movie!")
films[choice][1] = films[choice][1] -1
else:
print("Sorry, we are sold out!")
else:
print("You are too young to see this movie!")
else:
print("We don't have that movie now, check back next week!")
| true |
02f01d1a2300bab70e83ede299504b73ac2f59e1 | sana9056/Python-and-Scheme-GB | /HW3/HW3_7.py | 937 | 4.1875 | 4 | '''7. В одномерном массиве целых чисел определить два наименьших
элемента. Они могут быть как равны между собой (оба являться
минимальными), так и различаться.'''
import random
r = [random.randint(0, 99) for _ in range(100)]
print(f'Массив: {r}')
min_index_1 = 0
min_index_2 = 1
for i in r:
if r[min_index_1] > i:
min_index_2 = min_index_1
min_index_1 = r.index(i)
elif r[min_index_2] > i:
min_index_2 = r.index(i)
print(f'Два наименьших элемента: {r[min_index_1]} и {r[min_index_2]}')
'''Второй способ через сортировку списка'''
sort_list = []
sort_list.extend(r)
sort_list.sort()
print(
f'Два наименьших элемента (второй способ): {sort_list[0]} и {sort_list[1]}'
)
| false |
3256b2448a3f477071e3840f98975b690edfebba | sana9056/Python-and-Scheme-GB | /HM1/code/HM1_1.py | 238 | 4.125 | 4 | number = input('Введите число: ')
sum = 0
prod = 1
for f in number:
sum += int(f)
prod *= int(f)
print(f"Сумма цифр числа {number}: {sum}")
print(f"Произведение цифр: {number}: {prod}")
| false |
7d8f9aeaf0df6e961d6c5b60806e5c7eb78ad606 | Darksoulz15/HackerRank_Solutions | /Finding the percentage.py | 1,382 | 4.375 | 4 | if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *percent = input().split()#only the first variable will be stored in name. rest all the other space seperated entries falls within the *percent as a list
scores = list(map(float, percent))
student_marks[name] = scores #student_marks[name] will store the marks of the corresponding name in a dictionary(data structure)
query_name = input() #the final query_name which is out of the loop takes in the name of student for whom we need the average to be calculated.
#Eloborated explaination for name,*percent with examples
"""
So if you had:
>>> first, *rest = input().split()
>>> print(first)
>>> print(*rest)
and ran it and typed in "hello my name is bob" It would print out
hello
['my', 'name', 'is', 'bob']
Another example would be this:
>>> a, b, *rest = range(5)
>>> a, b, rest
(0, 1, [2,3,4])
It can also be used in any position which can lead to some interesting situations
>>> a, *middle, c = range(4)
>>> a, middle, c
(0, [1,2], 3)
"""
average = sum(student_marks[query_name])/3 #sum function adds up all the elements of list and divied by "3" gives the average since there are only 3 subjects given
average = "{:.2f}".format(average) #the "{:.2f}"format function helps to produce the output float to upto only 2 precision
print(average)
| true |
b6153c0e9c2230117ecfc22615cb1303ca93b553 | juliejonak/Intro-Python-I | /src/scopes.py | 885 | 4.1875 | 4 | # Experiment with scopes in Python.
# Good reading: https://www.programiz.com/python-programming/global-local-nonlocal-variables
# Better reading: https://www.datacamp.com/community/tutorials/scope-of-variables-python , https://www.programiz.com/python-programming/global-keyword
# When you use a variable in a function, it's local in scope to the function.
x = 12
def changeX():
global x
x = 99
changeX()
# This prints 12. What do we have to modify in changeX() to get it to print 99?
print(x)
# This nested function has a similar problem.
def outer():
y = 120
def inner():
nonlocal y
y = 999
inner()
# This prints 120. What do we have to change in inner() to get it to print
# 999? Google "python nested function scope".
print(y)
outer()
# OR can set y to global within inner(), but then need a print(y) after calling outer | true |
c126f8b881bafc5686cf45b866f6f209e2f544bc | zeemba/pyclass | /flow.py | 225 | 4.125 | 4 | name = 'Oyin'
if name == 'Azeem':
print('Hi ' + name)
elif name == 'Oyin':
print('Hey baby!')
else:
print('Oh what is your name then?')
myName = input()
print('Great!, Hi ' + myName)
print('Done') | false |
000678c3734fb91158bd841665ddcf606043e992 | JasonRillera/functions_basic2 | /functions_basic2.py | 2,622 | 4.40625 | 4 | # 1. Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
# Example: countdown(5) should return [5,4,3,2,1,0]
# def countdown(num):
# nums_list= []
# for val in range(num, -1,-1):
# nums_list.append(val)
# return nums_list
# print(countdown(5))
# 2. Print and Return - Create a function that will receive a list with two numbers. Print the first value and return the second.
# Example: print_and_return([1,2]) should print 1 and return 2
# def print_and_return(nums_list):
# print(nums_list[0])
# return(nums_list[1])
# (print_and_return([1,2]))
# 3. First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length.
# Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5)
# def first_plus_length(nums_list):
# first_val = nums_list[0]
# length_of_list = len(nums_list)
# return first_val + length_of_list
# print(first_plus_length([1,2,3,4,5]))
# or
# def first_plus_length(nums_list):
# return nums_list[0] + len(nums_list)
# print(first_plus_length([2,2,3,4,5]))
# 4. Values Greater than Second - Write a function that accepts a list and creates a new list containing only the values from the original list that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False
# Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4]
# Example: values_greater_than_second([3]) should return False
# def values_greater_than_second(og_list):
# new_list = []
# second_val = og_list[1]
# for idx in range(len(og_list)):
# if og_list[idx] > second_val:
# new_list.append(og_list[idx])
# print(len(new_list))
# return new_list
# print(values_greater_than_second([5,2,3,2,1,4]))
# 5. This Length, That Value - Write a function that accepts two integers as parameters: size and value. The function should create and return a list whose length is equal to the given size, and whose values are all the given value.
# Example: length_and_value(4,7) should return [7,7,7,7]
# Example: length_and_value(6,2) should return [2,2,2,2,2,2]
# def length_and_value(size, value):
# new_list =[]
# for num_times in range(size):
# new_list.append(value)
# return(new_list)
# print(length_and_value(4,7)) | true |
a16ba9872cd06df653ddaa02d3c411ba0d92a338 | Flavio-Varejao/Exercicios | /Python/EstruturaDeRepeticao/Q17.py | 278 | 4.3125 | 4 | #!/usr/bin/env python3
#Faça um programa que calcule o fatorial de um número inteiro fornecido pelo usuário. Ex.: 5!=5.4.3.2.1
num=int(input("Digite o número: "))
fatorial=1
for i in range(1,num+1,1):
fatorial=fatorial*i
print("Fatorial de",num,"é igual a",fatorial)
| false |
33511f0512204c6e0beb88579a82ad01e37b0235 | Flavio-Varejao/Exercicios | /Python/EstruturaDeRepeticao/Q11.py | 651 | 4.28125 | 4 | #!/usr/bin/env python3
'''
Faça um programa que receba dois números inteiros e gere os números inteiros que estão no intervalo compreendido por eles.
Altere o programa anterior para mostrar no final a soma dos números.
'''
#FOR
lista=[]
for num in range(int(input("Digite o 1º número: "))+1,int(input("Digite o 2º número: ")),1):
lista.append(num)
print("lista = "+str(lista))
print("soma = "+str(sum(lista)))
#WHILE
#lista=[]
#num1=int(input("Digite o 1º número: "))
#num2=int(input("Digite o 2º número: "))-1
#while num1<num2:
#num1+=1
#lista.append(num1)
#print("lista = "+str(lista))
#print("soma = "+str(sum(lista)))
| false |
8416650320ae9739f3f594d7e00f547fbc6b06a1 | Flavio-Varejao/Exercicios | /Python/Listas/Q14.py | 1,148 | 4.1875 | 4 | '''
Utilizando listas faça um programa que faça 5 perguntas para uma pessoa sobre um crime.
As perguntas são:
"Telefonou para a vítima?"
"Esteve no local do crime?"
"Mora perto da vítima?"
"Devia para a vítima?"
"Já trabalhou com a vítima?" O programa deve no final emitir uma classificação
sobre a participação da pessoa no crime. Se a pessoa responder positivamente a 2
questões ela deve ser classificada como "Suspeita", entre 3 e 4 como "Cúmplice" e
5 como "Assassino". Caso contrário, ele será classificado como "Inocente".
'''
contador=0
perguntas=[input("Telefonou para a vítima? ").upper(),
input("Esteve no local do crime? ").upper(),
input("Mora perto da vítima? ").upper(),
input("Devia para a vítima? ").upper(),
input("Já trabalhou com a vítima? ").upper()]
for resposta in perguntas:
if resposta == "S":
contador+=1
if contador == 0 or contador == 1:
print("\nVocê é inocente")
elif contador == 2:
print("\nVocê é suspeito")
elif contador == 3 or contador == 4:
print("\nVocê é cúmplice")
else:
print("\nVocê é o assassino") | false |
94794faad742bc00c44e6ffcec8302f82e482da5 | uzwer1/my-python | /my pithon 06 (Python Lists and Dictionaries).py | 1,354 | 4.28125 | 4 | #Python Lists and Dictionaries
'''
Метод берет числа из одного списка
и с помощью стандартного для таких случаев
FOR возводит в квадрат каждый элемент списка.
Потом зачем-то (можно удаолить за ненадобностью)
сортирует полученные элементы нового списка
по возрастанию и выводит на экран поочередно
'''
start_list = [5, 3, 1, 2, 4]
square_list = []
# Your code here!
for x in start_list:
x = x**2
square_list.append(x)
square_list.sort()
print square_list
'''
'''
inventory = {
'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}
# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']
# Sorting the list found under the key 'pouch'
inventory['pouch'].sort()
# Your code here
inventory['pocket'] = ['seashell', 'strange berry', 'lint']
inventory['backpack'].sort()
inventory['backpack'].remove('dagger')
for x in inventory['gold']:
y = x+50
inventory['gold'].remove()
inventory['gold'].append(y) | false |
4b7c4a31eeb90929b2b0295161617c18d89bdc50 | solomc1/python | /ics 33/workspace/larc/Regex_Search_Example.py | 525 | 4.21875 | 4 | # LARC ICS 33 Spring 2014
# Regular Expressions File Searcher
# This program, given a pattern, will print out the lines that contain the given pattern
import re
file_to_be_searched = "supersecretfile.txt"
pattern = "Password:\d{4}" # your answer goes here
compiled_pattern = re.compile(pattern)
for i, line in enumerate(open(file_to_be_searched)):
for match in re.finditer(compiled_pattern, line):
print("Found a password! Line Number: " + str(i + 1))
l = ['a', 'b', 'c', 'd']
for i, l in enumerate(l):
print(i, l) | true |
c223472807ca912bb40b05b478031f3b0e40e85a | solomc1/python | /ics 32/code examples/count_lines.py | 1,074 | 4.25 | 4 | def count_file_lines(path_to_file: str) -> int:
'''given the path to a file, return the number of lines of text in that file
or raises an exception if the file could not be opened.'''
file = None
try:
file = open('r', path_to_file)
lines = 0
line = file.readline()
while line != ' ':
lines += 1
line = file.readline()
return lines
finally:
if file != None:
file.close()
def user_interface() -> None:
'''Repeated asks the user to specify a file; each time, the number of lines
of text in the file are printed, unless the file could ont be opened,
in which case a brief error message is displayed instead'''
while True:
path_to_file = input("Enter path: ").strip()
if path_to_file == '':
break
try:
number = count_file_lines(path_to_file)
print("{} has {} lines".format(path_to_file, number)
except:
print("Error")
if __name__ == "__main__":
user_interface()
| true |
5a252069ddc02d48a8ecfd007962f55b4eb9781b | valkyrie55/Numpy-Pandas-Matplotlip | /numpy_basics_begin.py | 1,040 | 4.28125 | 4 | import numpy as np
#let create a random data
data = np.random.randn(2,3)
print(data)
#Perform some operations on it
print(data * 10)
print(data + data)
#now create a 2-D numpy array
data2 = [[1,2,3,4],[5,6,7,8]]
arr2 = np.array(data2)
print(arr2)
#Dimensions of the ndarray
print(arr2.ndim)
#----------------------------------------#
#Functions for creating new arrays
print(np.zeros(10)) #ndarray initialized with zero
print(np.zeros((2,3))) # 2X3 ndarray
#-----------------
# To specify data type for an ndarray----------
d = [1,2,3,4,5]
data = np.array(d,dtype =np.float64)
print(data)
data1 = np.array(d,dtype = np.int32)
print(data1)
#explicitly cast an array from one datatype to another
data3 = data.astype(np.float64)
#Arithmetic operations for np array
data4 =[[1,2,3],[4,5,6]]
data4_ = np.array(data4)
print("-----------------------")
print(data4_)
print(data4_*data4_)
print(data4_ + data4_)
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a)
#--------------------------
#----slicing in ndarray-----
print(a[1])
print(a[1,1])
| true |
c72503b3203ca1e112615fc0c3d77162de26f648 | josedoneguillen/fundamentos_programacion_python | /tipos_de_datos/ejercicio-6-jose-done.py | 444 | 4.3125 | 4 | '''
Ejercicio 6:
Escribe un script que imprima el indice de una letra dentro de una tupla.
'''
# Declaracion de tupla
tupla = (1, 2, 3, 'a', 5)
# Recorrer tupla con un ciclo for
for k, v in enumerate(tupla) :
# Sentencia if para comparar el tipo de dato
if type(v) == str :
# Imprimir si el tipo de dato encontrado es string
print('El indice de la letra (' + str(v) + ') es: ' + str(k) )
| false |
fb794266d84181ac8b6b56ccd6d6026e4c6b2958 | mridubhatnagar/HackerRank | /Algorithms/14-PickNumbers.py | 1,547 | 4.5 | 4 | """
Given an array of integers, find and print the maximum number of integers you can select from the array such that the absolute difference between any two of the chosen integers is less than or equal to . For example, if your array is , you can create two subarrays meeting the criterion: and . The maximum length subarray has elements.
Input Format
The first line contains a single integer , the size of the array .
The second line contains space-separated integers .
Constraints
The answer will be .
Output Format
A single integer denoting the maximum number of integers you can choose from the array such that the absolute difference between any two of the chosen integers is .
Sample Input 0
6
4 6 5 3 3 1
Sample Output 0
3
Explanation 0
We choose the following multiset of integers from the array: . Each pair in the multiset has an absolute difference (i.e., and ), so we print the number of chosen integers, , as our answer.
Sample Input 1
6
1 2 2 3 1 2
Sample Output 1
5
Explanation 1
We choose the following multiset of integers from the array: . Each pair in the multiset has an absolute difference (i.e., , , and ), so we print the number of chosen integers, , as our answer.
"""
#!/bin/python3
import sys
def pickingNumbers(a):
# Complete this function
for x in range(len(a) - 1):
diff=abs(a[x] - a[y+1])
print(diff)
return
if __name__ == "__main__":
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
result = pickingNumbers(a)
print(result)
| true |
b3e72effa59a444e1c43213b0b93a4ae9ff58799 | mridubhatnagar/HackerRank | /Algorithms/08-MiniMaxSum.py | 1,379 | 4.15625 | 4 | """
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
Input Format
A single line of five space-separated integers.
Constraints
Each integer is in the inclusive range .
Output Format
Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than a 32 bit integer.)
Sample Input
1 2 3 4 5
Sample Output
10 14
Explanation
Our initial numbers are , , , , and . We can calculate the following sums using four of the five integers:
If we sum everything except , our sum is .
If we sum everything except , our sum is .
If we sum everything except , our sum is .
If we sum everything except , our sum is .
If we sum everything except , our sum is .
"""
#!/bin/python3
import os
import sys
#
# Complete the miniMaxSum function below.
#
def miniMaxSum(arr):
#
# Write your code here.
#
sum =0
L=[]
for element in arr:
sum = sum + element
for x in arr:
result = sum - x
L.append(result)
print(min(L), max(L))
if __name__ == '__main__':
arr = list(map(int, input().rstrip().split()))
miniMaxSum(arr) | true |
ebc237db02b113adfcb33fd2463f672eb279f2d4 | mridubhatnagar/HackerRank | /Algorithms/60-QuickSort1.py | 764 | 4.15625 | 4 | """
Problem Statement - https://www.hackerrank.com/challenges/quicksort1/problem
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the quickSort function below.
def quickSort(arr):
pivot = arr[0]
left = []
right = []
L = []
for element in arr:
if element < pivot:
left.append(element)
elif element > pivot:
right.append(element)
L.extend(left)
L.append(pivot)
L.extend(right)
return L
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = list(map(int, input().rstrip().split()))
result = quickSort(arr)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
| true |
4dafca281aa72373b6fd9a00a2cc61cbc0d4a5cc | mridubhatnagar/HackerRank | /Algorithms/06-plusMinus.py | 1,812 | 4.15625 | 4 | """
Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.
Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to are acceptable.
Input Format
The first line contains an integer, , denoting the size of the array.
The second line contains space-separated integers describing an array of numbers .
Output Format
You must print the following lines:
A decimal representing of the fraction of positive numbers in the array compared to its size.
A decimal representing of the fraction of negative numbers in the array compared to its size.
A decimal representing of the fraction of zeros in the array compared to its size.
Sample Input
6
-4 3 -9 0 4 1
Sample Output
0.500000
0.333333
0.166667
Explanation
There are positive numbers, negative numbers, and zero in the array.
The proportions of occurrence are positive: , negative: and zeros: .
"""
import os
import sys
#
# Complete the plusMinus function below.
#
def plusMinus(arr):
#
# Write your code here.
#
positive = 0
negative = 0
zero = 0
for element in arr:
if element < 0:
negative += 1
elif element > 0:
positive += 1
elif element == 0:
zero +=1
print(positive, negative, zero)
# Proportion of occurance
positive_fraction = positive/len(arr)
print("%.6f" %(positive_fraction))
negative_fraction = negative/len(arr)
print("%.6f" %(negative_fraction))
zero_fraction = zero/len(arr)
print("%.6f" %(zero_fraction))
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr)
| true |
b74ad38a5d4d061970134499891663af1dbd1806 | mridubhatnagar/HackerRank | /Algorithms/10-TimeChallenge.py | 1,371 | 4.15625 | 4 | """
Given a time in -hour AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.
Function Description
Complete the timeConversion function in the editor below. It has the following description:
Parameters Name Type Description
s String Time in 12-hour format.
Return The function must return a string denoting time in 24-hour format.
Raw Input Format
A single string containing a time in -hour clock format (i.e.: or ), where and .
Sample Input 0
07:05:45PM
Sample Output 0
19:05:45
"""
#!/bin/python3
import os
import sys
#
# Complete the timeConversion function below.
#
def timeConversion(s):
#
# Write your code here.
#
time = s[:-2]
if 'PM' in s:
L=s[:-2].split(":")
if int(L[0]) < 12:
L[0] = str(int(L[0]) + 12)
time = ':'.join(L)
else:
time = s[:-2]
elif 'AM' in s:
L=s[:-2].split(":")
L[0] = str(int(L[0]) - 12)
if int(L[0]) >= 0:
L[0] = '00'
time = ':'.join(L)
else:
time = s[:-2]
return time
if __name__ == '__main__':
#f = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = timeConversion(s)
print(result)
#f.write(result + '\n')
#f.close() | true |
7a5dc9275ee3e2f3d65030bf6ccc94cc9726ee24 | CrisKP/Udemy-Programming-with-Python | /if-else.py | 294 | 4.15625 | 4 | # if/elif statements
grade = int(input("Enter the student's grade: "))
if grade >= 90:
print("Student got an A")
elif grade >= 80:
print("Student got a B")
elif grade >= 70:
print("Student got a C")
elif grade >= 60:
print("Student got a D")
else:
print("Student got an F")
| true |
1732699c249b68d7f63e09143d031a90eb006c51 | CrisKP/Udemy-Programming-with-Python | /print-statements.py | 244 | 4.25 | 4 | print("Hello Python")
print("Hi", "Python")
#Using a separator
print("Hello", "Python", sep="-")
#New style string format of Py3 using {} as a place holder for the value being passed in to the format function.
print("Hi {}".format("Python"))
| true |
315c9871da7ab1029320da36446504cfe4840376 | iainsproat/Euler | /src/python/Problem0004/problem0004.py | 984 | 4.125 | 4 | def largest_palindrome(num_digits):
max_input = 10 ** num_digits
min_input = 10 ** (num_digits - 1)
inputs = range(min_input, max_input)
products = []
print('Debug: max_input: {0}'.format(max_input))
print('Debug: min_input: {0}'.format(min_input))
for input1 in inputs:
for input2 in inputs: #TODO this doubles up items and could be optimised
products.append(input1 * input2)
largest_candidate = 0
for candidate in products:
if not candidate > largest_candidate:
continue #move to the next candidate
s = str(candidate)
length = len(s)
completed = True
for i in range(0, int(length/2)):
if s[i] != s[length - 1 - i]:
completed = False
break
if completed:
largest_candidate = candidate
return largest_candidate
if __name__ == "__main__":
print(largest_palindrome(3))
| true |
573542da145a442fb98a0218b499d3a0b50c2cb9 | LinJunVanier2019/LinJunSorting | /radixsort.py | 1,643 | 4.1875 | 4 |
# Algorithm : Radix Sort
"""
Time Complexity :
Best-case : O(kn); Average-case : O(kn); Worst-case : O(kn)
Where k is the length of the largest number in the list
and n is the size of the list
Space Complexity:
O(k+n)
"""
"""
Radix sort is similar to counting sort and bucket sort.
It creates buckets for each base digit (ie. 0-9)
And rearrange the list using counting sort.
It rearranges each number based on their radix
"""
def radixSort(alist):
digit = 0 #set base digit
maxdigit = 1 #to find biggest digit
max_num = max(alist)
while max_num > 10**maxdigit:
maxdigit += 1
while digit < maxdigit:
bucket = {} #dictionary as 'bucket'
for x in range(10):
bucket.setdefault (x,[]) #set each bucket from base 0-9
for num in alist:
radix = int((num/(10**digit)%10)) #find its radix(number at the digit that's being checked)
bucket[radix].append(num) #arrange each number in to its bucket
index=0
for check in range(10):
if len(bucket[check]) != 0: #check if there is number in the bucket
for y in bucket[check]:
alist[index] = y #rearrange each number into the original list
index += 1 #in the order from the bucket
digit += 1 #loop stop when check digit reaches maxdigit
import time
import random
alist = []
for i in range(0,100000):
num= random.randint(1,99999999)
alist.append(num)
start = time.time()
radixSort(alist)
end = time.time()
print (end-start)
| true |
c024d9e28dcb129543da0e973b5bc85925d223cc | e36blur/election-analysis-python | /notes.py | 888 | 4.25 | 4 | # Import the datetime class from the datetime module.
#import datetime as dt
# Use the now() attribute on the datetime class to get the present time.
#now = dt.datetime.now()
# Print the present time.
#print("The time right now is ", now)
# Import the datetime class from the datetime module.
#import datetime
# Use the now() attribute on the datetime class to get the present time.
#now = datetime.datetime.now()
# Print the present time.
#print("The time right now is ", now)
# Create a filename variable to a direct or indirect path to the file.
file_to_save = os.path.join("analysis", "election_analysis.txt")
# Using the open() function with the "w" mode we will write data to the file.
open(file_to_save, "w")
# Using the with statement open the file as a text file.
txt_file = open(file_to_save, "w")
# Write some data to the file.
txt_file.write("Arapahoe\nDenver\nJefferson")
| true |
5e85bec370a6928e7a648b34de7fadd3eaecf526 | markcharyk/fizzbuzz | /fizzbuzz.py | 592 | 4.34375 | 4 | def fizz_buzz(n):
return_string = ''
# Is the number divisible by three? -> Add a Fizz
if n % 3 == 0:
return_string += 'Fizz'
# Is the number divisible by five? -> Add a Buzz
if n % 5 == 0:
return_string += 'Buzz'
# Is there a Fizz or Buzz yet? -> return the number as a string
if return_string == '' or n == 0:
return str(n)
# Otherwise, return Fizz and/or Buzz
return return_string
if __name__ == '__main__':
user_input = raw_input("What is the number with which we are concerned? ")
print fizz_buzz(int(user_input))
| true |
61fb46aaca368e5f2cb4b052d22c6768bc912366 | Ryan-R-C/my_hundred_python_exercises | /Exercises/exc36.py | 508 | 4.15625 | 4 | print("Today we'll see if you were accredited!")
print('''Our system is:
If your final media is lower than 5 - Disapproved
Your final media between 5.0 and 6.9 - Recuperation
And finally bigger than 7 - Okay''')
notea = float(input("Type here your first note."))
noteb = float(input("Now the last."))
final = ((notea+noteb)/2)
if final < 5:
print("Disapproved! How shame!")
elif 5 <= final <= 6.9:
print("Recuperation! I'll see ya on the your vacations! HA HA HA!")
else:
print("You're Okay!") | true |
c01042ae17e215f18d314bca20251425e0c3759a | Ryan-R-C/my_hundred_python_exercises | /Exercises/exc60.py | 260 | 4.21875 | 4 | print("Fibonacci!")
n = int(input("Type here how many terms:"))
x = 0
t1 = 0
t2 = 1
print("{} -> {}".format(t1,t2), end="")
cont = 3
while cont <= n:
t3 = t1 + t2
print(" -> {}".format(t3), end="")
t1 = t2
t2 = t3
cont += 1
print("-> End")
| false |
967b19ee30728796f670682e5b775577989edfdf | Ryan-R-C/my_hundred_python_exercises | /Exercises/exc30.py | 467 | 4.25 | 4 | print("Now let's see which is the biggest and the smallest! ")
a = int(input("Enter here a number."))
b = int(input("Enter here an another number."))
c = int(input("Enter here the last one, please."))
smallest = a
biggest = a
if b < a and b < c:
smallest = b
if c < a and c < b:
smallest = c
print("The smallest is {}".format(smallest))
if b > a and b > c:
biggest = b
if c > a and c > b:
biggest = c
print("And the biggest is {}".format(biggest)) | true |
6a5d37b904a3992b1f56619b30ecf8705ab25145 | felrivglz/Python | /e5.py | 234 | 4.125 | 4 | #this is a little example the how use the sentece 'if'
x=int(raw_input("ingresa un numero entero:"))
if x<0:
x=0
print'Negativo cobinadi a cero'
elif x==0:
print 'cero'
elif x==1:
print 'somple'
else :
print 'mas'
| false |
8e8eb65a92d00b8caee1e0b9d4ef738162b8abbd | YeetOrBeYate/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 684 | 4.25 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
word = "abcthxyz"
def count_th(word):
value = "th"
n1 = len(word)
n2 = len(value)
if n1 == 0:
return 0
# if the first two letters of the string have it, add one to the return
if word[0 :n2] == value:
# move 1 leter over and repeat
return count_th(word[n2-1:]) + 1
else:
#move 1 leter over and repeat
return count_th(word[n2-1:])
print(count_th(word)) | true |
e79a01992aa620d22583c438f523829c8db94916 | shivanibadoni/G7 | /G7.py | 1,592 | 4.4375 | 4 | #Q1. Write a python program using tkinter interface to write Hello World and a exit button that closes the interface."""
from tkinter import *
m = Tk()
label = Label(m, text= "\nHello World\n")
label.pack()
#Q2. Write a python program to in the same interface as above and create a action when the button is click it will display some text.
def write_TEXT():
print("Acadview Python Training")
button = Button(m,text='Click to See Message',width=50,command = write_TEXT)
button.pack()
#Q3. Create a frame using tkinter with any label text and two buttons. One to exit and other to change the label to some other text.
r = Tk()
def change_label():
label2["text"] = "Python Programming "
frame = Frame(r)
frame.pack()
label2 = Label(r,text="\nCLICK TO CONTINUE\n")
label2.pack()
bottomframe = Frame(r)
bottomframe.pack(side=BOTTOM)
stopbutton = Button(frame, text='Abort', width = 30, fg = 'Red', command = r.destroy)
stopbutton.pack(side=LEFT)
printbutton = Button(frame, text='Change Label', width = 30, fg = 'Steel Blue', command=change_label)
printbutton.pack(side=LEFT)
#Q4. Write a python program using tkinter interface to take an input in the GUI program and print it.
tk = Tk()
def display():
print(temp1.get()+ " is " +temp2.get())
Label(tk, text = "Enter your name: ").grid(row=0)
Label(tk, text = "Enter AGE: ").grid(row=1)
temp1 = Entry(tk)
temp2 = Entry(tk)
temp.grid(row=0,column=1)
temp.grid(row=1,column=1)
button1 = Button(tk, text='PRINT',width=50,fg='Blue',command=display)
button1.grid(row=4,column=1)
m.mainloop()
| true |
ff8dd5ce7b0595f3702ec035e1aa40066a7bc79c | shashwatagarwal/Tech_Savvy_Entrepreneurship | /Day1.py | 2,077 | 4.15625 | 4 | ##math
# #minute to seconds converter
# print("Enter time in minutes")
# minutes = input()
# seconds = float(minutes)* 60
# print("There are {} seconds in a minute".format(seconds))
# # date/time
# import datetime
# now = datetime.datetime.now()
# print(now.hour,"hours", now.minute,"minutes", now.second, "seconds")
# print(now.year)
#
# # volume calculator
# import math
# print("Enter the desired radius")
# radius = int(input())
# volume = (4/3)*math.pi*math.pow((radius),3)
# print("The volume of your sphere is {:.2f}".format(volume))
# print("Input a base and a power")
# base = int(input())
# power = int(input())
# length_of_number = len(str(base**power))
# print(base**power)
# print(length_of_number)
# import random
# print("input the lower and upper bound")
# lb = int(input())
# ub = int(input())
# # print(random.random()*(ub-lb)+lb)
# print(random.randint(lb, ub))
# print(random.choice([1,2,3,4,5,6]))
## Strings
# \n - new line
# \ - keep apostrophe
# print('I am saying I am \'OK\'')
# print("Hi!\nMy name is Shashwat")
## Boolean - important for conditional statements
# print(3>2)
# print(3>5)
# print(3 > 2 and 3 > 5)
# print(3 > 2 or 3 > 5)
# Virtual Bouncer
age = int(input("How old are you?"))
location = input("Are you located in the greater boston area? ")
timeleft = (21 - age)
if age >= 21 and location == 'yes':
print('Your all set! Time to party!')
elif age < 21 and location == 'yes':
print("Sorry, you have to wait for {} year!".format(timeleft))
if timeleft == 1:
print("Sorry, you have to wait for {} more year!".format(timeleft))
else:
print("Sorry, you have to wait for {} more years!".format(timeleft))
elif age < 21 and location == 'no':
if timeleft == 1:
print("Sorry, you have to wait for {} more year and move to boston!".format(timeleft))
else:
print("Sorry, you have to wait for {} more years and move to boston!".format(timeleft))
elif age >= 21 and location == 'no':
print("Sorry, you are too far away from us!")
# == is literally equal to
# != is not equal to
| true |
fb3c8fc56f75b5ba0f42a43affce179721a33e9b | shafaypro/shafayworkspace | /Practicechecks/Gpa.py | 545 | 4.15625 | 4 | checker=True # just tp check the condition rather to be true of false
counter=1 # To keep track of the current Semester
TOTAL_CGPA=0.0; #count the total cgpa variable
checker = raw_input('Do you want to continue and False to Cancel now')
while(checker == 'True'):
GPA= '''Here write the function called having a return type which you had made before '''
TOTAL_CGPA += GPA
checker = raw_input('Add Another Semester? True to continue , False to finish')
counter += 1
print ('Your Cgpa Till now is :',TOTAL_CGPA/(counter-1))
| true |
e1fa4ddb19180218351702833886ec85b639110b | mmaung1/MIS-3640 | /session05/exercise1.py | 2,143 | 4.46875 | 4 | import turtle #importing the turtle package
import math #importing the math package in which we get pi from
jonathan = turtle.Turtle() #naming the turtle function as jonathan
print(jonathan) #printing the window
def polygon(turtle, n, length):
angle = 360 / n
for i in range(n):
turtle.fd(length)
turtle.lt(angle)
def circle(turtle, r):
circumference = 2 * math.pi * r
n = 100
length = circumference / n
polygon(turtle, n, length)
def arc(turtle, r, angle):
arc_length = 2 * math.pi * r * angle / 360
n = int(arc_length / 3) + 1
step_length = arc_length / n
step_angle = angle / n
for i in range(n):
turtle.fd(step_length)
turtle.lt(step_angle)
def triangle (turtle, length, angle):
for i in range(3):
turtle.forward(length)
turtle.left(angle)
def move(turtle,x,y):
turtle.pu()
turtle.setpos(x,y)
turtle.pd()
# drawing the flower inside the circle
circle(jonathan, 100) #draw the circle
jonathan.left(60)
arc(jonathan,100,120)
jonathan.left(120)
arc(jonathan,100,120)
jonathan.left(120)
arc(jonathan,100,120)
move(jonathan,0,200)
jonathan.right(59)
arc(jonathan,100,120)
jonathan.left(119)
arc(jonathan,100,120)
jonathan.left(120)
arc(jonathan,100,120)
# #drawing yinyang
# jonathan.pensize(3)
# circle(jonathan, 100) #draw the circle
# move(jonathan,0,100)
# arc(jonathan,50,180)
# move(jonathan,0,100)
# arc(jonathan,50,180)
# move(jonathan,0,35)
# circle(jonathan,15)
# move(jonathan,0,135)
# circle(jonathan,15)
#drawing the pizza
# circle(jonathan, 100) #draw the circle
# move(jonathan,54,185)
# jonathan.left(180)
# triangle(jonathan,100,120)
# move(jonathan,-46,12)
# jonathan.right(180)
# triangle(jonathan,100,120)
# move(jonathan,90,48)
# jonathan.left(90)
# triangle(jonathan,100,120)
# move(jonathan,2,99)
# jonathan.left(60)
# triangle(jonathan,100,120)
# move(jonathan,76,122)
# circle(jonathan,29)
# move(jonathan,-40,123)
# circle(jonathan,29)
# move(jonathan,20,66)
# circle(jonathan,29)
# move(jonathan,20,180)
# circle(jonathan,29)
turtle.mainloop() #keeps screen open, but must be at very end
| false |
93ea4ff6435b56bf4dc80850829703b3f12b9f63 | NathanaelNeria/Workshop6 | /intermediate.py | 404 | 4.25 | 4 | color_name = {"Aliceblue":'#f0f8ff', 'Antiquewhite':'#faebd7', 'Antiquewhite1':'#ffefdb', 'Antiquewhite2':'#eedfcc', 'Antiquewhite3':'#cdc0b0', 'Antiquewhite4':'#8b8378', 'Aquamarine1':'#7fffd4', 'Aquamarine2':'#76eec6', 'Aquamarine4':'#458b74', 'Azure1':'#f0ffff'}
colorinput=input("Enter a color name: ").capitalize()
for key,value in color_name.items():
if colorinput == key:
print(value) | false |
c6dbde760d6512f3945a15ee239478ad5cef153b | iamniting/hackerrank | /number-staircase.py | 1,531 | 4.34375 | 4 | #!/bin/python3
# A number staircase s is an integer number, when read from left to right,
# starts with the number 1, which is followed by a 2, which is followed
# by a 3, and so on. This process continues until a maximum number n is
# reached, which may contain more than one digit. From this point, the
# number staircase s will descend starting at n - 1, then n - 2,
# then n - 3, and so on, until it descends back to 1.
import doctest
def isStairCase(s):
"""
>>> isStairCase('123456789101110987654321')
True
>>> isStairCase('12345678910987654321')
True
>>> isStairCase('123321')
False
>>> isStairCase('11')
False
>>> isStairCase('2')
False
"""
if s == '1':
return True
if len(s) == 1:
return False
length = len(s)
i = 1
j = length - 2
old = int(s[0])
new = int(s[0])
r_old = int(s[length-1])
r_new = int(s[length-1])
digits = 1
res = False
while i <= j:
if new in (9, 99, 999, 9999, 99999):
digits += 1
old = new
new = int(s[i:i + digits])
r_old = r_new
r_new = int(s[-(i + digits):-i])
if new == r_new and new - old == 1 and r_new - r_old == 1:
res = True
else:
return False
i = i + digits
j = j - digits
if new == int(s[i:i+digits]):
return False
return res
if __name__ == '__main__':
doctest.testmod()
s = str(input())
res = isStairCase(s)
print (res)
| true |
dc39381cc929823296ba30a891de05b9c6c0ef19 | gettodaze/BioInfo | /FASTA_9-14/fasta.py | 903 | 4.15625 | 4 | def read_sequences_from_fasta_file(filename):
"""Reads all sequence records from the FASTA-formatted file specified by filename
and returns a list of records. Each record is represented by a tuple (name, sequence)"""
sequences = []
current_record_lines = None
for line in open(filename):
if line.startswith(">"):
if current_record_lines is not None:
sequences.append(sequence_from_fasta_lines(current_record_lines))
current_record_lines = []
current_record_lines.append(line.rstrip())
# Handle the last record in the file
if current_record_lines is not None:
sequences.append(sequence_from_fasta_lines(current_record_lines))
return sequences
def sequence_from_fasta_lines(lines):
# Strip the beginning '>'
name = lines[0][1:]
sequence = ''.join(lines[1:])
return (name, sequence)
| true |
fb214e24f33f40590e967978306b94c1d4b7c29b | ChrisMCodes/CoinToss | /cointoss.py | 2,224 | 4.21875 | 4 | #!/usr/bin/env
#
#
# Purpose: performs a simulation of coin tosses
# to use empirical data
# to demonstrate the law of large numbers.
#
# Last update: 2020-06-18
# Uses random package to choose heads or tails
import random
def coin_flip(trials, my_data):
'''randomizes 0 and 1 'trials' times'''
my_data += [random.randint(0, 1) for i in range(0, trials)]
return my_data
def get_vals(my_data, my_dict):
'''compiles my_data into a dictionary, 0 and 1 are keys, count of each are values'''
for data in my_data:
if data in my_dict:
my_dict[data] += 1
else:
my_dict[data] = 1
return my_dict
def show_results(my_data, my_dict):
'''prints out percentages. Here, we'll call 0 heads and 1 tails'''
# some local variables to handle counts
heads = my_dict[0] / (my_dict[0] + my_dict[1]) * 100
tails = my_dict[1] / (my_dict[0] + my_dict[1]) * 100
trials = len(my_data)
variance = 0
if heads > 50:
variance = heads - 50
else:
variance = tails - 50
# print("Heads: {:.3f}%, tails: {:.3f}% for a total variance from 50% of {:.3f}% in a trial of {}.".format(heads, tails, variance, trials)) # This can be commented out if you don't want it
return variance
# A sample test
def test_it(num):
'''This function was added for my test purposes only'''
max_variance = 0
current_variance = 0
# iterates through num flips x times
for i in range(0, 10):
my_data = []
my_dict = {}
my_data = coin_flip(num, my_data)
my_dict = get_vals(my_data, my_dict)
current_variance = show_results(my_data, my_dict)
if current_variance > max_variance:
max_variance = current_variance
# prints how far the results of this round varied from an even 50/50 split.
# for example, if you flipped 9 heads and 1 tail, that's a 90% max variance.
print("In 10 trials of {} flips each, the max variance from a 50/50 split was: {:.3f}%.".format(num, max_variance))
pass
# calling my test_it function with multiples of 10 flips
test_it(10)
test_it(100)
test_it(1000)
test_it(10000)
test_it(100000)
| true |
0fa3500fca11f294ca284c4ad3e5a2b4cd26b3b0 | KanwalSaeed/Nested_If_Statement_Python | /20. NESTED IF STATEMENT IN PYTHON.py | 1,249 | 4.15625 | 4 | first_number = int(input("Enter First Number: "))
second_number = int(input("Enter Second Number: "))
third_number = int(input("Enter Third Number: "))
if first_number > second_number and first_number > third_number:
print("First Number is at First Position.")
if second_number > third_number:
print("Second Number is at Second Position")
print("Third number is at Third Position")
else:
print("Second Number is at Third Position.")
print("Third Number is at Second Position.")
if second_number > first_number and second_number > third_number:
print("Second Number is at First Position")
if first_number > third_number:
print("First Number is at Second Position.")
print("Third Number is at Third Position")
else:
print("First Number is at Third Position")
print("Third Number is at Second Position")
elif third_number > first_number and third_number > second_number :
print("Third Numbe is at First position")
if first_number > second_number:
print("First Number is at Second Positionn")
print("Second number is at Third Position")
else:
print("First number is at Thid Position")
print("Second Number is at Second Position")
| false |
e8567fe1499da05aa814ae43463369aac71e30bf | lawrenceguofc/leetcode | /educative/stack/balanced_brackets.py | 974 | 4.15625 | 4 | from stack import Stack
def is_match(p1,p2):
if p1 == '(' and p2 == ')':
return True
elif p1 == '{' and p2 == "}":
return True
elif p1 == '[' and p2 == ']':
return True
else:
return False
def is_bracket_balanced(str):
s = Stack()
i = 0
is_balanced = True
while i < len(str):
if str[i] in '([{':
s.push(str[i])
else:
if s.is_empty():
is_balanced = False
else:
top = s.pop()
if not is_match(top,str[i]):
is_balanced = False
i += 1
return is_balanced
def main():
print("String : (((({})))) Balanced or not?")
print(is_bracket_balanced("(((({}))))"))
print("String : [][]]] Balanced or not?")
print(is_bracket_balanced("[][]]]"))
print("String : [][] Balanced or not?")
print(is_bracket_balanced("[][]"))
if __name__ == "__main__":
main() | false |
c11375728e0edb9adbb298ea3c69234711effdc9 | mmichall/PyTorchTutorial | /example5.py | 2,217 | 4.15625 | 4 | import torch
from torch.autograd import Variable # for computational graphs
import torch.nn as nn ## Neural Network package
import torch.optim as optim # Optimization package
# Now, instead of calculating the gradient of our linear layer wrt our inputs (x) in lesson 3,
# we're going to calculate the gradient of our loss function wrt our weights / biases
x1 = torch.Tensor([1, 2, 3, 4])
x1_var = Variable(x1, requires_grad=True)
linear_layer1 = nn.Linear(4, 1)
target_y = Variable(torch.Tensor([0]), requires_grad=False)
predicted_y = linear_layer1(x1_var)
loss_function = nn.MSELoss()
loss = loss_function(predicted_y, target_y)
optimizer = optim.SGD(linear_layer1.parameters(), lr=1e-1)
# here we've created an optimizer object that's responsible for changing the weights
# we told it which weights to change (those of our linear_layer1 model) and how much to change them (learning rate / lr)
# but we haven't quite told it to change anything yet. First we have to calculate the gradient.
loss.backward()
# now that we have the gradient, let's look at our weights before we change them:
print("----------------------------------------")
print("Weights (before update):")
print(linear_layer1.weight)
print(linear_layer1.bias)
# let's also look at what our model predicts the output to be:
print("----------------------------------------")
print("Output (before update):")
print(linear_layer1(x1_var))
optimizer.step()
# we told the optimizer to subtract the learning rate * the gradient from our model weights
print("----------------------------------------")
print("Weights (after update):")
print(linear_layer1.weight)
print(linear_layer1.bias)
# looks like our weights and biases changed. How do we know they changed for the better?
# let's also look at what our model predicts the output to be now:
print("----------------------------------------")
print("Output (after update):")
print(linear_layer1(x1_var))
print("----------------------------------------")
# wow, that's a huge change (at least for me, and probably for you). It looks like our learning rate might be too high.
# perhaps we want to make our model learn slower, compensating with more than one weight update?
# next section! | true |
f1473d0869390b9453bfd9f38d2cf2ebb7623cd8 | Viswanath-Hemanth/My-ML-Internship-at-Indian-Servers | /Week 1/recursion_fibonacci.py | 615 | 4.53125 | 5 | '''
Complete the recursive function fibonacci() in the editor below. It must return the nth element in the Fibonacci sequence.
fibonacci has the following parameter(s):
n: the integer index of the sequence to return
Input Format
The input line contains a single integer, n.
Output Format
Locked stub code in the editor prints the integer value returned by the fibonacci() function.
Sample Input
3
Sample Output
2
'''
def fibonacci(n):
if (n == 0):
return 0
if (n == 1):
return 1
else:
return (fibonacci(n - 1) + fibonacci(n - 2))
n = int(input())
print(fibonacci(n))
| true |
9ef794e9fe93782e2de30e05b54d16c1413123d2 | bilalmaxood/01_Python | /01_03 Functions.py | 839 | 4.40625 | 4 | #Functions
#How to define a function
def func():
print "This is a function definition"
#Function Calling
func()
print func()
print func # returns the address where functino func() is located
#Passing arguments in a function
def func2(arga, argb):
print arga,'*', argb
# Function call
func2(10,13)
#Function that returns a value
def func3(y):
return y*y
print func3(4)
# Passing variable no. of arguments
def func4(*args):
tot = 0
for i in args:
tot = tot + i
return tot
print func4(1,2,3,4,12)
# Function with defalut value of an arguments
def func5(num, ras = 1):
pow = 1
for i in range(ras):
pow = pow * num
return pow
print func5(3) # here, default value of ras = 1 is used
print func5(3,2) # here, 2 is used as the raise to power
print func5(ras = 2, num = 4) | true |
e19df44764cc759b6313d0620e42acbd7ef9e265 | dana19-meet/meet2017y1lab6 | /funturtle.py | 917 | 4.15625 | 4 | import turtle
'''turtle.shape('turtle')
square=turtle.clone()
square.shape('square')
square.goto(100,0)
square.goto(100,100)
square.goto(0,100)
square.goto(0,0)
square.goto(300,300)
square.stamp()
square.goto(100,100)
triangle=turtle.clone()
triangle.shape('triangle')
triangle.goto(-100,-100)'''
UP_ARROW="Up"
LEFT_ARROW="Left"
DOWN_ARROW="Down"
RIGHT_ARROW="Right"
SPACEBAR="space"
UP=0
LEFT=1
DOWN=2
RIGHT=3
direction=UP
def up():
global direction
direction=UP
print('you pressed up')
def left():
global direction
direction=LEFT
print('you pressed left')
def down():
global direction
direction=DOWN
print('you pressed down')
def right():
global direction
direction=RIGHT
print('you pressed right')
turtle.onkeypress(up,UP_ARROW)
turtle.onkeypress(down,DOWN_ARROW)
turtle.onkeypress(right,RIGHT_ARROW)
turtle.onkeypress(left,LEFT_ARROW)
turtle.mainloop()
| false |
f68293232185ff47be5292cee6f769a66e855626 | GilDark012/python_examples | /Factorial.py | 483 | 4.21875 | 4 | num = int(input("Enter any number :"))
# Method - 1 --> using loop
def cal_factorial(num):
factorial = 1
if num == 0 or num == 1:
return 1
for i in range(1, num+1):
factorial = factorial * i
return factorial
output = cal_factorial(num)
print('Factorial of number ', num , ' is : ', output)
# Method - 2 --> using inbuilt function from math module
import math
output = math.factorial(num)
print('Factorial of number ', num , ' is : ', output)
| true |
2c91bd91bb34f1a785bd11f21d3374420c6ec52e | piotrsty/py_lab | /z_constructors.py | 732 | 4.28125 | 4 | class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self):
print("move")
def draw(self):
print("draw")
point = Point(10, 20)
point.x = 11
print(point.x)
#exercise
class Person:
#we call this new method a constructor; 'name' is parameter
def __init__(self, name):
#self references the current object we're setting the name attribute of the current object, to the name argument passed to this method
self.name = name
def talk(self):
print(f"Hi, I am {self.name}")
#john = Person()
john = Person("John Smith")
#print(john.name)
john.talk()
#each object is a different instance of a person class
bob = Person("Bob Smith")
bob.talk()
| true |
b3ebaad00b609ff91709235043bca40b7fff4dfc | X-thon/LeetCodeRecord | /leetcode225_用两个队列实现栈/leetcode225_用两个队列实现栈.py | 1,788 | 4.1875 | 4 | from queue import Queue
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue1 = Queue()
self.queue2 = Queue()
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
if self.queue1.empty():
self.queue2.put(x)
elif self.queue2.empty():
self.queue1.put(x)
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
if self.queue1.empty() and self.queue2.empty():
return
if not self.queue1.empty():
while self.queue1.qsize() != 1:
self.queue2.put(self.queue1.get())
return self.queue1.get()
if not self.queue2.empty():
while self.queue2.qsize() != 1:
self.queue1.put(self.queue2.get())
return self.queue2.get()
def top(self) -> int:
"""
Get the top element.
"""
if self.queue1.empty() and self.queue2.empty():
return
if not self.queue1.empty():
while self.queue1.qsize() != 1:
self.queue2.put(self.queue1.get())
top = self.queue1.get()
self.queue2.put(top)
return top
if not self.queue2.empty():
while self.queue2.qsize() != 1:
self.queue1.put(self.queue2.get())
top = self.queue2.get()
self.queue1.put(top)
return top
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
if self.queue1.empty() and self.queue2.empty():
return True
else:
return False
| false |
acda490c0827c98a1b9485d53be69c4ffc39a2eb | testerkurio/python_learning | /liaoxuefeng_python3.5/test_2.py | 558 | 4.3125 | 4 | # 测试代码:
print('The big animal','is a lion','with golden firgure.')
print(300)
print(100+200)
print('100 + 200 =',100+200)
'''
print("please enter your name:")
name = input()
print('what\'s up,',name,"?")
'''
print("1024 * 768 =",1024*768)
print('\\\t\\')
print(r'\\\t\\')
print(r'''line1
line2
line3''')
'''
age=int(input())
if age>=18:
print('adult')
else:
print('teenager')
'''
n=123
f=456.789
s1=('Hello, world')
s2=('Hello, \'Adam\'')
s3=(r'Hello, "Bart"')
s4=(r'''Hello,
Lisa!''')
print(n,'\n',f,'\n',s1,'\n',s2,'\n',s3,'\n',s4)
| false |
6ff1848d46ef3fc134be575355985904502097f9 | testerkurio/python_learning | /python_with_kids/list_5-3_tran-temperature.py | 203 | 4.21875 | 4 | print("This program converts Fahreherit to Celsius");
print("Type in temperature in Fahrenheit:"),
Fahreherit = float(input());
Celsius = (Fahreherit - 32)*5/9;
print("This is",Celsius,"degrees celsius") | false |
da9d8b9057099b305a8f1fac53db510c66cd5394 | Exxxx/countdownlooptimer | /countdown_timer.py | 1,220 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
A countdown timer that loops.
"""
import keyboard
import time
def countdown(t):
while t > 0:
print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
print(t)
t -= 1
time.sleep(1)
if keyboard.is_pressed("\\"):
print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nResetting in "+sleepstr+" seconds!")
time.sleep(sleeps)
countdown(seconds)
print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nNext in "+sleepstr+" seconds!")
time.sleep(sleeps)
countdown(seconds)
print("Press the backslash during countdown to reset.\n\nClose the program to select a new countdown length.\n\nHow many seconds to count down from?\nEnter an integer:")
seconds = input()
while not seconds.isdigit():
print("That wasn't an integer! Enter an integer:")
seconds = input()
print("Set the time between count downs.\nEnter an integer:")
sleeps = input()
while not sleeps.isdigit():
print("That wasn't an integer! Enter an integer:")
sleeps = input()
seconds = int(seconds)
sleeps = int(sleeps)
sleepstr = str(sleeps)
countdown(seconds)
| true |
d19d27f164b7975bb8bbf3dda419a7e0fc779c84 | the-code-experiments/get-to-know-python | /codes/session_9/jsonEg1.py | 770 | 4.28125 | 4 | # How to Run? Open Terminal> python3 jsonEg1.py
# Read the code comments and output on the terminal
# Objective: Know about JSON in Python using 'json' module
# Python Object
data = {
"empId": 1,
"name": {
"first": "Ashwin",
"last": "Hegde"
},
"email": "ashwin.hegde3@gmail.com",
"isEngineer": True
}
# Built-in JSON library
import json
# Dump Python Object to jsonEg1.json in JSON format
# using dump() function
with open('jsonEg1.json', 'w') as writeFile:
json.dump(data, writeFile)
print('\n')
# using dumps() function
jsonData = json.dumps(data, indent=2)
print('Data in JSON format: ', jsonData)
print('\n')
# Read data from JSON file
with open('jsonEg1.json', 'r') as readFile:
readData = json.load(readFile)
print('JSON file content: ', readData)
| true |
b6526c3ee3eb2857ebe765011b50c0871071a12f | the-code-experiments/get-to-know-python | /codes/session_2/default.py | 700 | 4.25 | 4 | # Open terminal > python3 default.py
# Start typing below commands and see the output
# Function with default values for arguments, and while loop examples
# Note: The default value is evaluated only once.
def askme(prompt, retries=3, reminder='Invalid response, please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'yes'):
return True
if ok in ('n', 'no'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('System is auto locked!')
print(reminder)
askme('Are you sure you want to quit? ')
# Annotations example
def hello(name: str) -> str:
print('Annotations: ', hello.__annotations__)
hello('Ashwin') | true |
ca42a0ce14fec2b223aaf673510476fd6c670cae | the-code-experiments/get-to-know-python | /codes/session_4/inputOutput.py | 1,068 | 4.21875 | 4 | # Open terminal > python3 inputOutput.py
# Start typing below commands and see the output
x = 10 * 45
y = 20 * 90
s = 'The value of x is ' + repr(x) + ' , and y is ' + repr(y)
print(s)
for a in range(1, 10):
print(repr(a).rjust(2), repr(a*a).rjust(3), end=' ')
print(repr(a*a*a).rjust(4))
print('\n\n')
for b in range(1, 10):
print('{0:2d} {1:3d} {2:4d}'.format(b, b*b, b*b*b))
print('\n\n')
import math
print('The value of PI is approximately %5.3f' % math.pi)
print('I love working on {} as well as {}!'.format('JavaScript', 'Python'))
print('I love working on {0} as well as {1}!'.format('JavaScript', 'Python'))
print('I love working on {1} as well as {0}!'.format('JavaScript', 'Python'))
print('My name is {name}, and I\'am a {job}'.format(name='Ashwin', job='Software Engineer'))
print('My name is {name}, and I love working in {0}, and {1}'.format('JavaScript', 'Python', name='Ashwin'))
table = {'Ashwin': 'Engineer', 'Saju': 'Architect', 'Ajay': 'Manager'}
for name, role in table.items():
print('{0:10} -> {1:10s}'.format(name, role)) | true |
445f2136e85dbcaf5d89a5fb11c37381ae880353 | poopy-boi/poopy-boi | /Untitled-1.py | 433 | 4.15625 | 4 | clouds = str(input('Is it cloudy today? Only answer with yes/no'))
temp = str(input('Does it feel cold? Only answer with yes/no'))
if clouds == 'yes' and temp == 'yes':
print('Highly likely it will rain today')
if clouds == 'yes' and temp == 'no':
print('It wont rain today')
if clouds == 'no' and temp == 'yes':
print('It wont rain today')
if clouds == 'no' and temp == 'no':
print('it wont rain today')
| true |
ee5e61f31cd34d980da3b7dc94a9921a3f95b051 | stjsmith8/stjsmith | /Coding Problem 2.3.12.py | 1,172 | 4.4375 | 4 | a = True
b = False
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#There are six logical operations to compare two boolean
#values. They are:
#
# And: True if both are True, False otherwise
# Or: True if either is True, False otherwise.
# Xor: True if exactly one is True; False if both are True
# or both are False ("Exclusive Or")
# Nand: False if both are True, True otherwise.
# Nor: False if either is True, True otherwise.
# Xnor: False if exactly one is True; True if both are True
# or both are False.
#
#For a and b above, print the results of all six operations,
#with the following format:
#
#And: False
#Or: True
#Xor: True
#Nand: True
#Nor: False
#Xnor: False
#
#Add your code below! Be aware: there is no dedicated operator
#in Xor, Nand, Nor, or Xnor. You'll have to find those values
#through a combination of And, Or, and Not.
print("And:", a and b)
print("Or:", a or b)
print("Xor:",(a and not b) or (not a and b))
print("Nand:", not(a and b))
print("Nor:", not(a or b))
print("Xnor:",(a and b) or (not a and not b))
| true |
aa3c3731cb6637f4faf6672186f66ef1b3dedc8b | SMGST/Git_Python_Test | /Others/Function.py | 2,106 | 4.21875 | 4 | def my_Function():
print("it is printing from function")
def function(fname):
print("Hello ," + fname)
def unKnown_args(*ar):
print("Secend Arguments : " + str(ar[1]))
print("All Arguments : ")
for x in ar:
print(x)
def keyword(ar2,ar3,ar1):
print("Argument no 1 = " + str(ar1))
def unknown_Keyword(**kid):
print("His First name is " + kid["fname"])
print("His last name is " + kid["lname"])
def defualt_Value(country = "Norway"):
print("I am from " + country)
def print_List(list):
for x in list:
print(x)
def sum(a,b):
return a+b
def myfunction():
pass
# having an empty function definition like this, would raise an error without the pass statement
def tri_recursion(k):
if(k<0):
return 0
result = k + tri_recursion(k-1)
print(result)
return result
# lambda function
x = lambda a:a*10
multipliction = lambda a,b:a*b
# lambda inside function
def funLambda(n):
return lambda a:a-n
myfunction()
print("------------------------------")
my_Function()
print("------------------------------")
function("Tamim")
print("------------------------------")
unKnown_args(1,2,3)
unKnown_args("C","C++","java","Python")
print("------------------------------")
keyword(ar1="Laptop",ar2="Mobile",ar3="TV")
print("------------------------------")
unknown_Keyword(fname = "Tobias", lname = "Refsnes")
print("------------------------------")
defualt_Value("Sweden")
defualt_Value("India")
defualt_Value()
defualt_Value("Brazil")
print("------------------------------")
list = ["C","C++","java","Python"]
print_List(list)
print("------------------------------")
tuples = ("Name","Roll","Dep")
print_List(tuples)
print("------------------------------")
print(sum(5,4))
print("------------------------------")
print("Recursion Example Results")
tri_recursion(7)
print("------------------------------\n\n\t# Lambda function")
print(x(5))
print(multipliction(5,6))
print("------------------------------\n\n\t# lambda inside function")
print(funLambda(2)(7))
z = funLambda(3)
print(z(10))
print("------------------------------")
| true |
0e76709f19159b6c8bdfb3cda6d6ee411bdae86f | evaldojr100/Python_Lista_2 | /18_categorias.py | 541 | 4.1875 | 4 | '''18) (BACKES, 2012) Escreva um programa que, dada a idade de um nadador, classifique-o em
uma das seguintes categorias:
Categoria Idade
Infantil A 5 a 7
Infantil B 8 a 10
Juvenil A 11 a 13
Juvenil B 14 a 17
Sênior Maiores de 18 anos
Salve o programa com o nome “ 18_categorias'''
idade=int(input("Digite a idade do nadador:"))
if 5<=idade<=7:
print("Infantil A")
elif 8<=idade<=10:
print("Infantil B")
elif 11<=idade<=13:
print("Juvenil A")
elif 14<=idade<=17:
print("Juvenil B")
elif idade>=18:
print("Senior") | false |
c53b9c0c5e586fa93664e830bf3b27d10655881d | MH10000/Python_Labs | /python_fundamentals-master/07_classes_objects_methods/car.py | 912 | 4.28125 | 4 | class Car():
"""Takes 3 data attributes associated with a car"""
def __init__(self, model, year, speed=0):
self.model = model
self.year = year
self.speed = speed
def accelerate(self):
"""Adds 5 to the speed of the car"""
self.speed += 5
def brake(self):
"""Reduces speed by 5 with a lower limit of zero"""
if self.speed < 5:
self.speed - self.speed
else:
self.speed -= 5
def honk_horn(self):
"""Prints a string to honk the horn of the model"""
return f"{self.model} goes 'beep beep'"
my_car = Car("ford", 1985, 4)
my_car.accelerate()
print(my_car.speed)
my_car = Car("Zastava", 2001, 30)
my_car.accelerate()
my_car.accelerate()
my_car.brake()
print(my_car.speed)
my_car = Car("Rust bucket", 1987)
print(my_car.honk_horn()) | true |
b89120664ad0478f506096dd4b09f80c097eab25 | MH10000/Python_Labs | /python_fundamentals-master/03_more_datatypes/2_lists/03_09_flatten.py | 598 | 4.5 | 4 | '''
Write a script that "flattens" a shallow list. For example:
starting_list = [[1, 2, 3, 4], [5, 6], [7, 8, 9]]
flattened_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Note that your input list only contains one level of nested lists.
This is called a "shallow list".
CHALLENGE: Do some research online and find a solution that works
to flatten a list of any depth. Can you understand the code used?
'''
starting_list = [[1, 2, 3, 4], [5, 6], [7, 8, 9]]
# Create a new list
new_list = []
# Append items to new list
for a in starting_list:
for b in a:
new_list.append(b)
print(new_list)
| true |
dc8be9e0b8a9ec73f38c739babc3e785074714bc | MH10000/Python_Labs | /python_fundamentals-master/07_classes_objects_methods/07_03_freeform.py | 2,152 | 4.6875 | 5 | '''
- Write a script with three classes that model everyday objects.
- Each class should have an __init__ method that sets at least three attributes
- Include a __str__ method in each class that prints out the attributes
in a nicely formatted string.
- Overload the __add__ method in one of the classes so that it's possible
to add attributes of two instances of that class using the + operator.
- Create at least two instances of each class.
- Once the objects are created, change some of their attribute values.
Be creative. Have some fun. :)
Using objects you can model anything you want.
Cars, animals, card games, sports teams, trees, people etc...
'''
class Product():
def __init__(self, name, quantity=0, price=0):
self.name = name
self.quantity = quantity
self.price = price
def __add__(self, other):
return self.quantity + other.quantity, self.price + other.price
def __str__(self):
return f"{self.quantity} of {self.name} is in stock and cost is USD {self.price}"
class Shelf():
def __init__(self, location, length, color):
self.location = location
self.length = length
self.color = color
def __str__(self):
return f"This {self.color} shelf is in the {self.location} section and is {self.length}cm long"
class Food():
def __init__(self, description, carb_content, protein_content, fat_content):
self.description = description
self.carb_content = carb_content
self.protein_content = protein_content
self.fat_content = fat_content
def __str__(self):
return f"This {self.description} has {self.carb_content}g carbs, {self.protein_content}g protein and {self.fat_content}g fat"
toothpaste = Product("toothpaste", 10, 2)
toothbrush = Product("toothbrush", 8, 3)
shelf1 = Shelf("upper", 50, "red")
shelf2 = Shelf("lower", 100, "blue")
steak = Food("sirloin steak", 2, 30, 15)
bread = Food("wholewheat bread", 25, 3, 1)
toothpaste.quantity = 15
shelf1.color = "white"
dental_prod_total = toothpaste + toothbrush
print(toothpaste.quantity)
print(shelf1.color)
print(dental_prod_total) | true |
173d68cf1479c4f01d8e4cd8f3a9f2e60916fe79 | wuna0835/testDemo | /snake.py | 920 | 4.125 | 4 | how_many_snakes = 1
snake_string = """
Welcome to Python3!
____
/ . .\\
\ ---<
\ /
__________/ /
-=:___________/
<3, Juno
"""
print(snake_string * how_many_snakes)
print(snake_string * how_many_snakes)
def create_groups(items, num_groups):
try:
size = len(items) // num_groups
except ZeroDivisionError:
print("WARNING: Returning empty list. Please use a nonzero number.")
return []
else:
groups = []
for i in range(0, len(items), size):
groups.append(items[i:i + size])
return groups
finally:
print("{} groups returned.".format(num_groups))
print("Creating 6 groups...")
for group in create_groups(range(32), 6):
print(list(group))
print("\nCreating 0 groups...")
for group in create_groups(range(32), 0):
print(list(group)) | false |
c9f7d73ad4051d0157643b02d69a8d8ac2878333 | sgibb1/project1_4 | /house.py | 1,104 | 4.34375 | 4 | # all inputs are taken in try block to handle invalid inputs
try:
bathrooms = int(input("Enter number of bathrooms: "))
bedrooms = int(input("Enter number of bedrooms: "))
chairs = int(input("Enter number of chairs: "))
sofas = int(input("Enter number of sofas: "))
table = int(input("Enter number of tables: "))
distance = int(input("Enter distance from college: "))
# handling invalid inputs
except: # catching all types of errors , ValueError can also be used specifically
# if user inputs invalid print Nope
print("NOPE!")
# if all inputs are valid then check if house is good or bad
else:
# if house have 3 bathrooms, 4 bedrooms and less than 10 miles from college
if bathrooms >= 3 and bedrooms >= 4 and distance <= 10:
# and if 2 ~ 4 chairs and have a table OR have a sofa then print 'good'
if (2 <= chairs <= 4 and table > 0) or (sofas > 0):
# NOTE: This message can be changed
print("Good!")
# else print 'bad'
else:
print("Bad!")
# else print 'bad'
else:
print("Bad!")
| true |
f8f334ea72228c0a2649f270203de894168790c2 | czamoral2021/CEBD-1100-CODE-WINTER-2021 | /Class03/add_numbers_2.py | 506 | 4.3125 | 4 | # Keep asking the user for a number (integer)
# keep track of the SUM of the numbers added
# When the user enters "-1" then stop and print the sum of all numbers entered
sum_of_numbers = 0
entered_value = ""
while True:
entered_value = int(input("enter a number >"))
if entered_value == -1:
break
else:
sum_of_numbers += entered_value
print(f"The sum of the numbers is {sum_of_numbers}")
# print("The sum of the numbers is {sum_of_numbers}") really bad sentence, no format
| true |
8655493b03349a6d830b4054d5d45047f5f0d47d | czamoral2021/CEBD-1100-CODE-WINTER-2021 | /Class04/range_function.py | 252 | 4.3125 | 4 | print(range(5,10))
print(list(range(5,10)))
# range()
# "string"
# [1,2,3]
# In what situations would you use FOR or a WHILE?
# FOR
# WHEN YOU HAVE A PRE-DEFINED START AND END. (KNOW IT ALREADY).
# WHILE
# WHEN YOU DO NOT KNOW WHEN IT ENDS....
| true |
6724ef3e3fabbda4356785a404964b86fb6f14f1 | czamoral2021/CEBD-1100-CODE-WINTER-2021 | /CZ_Exercises_class03/Ex_n4_class03.py | 1,315 | 4.53125 | 5 | # Restaurant Seating: Write a program that asks the user how many people are
# in their dinner group. If the answer is more than eight, print a message saying
# they’ll have to wait for a table. Otherwise, report that their table is ready.
# b. Ex_n4_class03
from string import digits
# initialize variables
num_of_users = 0
v_stay = True
# text = 'text%'
#
# from string import ascii_letters, digits
#
# if set(text).difference(ascii_letters + digits):
# print('Text has special characters.')
# else:
# print("Text hasn't special characters.")
while v_stay:
num_of_users = input("How many people are in the dinner group, number please?>")
if num_of_users == -1:
print("You are not sure to eat in this restaurant")
v_stay = False
if str(num_of_users).isalpha() or set(str(num_of_users)).difference(digits):
print("number of users is not an integer number")
# if str(num_of_users).isalpha() or not str(num_of_users).isnumeric():
# print("number of users is not an integer number")
else:
if (int(num_of_users) <= 8) and (int(num_of_users) > 0):
print(f"Your table is ready for {num_of_users} users")
v_stay = False
elif int(num_of_users) > 8:
print("We do not have a table for more than 8 users")
| true |
a47f69cf1d92778d9a81b376996e43403c46e46b | czamoral2021/CEBD-1100-CODE-WINTER-2021 | /Class04/list.py | 614 | 4.125 | 4 | # empty list
# colours = []
# colours = ["red", "green", "blue", "yellow"]
#
# prime_numbers = [2,3,5,7,9,11,19]
# change the list after it's created.
# print(colours[1])
# 1 -> green
# Iterate over the list
# enumerate over the list
# for c in colours:
# print(c)
# Every student has 2 grades available. A midterm grade and a final grade.
# These grades must be grouped together
grades = [70, 72, 80, 81, 66, 67]
grades_better = [
[70,72],
[80,81],
[66,67]]
for s in grades_better:
grade_midterm = s[0]
grade_final = s[1]
av = (grade_midterm + grade_final) / 2
print(av)
| true |
fd5ff74fd9fe634be3354955e6a9c8d664b098e1 | czamoral2021/CEBD-1100-CODE-WINTER-2021 | /CZ_Homework_Challenge/HomeWork_FizzBuzz.py | 1,701 | 4.34375 | 4 | # Homework Challenge: FizzBuzz
# Print a list of numbers from 0 to 25, including 25.
# If the number is divisible by 3, print the number and "Fizz".
# If the number is divisible by 5, print the number and "Buzz".
# If the number is divisible by both, print the number and "FizzBuzz“
# If the number is divisible by neither, print just the number.
# Separate the number and "FizzBuzz" by a TAB character.
# Note, this is a commonly asked question at job interviews.
# The goal, rather than just making it work, is to try to write it as clearly and efficiently as possible.
# FizzBuzz Output
#
# 00: FizzBuzz
# 01:
# 02:
# 03: Fizz
# .
# 15: FizzBuzz
# .
# 25: Buzz
# initialize variables
v_len = 0
for x in range(26):
v_len = len(str(x))
if x == 26:
break
elif (int(x) % 3 == 0) and (int(x) % 5 != 0):
# the number is divisible by 3 but not by 5
if v_len == 1:
print("0" + str(x) + ":\t Fizz")
else:
print(str(x) + ":\t Fizz")
elif (int(x) % 3 != 0) and (int(x) % 5 == 0):
# the number is divisible by 5 but not by 3
if v_len == 1:
print("0" + str(x) + ":\t Buzz")
else:
print(str(x) + ":\t Buzz")
elif (int(x) % 5 == 0) and (int(x) % 3 == 0):
# the number is divisible by 3 and 5
if v_len == 1:
print("0" + str(x) + ":\t FizzBuzz")
else:
print(str(x) + ":\t FizzBuzz")
else:
if (int(x) % 5 != 0) and (int(x) % 3 != 0):
# the number is not divisible by 3 and 5
if v_len == 1:
print("0" + str(x) + ":\t")
else:
print(str(x) + ":\t")
# End program | true |
8e3ce10eee6e0656c5955c2a75f2bd2e7415a13a | rajanmahato/n-th_monsien_number | /monsien_number.py | 1,030 | 4.15625 | 4 | import random
'''
find the n-th Monisen number.
A number M is a Monisen number if M=2**P-1
and both M and P are prime numbers.
For example, if P=5, M=2**P-1=31,
5 and 31 are both prime numbers,
so 31 is a Monisen number.
Put the 6-th Monisen number into a
single text file and submit online.
n = input("enter the nth prime ")
number=10
p=2
while p <int(n):
if all(number % i != 0 for i in range(2, number)):
p = p+1
number = number+1
m=2**p-1
print("6TH prime number: ",number-1,"and the monisen number is: ", m)
d=[i+1 for i in range(10) if i%2==0]
print(d)
sumA=0
i=1
while True:
sumA +=i
i+=1
if sumA>10:
break
print('i={}, sum={}'.format(i,sumA))
i = 1
while(i % 3):
print(i, end = ' ')
if (i >= 10):
break
i += 1
'''
def foo(num,base):
if(num >= base):
foo(num // base , base)
print(num%base, end = ' ')
numA = int(input())
numB = int(input())
foo(numA, numB)
| false |
7fb426f6eadef823327f76aad05ae5c923d2738c | CalJansen/PythonCalculator | /Calculator.py | 355 | 4.3125 | 4 |
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Enter operation: +, -, *, /")
if operation == "+":
print(num1 + num2)
elif operation == "-":
print(num1 - num2)
elif operation == "*":
print(num1 * num2)
elif operation == "/":
print(num1 / num2)
else:
print("Invalid input")
| false |
23a91ef823bf28eb8afd08b696d17b27c20fff30 | surajpmohan/python | /Python/SequentialSearch.py | 427 | 4.21875 | 4 | def search(array, value):
for item in array:
if item == value:
return item;
return False
n = int(input("Enter the array size: "))
array = [];
print("Enter the elements:")
for i in range(n):
num = input()
array.append(object)
value = input("Enter item for search:")
present = search(array, value)
if present:
print("Item is found.")
else:
print("Item is not found.") | true |
3fbd68fa9d27492b544f6836c1a540fcac72a25f | malachyo/BFS | /ceaseoarchipher.py | 2,606 | 4.34375 | 4 | alphabet = "abcdefghijklmnopqrstuvwxyz"
numbers = "1234567890"
def encrypt():
outputMsg = "" # space for encrypted message
inputMsg = input("Input message to encrypt.\n") # input for message to be encrypted
for character in inputMsg:
for num in numbers:
if character == num: # checks input message only contains letters
print("Message must only contain letters.")
exit()
shiftBy = input("Input number of letters to shift by.\n") # input for shift down the alphabet each letter will be
for character in shiftBy:
if character.isalpha():
print("Must be integer value to encrypt.") # checks shift value doesn't contains letters
exit()
shiftBy = int(shiftBy) # converts shift value to integer
for letter in inputMsg:
pos = alphabet.index(letter) # sets position of each letter in inputted message to its index value
pos2 = (pos + shiftBy) % 26 # sets new position to original position added to shift value, ensures loops back after 26 letters in alphabet
letter2 = alphabet[pos2] # creates new letter set to the new position after shift
outputMsg += letter2 # encrypted message is all shifted letters combined.
print("Your encrypted message is", outputMsg) # outputs encrypted message
def decrypt():
outputMsg = ""
inputMsg = input("Input message to decrypt.\n")
for character in inputMsg:
for num in numbers:
if character == num:
print("Message must only contain letters.")
exit()
shiftBy = input("Input given key shift value.\n")
for character in shiftBy:
if character.isalpha():
print("Must be integer value to encrypt.")
exit()
shiftBy = int(shiftBy)
for letter in inputMsg:
pos = alphabet.index(letter)
pos2 = (pos - shiftBy) % 26 # subtracts shift from position this time to return encrypted letters back to original
letter2 = alphabet[pos2]
outputMsg += letter2
print("Your decrypted message is", outputMsg) # outputs decrypted message
userChoice = input("Would you like to encrypt or decrypt a message?\n")
# taking in users decision of whether to encrypt or decrypt
if userChoice == "encrypt":
encrypt() # execute encrypt function
elif userChoice == "decrypt":
decrypt() # execute decrypt function
else:
print("Must choose either 'encrypt' or 'decrypt'") # in case input is neither, end program
exit()
| true |
5b6fe2b9367cf9f86a33687c2b59b4abe4acaeb2 | sandordargo/ordinalizer | /ordinalizer/ordinalizer.py | 1,317 | 4.1875 | 4 | """
This module is responsible for turning your cardinal inputs into their ordinal representations
"""
class NonOrdinalizableException(Exception):
"""
Should be raised when the input cannot be turned into an ordinal
"""
pass
def ordinalize(cardinal):
"""
Ordinalizes the input number. If a non-integer input is give, exception is raised.
:param cardinal: an integer is expected
:raise: NonOrdinalizableException if input is not an integer
:return: The ordinal string for the given cardinal number
"""
if is_not_a_non_negative_integer(cardinal) and is_not_a_non_negative_numeric_string(cardinal):
raise NonOrdinalizableException("{} is not a non-negative int".format(cardinal))
cardinal = str(cardinal)
if cardinal.endswith("1") and not cardinal.endswith("11"):
cardinal += "st"
elif cardinal.endswith("2") and not cardinal.endswith("12"):
cardinal += "nd"
elif cardinal.endswith("3") and not cardinal.endswith("13"):
cardinal += "rd"
else:
cardinal += "th"
return cardinal
def is_not_a_non_negative_integer(candidate):
return not isinstance(candidate, int) or candidate < 0
def is_not_a_non_negative_numeric_string(candidate):
return not (isinstance(candidate, str) and candidate.isdigit())
| true |
6f93cfebf302ddea9d6e0aee48d62aff034117a3 | dvarkless/simple-projects | /prime_factorization.py | 1,655 | 4.34375 | 4 | """
This is a solution for karan/Projects
"Prime Factorization"
This script returns all prime factors of a positive integer
Algorithm used in get_prime is wheel factorization
it saves quite a lot of time
"""
def get_prime(number):
if number % 2 == 0:
return 2
if number % 3 == 0:
return 3
if number % 5 == 0:
return 5
k = 7
i = 0
increment = [4, 2, 4, 2, 4, 6, 2, 6]
# 7, 11, 13, 17, 19, 23, 29, 31, 37... script assignes k to this values, not all this numbers are primes, but most of them
while k*k <= number: # if number is less than k*k, it is 100% prime
if number % k == 0:
return k
k = k + increment[i]
i = i + 1
if i > 7:
i = 0
return int(number)
def print_all_primes(number):
print("\n----------------------")
print(1)
n = abs(number)
while n != 1:
divisor = get_prime(n)
n = n/get_prime(n)
if divisor != 1:
print(divisor)
print("----------------------\n")
def main():
print("\n---Prime Factorization program---")
print("type in any positive integer to find all its prime factors")
print("type (q) to quit")
while True:
print(">>> ", end='')
ans = input()
if ans == "q":
break
if not ans.isdigit():
print("Please type an integer")
continue
ans = int(ans)
print_all_primes(ans)
print("type in any positive integer to find all its prime factors")
print("type (q) to quit")
if __name__ == '__main__':
main()
| true |
e3fad1dbf1d954742a58625801040419db82cd8f | bwz3891923/LearningLog | /前8章/7.(4,5,6,7,8,9,10).py | 2,942 | 4.15625 | 4 |
def pizza(): #7.4
materials=[]
confirm=True
while confirm:
material=input("please write down material('quit' to end):")
if material=='quit':
confirm=False
continue
materials.append(material)
print("we will add :")
for _material in materials:
print(_material)
def movie(): #7.5
while True:
age=input("show your age:")
if age=='quit':
break
age=int(age)
if age <=3:
print("it's free")
elif 3 < age <=12:
print("It takes 10$")
elif 12<age:
print("It takes 15$")
def whiletrue(): #7.7
while True:
i=1
def sandwich():
sandwich_order=['tuna','lemon','bread','egg'] #7.8
finished_sandwiches=[]
while True:
material=sandwich_order.pop()
print("I have made your {} sandwich".format(material))
finished_sandwiches.append(material)
print(sandwich_order)
if sandwich_order==[]:
print("we have finish:")
for finished_sandwich in finished_sandwiches:
print(str(finished_sandwich)+" sandwich")
break
def pastrami(): #7.9
sandwich_order=['pastrami','tuna','pastrami','lemon','bread','egg','pastrami','pastrami']
print("we have sell-out partrami")
while 'pastrami' in sandwich_order:
sandwich_order.remove('pastrami')
print(sandwich_order)
print(sandwich_order)
def vocation(): #7.10
vocations={}
while True:
name=input("what's your name")
vocation=input("a place that you want to go :")
vocations[name]=vocation
continue_=input("continue?")
if continue_=='no':
break
for name,vocation in vocations.items():
print( name+" want to go to "+vocation)
def mountain_poll(): #7.3.3
responses={}
polling_active=1
while polling_active:
name=input("\nWhat is your name")
response=input("Which mountain would you like to climb?")
responses[name]=response
repeat=input("would you like to let another person respond?(yes/no)")
if repeat=='no':
polling_active=False
print("\n---result---")
for name,response in responses.items():
print(name + " "+response)
while True:
use=input("input a function:")
if use=='1':
pizza()
if use=='2':
movie()
if use=='3':
whiletrue()
print("you got into a dead cycle")
if use=='4':
sandwich()
if use=='5':
pastrami()
if use=='6':
vocation()
if use=='7':
mountain_poll()
| true |
0986058aa7399524593720f638929c4e0f786dfd | AndreaJuarez/Estructuras-de-datos | /ARREGLOS/practica4(version2).py | 1,992 | 4.375 | 4 | print("PRACTICA 4: OBTENCIÓN DE DIAGONAL DE UNA MATRIZ CUADRADA")
print("---------------------------------------------------------")
#INSERCION DE NUMERO DE FILA Y COLUMNA
fila=int(input("INTRODUCE EL NUMERO DE FILAS: "))
columna=int(input("INTRODUCE EL NUMERO DE COLUMNAS: "))
array=[]
#VALIDACION DE MATRIZ CUADRADA
while True:
if fila != columna or columna != fila:
print("LA MATRIZ DEBE SER CUADRADA, INGRESE LOS VALORES DE NUEVO")
print("---------------------------------------------------------")
fila=int(input("INTRODUCE EL NUMERO DE FILAS: "))
columna=int(input("INTRODUCE EL NUMERO DE COLUMNAS: "))
else:
break
#FORMATO DE LA MATRIZ
for m in range(fila):
array.append([0]*columna)
print("EL FORMATO SERÁ:")
for a in array:
print(a)
#INSERCION DE DATOS
print("--------- INTRODUCE LOS ELEMENTOS DE LA MATRIZ ---------")
for f in range(0,fila):
for c in range(0,columna):
array[f][c]=input("ELEMENTO A INGRESAR EN LA POSICION " + str(f) + (",") + str(c) + ": ")
for a in array:
print(a)
#OBTENCION DE DIAGONAL DE LA MATRIZ
#----------------------------MANERA EN QUE LA MISS EXPLICO COMO SE HACE------------------------------
array2=[] #Declaracion del otro array para imprimir el array unidimensional resultante
for f in range(fila): #Mediante un ciclo for, se repetira hasta el numero de filas
for c in range(columna): #Mediante un ciclo for, se repetira hasta el numero de columnas
if c ==f: #Condicion para evaluar si la fila y columna es igual, se ira agregando el valor al otro vector
array2.append(array[f][c]) #Se agregara en el array 2, lo que encuentre en el array uno y que esta evaluando en los for
print("LA DIAGONAL ES:")
print(array2)
#Como para sacar la diagonal se imprimiran los valores que esten en posiciones iguales,
# por eso se evalua con el if | false |
f9327bf9588d8829388f4d7e77593e19791e7f0e | AndreaJuarez/Estructuras-de-datos | /ARREGLOS/ejemplo.py | 989 | 4.375 | 4 | # encoding: utf-8
print("PRACTICA 3: INSERCION Y BUSQUEDA EN ARREGLO BIDIMENSIONAL")
print("---------------------------------------------------------")
#INSERCION DE NUMERO DE FILA Y COLUMNA
fila=int(input("INTRODUCE EL NUMERO DE FILAS: "))
columna=int(input("INTRODUCE EL NUMERO DE COLUMNAS: "))
array=[]
for i in range(fila):
array.append([0]*columna)
#print(array)
#INSERCION DE ELEMENTOS
print("--------- INTRODUCE LOS ELEMENTOS DE LA MATRIZ ---------")
for f in range(0,fila):
for c in range(0,columna):
array[f][c]=input("ELEMENTO A INGRESAR EN LA POSICION " + str(f) + (",") + str(c) + ": ")
print(array)
#BUSQUEDA DE ELEMENTOS
print("------------ BUSCAR DE ELEMENTO POR POSICION -----------")
busquedafila=int(input("INGRESE EL NUMERO DE FILA: "))
busquedacolumna=int(input("INGRESE EL NUMERO DE COLUMNA: "))
if busquedafila <= fila:
if busquedacolumna <= columna:
print("EL ELEMENTO SE ENCUENTRA EN: " )
| false |
35f7fb676dd9ab70cc8f86fc40bec940f48db2a0 | YashK1299/LeetCode | /Evaluate Reverse Polish Notation.py | 1,923 | 4.125 | 4 | """
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, and /. Each operand may be an integer or another expression.
Note that division between two integers should truncate toward zero.
It is guaranteed that the given RPN expression is always valid.
That means the expression would always evaluate to a result, and there will not be any division by zero operation.
Example 1:
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
Constraints:
1 <= tokens.length <= 10^4
tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].
"""
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
"""
Using Stacks:
T(n) = O(n)
S(n) = O(n)
"""
stack = []
op = "+-*/"
for i in tokens:
# print(stack)
if i in op:
val1 = stack.pop()
val2 = stack.pop()
if i == "+":
stack.append(val1 + val2)
elif i == "-":
stack.append(val2 - val1)
elif i == "*":
stack.append(val1 * val2)
else:
stack.append(int(val2 / val1))
else:
stack.append(int(i))
return stack[-1]
| true |
b199a6a5752a443e8326c092f1989612f1137900 | YashK1299/LeetCode | /Decode String.py | 2,895 | 4.125 | 4 | """
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is
being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits
are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
Example 1:
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Example 2:
Input: s = "3[a2[c]]"
Output: "accaccacc"
Example 3:
Input: s = "2[abc]3[cd]ef"
Output: "abcabccdcdcdef"
Example 4:
Input: s = "abc3[cd]xyz"
Output: "abccdcdcdxyz"
Constraints:
1 <= s.length <= 30
s consists of lowercase English letters, digits, and square brackets '[]'.
s is guaranteed to be a valid input.
All the integers in s are in the range [1, 300].
"""
class Solution:
# def decodeString(self, s: str) -> str:
# def dfs(i):
# string = ""
# num = ""
# while i < len(s):
# if s[i].isnumeric():
# num = num + s[i]
# i += 1
# elif s[i] == '[':
# temp, i = dfs(i+1)
# string += temp * int(num)
# num = ""
# elif s[i] == ']':
# return (string, i+1)
# else:
# string += s[i]
# i += 1
# return string
# return dfs(0)
def decodeString(self, s: str) -> str:
stack = []
res = ""
num = ""
for i in s:
if i.isdigit():
num += i
elif i == '[':
stack.append([res, num])
num, res = "", ""
# res = ""
elif i == ']':
prevs, prevn = stack.pop()
res = prevs + res * int(prevn)
else:
res += i
return res
# def decodeString(self, s: str) -> str:
# stack = []
# for i in s:
# if i == ']':
# res = ""
# while stack:
# temp = stack.pop()
# if temp == '[':
# break
# res = temp + res
# num = ''
# while stack and stack[-1].isdigit():
# num = stack.pop() + num
# stack.append(res*int(num))
# else:
# stack.append(i)
# return ''.join(stack)
| true |
06d21fc8b91efb6d5c52ccb7876307c4762449b0 | SDSS-Computing-Studies/009-basic-gui | /example4.py | 1,369 | 4.4375 | 4 | #!python3
import tkinter as tk
from tkinter import *
#importing ttk is required to use the tkinter.place() method
from tkinter import ttk
"""
The 3rd method of placing widgets is to treat the window as a map with x and y
coordinates, and then place the widget based on the location from the top left
corner of the window. Distances are measured in pixels
"""
window = tk.Tk()
window.title("Hi!")
window.geometry("200x400")
label1 = tk.Label(window,text="Text that does\nnothing is a label", bg="#ee0000")
dogphoto = PhotoImage(file="dog.png")
label2 = tk.Label(window, image=dogphoto)
lable3 = tk.Label(window, text="Note that an image can be in a label or a button!", borderwidth=4, relief=SUNKEN)
button1 = tk.Button(window,text="A button\nis clickable")
entry1 = tk.Entry(window,text="Entry widgets can be typed in", borderwidth=3, relief=SUNKEN)
combo = ttk.Combobox(window,values=["1","2","3"])
# we can use the tkiner.place() command to fix the position of a widget.
# further options available can be found at https://www.tutorialspoint.com/python/tk_place.htm
label2.place(x=0,y=0)
button1.place(x=100,y=50)
label1.place(x=50,y=60)
#Note, widgets can overlap. In that case, the order is determined by when
#widget object was CREATED,not when it was placed.
#Objects created earlier are underneath objects that are created later.
window.mainloop() | true |
0b278e8971bd516ba57e29eb3d5fab385c292d6d | wudeni/easy-python-string-projects | /reverse_a_string.py | 249 | 4.46875 | 4 | #Enter a string & this python program will reverse it and print it
name = input('Enter your Name:- ')
lst = list()
for char in name:
lst.append(char)
delimiter = ''
lst = delimiter.join(lst[::-1]).title()
print('Your alien name is :', lst)
| true |
06d4457cdd911e0847ba9d8d76f31b8725bf44d6 | hieubz/Crack_Coding_Interview | /sorting_argorithms/quick_sort.py | 2,100 | 4.125 | 4 | def partition_last(arr, low, high):
"""
divide the arr to 2 parts
:param arr:
:param low:
:param high:
:return: pivot
"""
# temp index
temp = low - 1
# choose the last one as the pivot
pivot = arr[high] # arr[low]
for j in range(low, high):
if arr[j] <= pivot:
# assign index of number (larger than pivot) to temp
temp += 1
# swap arr[j] with that larger number
# intend to move the smaller number to the left side and vise versa
arr[temp], arr[j] = arr[j], arr[temp]
# insert pivot number to the middle
arr[temp + 1], arr[high] = arr[high], arr[temp + 1]
# return pivot index
return temp + 1
def partition_start(arr, start, end):
i = start + 1
pivot = arr[start]
for j in range(start + 1, end + 1):
if arr[j] < pivot:
arr[i], arr[j] = arr[j], arr[i]
i += 1
# insert pivot element to the middle of two parts
arr[start], arr[i - 1] = arr[i - 1], arr[start]
return i - 1
def partition_middle(arr, low, high):
"""
divide the arr to 2 parts
:param arr:
:param low:
:param high:
:return: pivot
"""
# choose the last one as the pivot
pivot = arr[(low + high) // 2]
while low <= high:
while arr[low] < pivot:
low += 1
while arr[high] > pivot:
high -= 1
if low <= high:
arr[low], arr[high] = arr[high], arr[low]
low += 1
high -= 1
return low
def quick_sort(arr, low, high):
"""
:param arr: array to be sorted
:param low: starting index
:param high: ending index
:return:
"""
if len(arr) == 1:
return arr
if low < high:
pi = partition_last(arr, low, high)
if low < pi - 1:
quick_sort(arr, low, pi - 1)
if pi < high:
quick_sort(arr, pi + 1, high) # when use partition_middle: quick_sort(arr, pi, high)
return arr
a = [1, 2, 3, 5, 3, 12, 4]
print(quick_sort(a, 0, len(a) - 1))
| true |
33fd341dc31b4afb7c4c1e63094949c5d0e61299 | hieubz/Crack_Coding_Interview | /OO_designs/OOP/syntaxes/global_var.py | 739 | 4.5 | 4 | """
when we create a variable inside a function, it is local by default
when we define a variable outside of a function, it is global by default
we use global keyword to read and write a global var inside a function
"""
x = "awesome"
def my_func():
print("Python is " + x)
# if you create a variable with the same name inside a function => will be local, use only inside that function
# the global variable with the same name will remain as it was - global and with the original value
"""
to create a global variable inside a function, you can use global keyword
if you want to change the value of global variable, you can use global keyword
"""
x = "awesome"
def my_func_2():
global x
x = "fantastic"
my_func_2()
| true |
790bfc02b7249ce71e6e133b92355074a88c2bb9 | hieubz/Crack_Coding_Interview | /leetcode_2/easy/some_code_pieces.py | 1,978 | 4.28125 | 4 | # 1. reverse a string or list
my_str = "ABCDE"
reversed_str = my_str[::-1]
print(reversed_str)
# 2. uppercase with the first character of each word
my_str = "what the fuck"
print(my_str.title())
# 3. find all characters in a string
print(''.join(set("ajdjdjfjjdfaklh")))
# 4. print a string or list n times
n = 3
my_str = "abcd"
l = [1, 2, 3]
print(my_str * n)
print(l * 3)
# 5. exchange the values between 2 variables
a, b = 1, 3
a, b = b, a
print(a, b)
# 6. check a symmetry string
my_str = "abcba"
print(my_str == my_str[::-1])
# 7. count the numbers of occurrences
from collections import Counter
my_list = [1, 2, 3, 4, 5, 3, 4]
count = Counter(my_list)
print(count.most_common(1))
print(count[3])
# 8. check elements difference between 2 string
a = 'abc2'
b = '2acb'
count1 = Counter(a)
count2 = Counter(b)
print(count1 == count2)
# 9. try - except - else
a, b = 1, 0
try:
print(a / b)
except ZeroDivisionError as e:
print(e)
else:
print("fucking awesome")
finally:
# close connection, release resource, ...
print("end!")
# 10. enumerate to have index + value pairs
my_arr = [1, 2, 3, 4, 5]
for i, value in enumerate(my_arr):
print(i, value)
# 11. check size of object
import sys
num = 20
print(sys.getsizeof(num), "bytes")
# 12. combine 2 dicts
dict_1 = {'apple': 9, 'banana': 6}
dict_2 = {'banana': 4, 'orange': 8}
combined_dict = {**dict_1, **dict_2}
print(combined_dict)
for k, v in combined_dict.items():
if k in dict_1 and k in dict_2:
combined_dict[k] = [v, dict_1[k]]
print(combined_dict)
# 13. flattening the list
l = [[1, 2], [3, 4, 5]]
flatten_list = [ele for sublist in l for ele in sublist]
# 14. get a sample from a list
import random
my_list = [1, 2, 4, 6, 8]
num_samples = 2
samples = random.sample(my_list, num_samples)
print(samples)
# 15. map an integer to a list of numbers
num = 123456
list_of_digits = list(map(int, str(num)))
print(list_of_digits)
list_of_digits = [int(x) for x in str(num)]
| true |
335859afa07bcbf4d0608b1f9e865c356416dc47 | hieubz/Crack_Coding_Interview | /OO_designs/OOP/syntaxes/multiple_inheritance.py | 2,380 | 4.15625 | 4 | # class Contact:
# # class variable / class attribute
# all_contacts = []
#
# def __init__(self, name, email):
# # when initiate the instance of class
# # => assign value of input params to instance variables
# self.name = name
# self.email = email
# Contact.all_contacts.append(self)
#
#
# # Mixin
# class MailSender:
# def send_email(self, message):
# print(self.email)
#
#
# def send_email(message, param):
# print(message, param)
# # do smt
#
#
# """
# Mixin is complicate
# => we could have used single inheritance and added the send_email function to the subclass
# => we create a function only for sending an email
# """
#
#
# class EmailableContact(Contact, MailSender):
# pass
#
#
# e = EmailableContact("Hieu", "hieupd@gmail.com")
# e.send_email("fucking awesome")
#
# """
# we can work with multiple inheritance in python but it gets very messy when we have to call methods on the superclass
# because there are multiple super classes
#
# """
#
#
# class AddressHolder:
# def __init__(self, street, city, state, code):
# self.street = street
# self.city = city
# self.state = state
# self.code = code
#
#
# class Friend(Contact, AddressHolder):
# def __init__(self, name, email, phone, street, city, state, code):
# Contact.__init__(self, name, email)
# AddressHolder.__init__(self, street, city, state, code)
# self.phone = phone
"""
the above code can works but that's relatively harmless -
imagine trying to connect to a database twice for every request! disaster!!!
=> we can use super()....
"""
# solution: using kwargs for sets of arguments
class Contact:
all_contacts = []
def __init__(self, name="", email="", **kwargs):
print("contact")
super().__init__(**kwargs)
self.name = name
self.email = email
self.all_contacts.append(self)
class AddressHolder:
def __init__(self, street="", city="", state="", code="", **kwargs):
print("address")
super().__init__(**kwargs)
self.street = street
self.city = city
self.state = state
self.code = code
class Friend(Contact, AddressHolder):
def __init__(self, phone="", **kwargs):
super().__init__(**kwargs)
self.phone = phone
f = Friend()
print(f)
| true |
2bd045440326c2ee706d6b81bab17d95e959b1cf | hieubz/Crack_Coding_Interview | /leetcode_2/easy/third_largest_element.py | 479 | 4.4375 | 4 | """
given an array of n integers, find the third largest element
"""
def get_third_largest_ele(arr):
max1, max2, max3 = arr[0], arr[0], arr[0]
for num in arr:
if num > max1:
max3 = max2
max2 = max1
max1 = num
elif num > max2:
max3 = max2
max2 = num
elif num > max3:
max3 = num
return max3
arr = [2, 4, 5, 6, 8, 9, 10, 17]
num = get_third_largest_ele(arr)
print(num) | true |
48760bd973fc90de49eb1bab40f7ee5d411717a4 | aashiqms/python_data | /quadratic_equation.py | 558 | 4.15625 | 4 | def solve_quadratic(a, b, c):
"""
A function to solve quadratic equation
:return:
x value of the quadratic equation as pair of tuples
eg: print(solve_quadratic(1,-3,2))
(2.0,1.0)
print(solve_quadratic(1,2,1))
(-1.0,-1.0)
"""
# ax2+bx+c=0
y = (b ** 2) - (4 * a) * c
top_a = -b + (y ** 0.5)
top_b = -b - (y ** 0.5)
bottom = 2 * a
x_a = top_a / bottom
x_b = top_b / bottom
x_answer = (x_a, x_b)
return x_answer
print(solve_quadratic(1, -3, 2))
solve_quadratic(1, -3, 1)
| true |
1f3cca837f984c8197dd10f9f5c5c948b55f6bd7 | henrypj/codefights | /Intro/03-SmoothSailing/commonCharacterCount.py | 870 | 4.21875 | 4 | #!/bin/python3
import sys
"""
# Description
#
# Given two strings, find the number of common characters between them.
#
# Example:
#
# For s1 = "aabcc" and s2 = "adcaa", the output should be
# commonCharacterCount(s1, s2) = 3.
#
# Input Format
#
# string s1, A string consisting of lowercase latin letters a-z.
# 1 ≤ s1.length ≤ 15
#
# string s2, A string consisting of lowercase latin letters a-z.
# 1 ≤ s2.length ≤ 15
#
# Output Format
#
# Integer
#
# Solution:
"""
##############
# SOLUTION 1 #
##############
def commonCharacterCount(s1, s2):
commonCount = 0
commonChars = list(set(s1) & set(s2))
for i in range(len(commonChars)):
numS1 = s1.count(commonChars[i])
numS2 = s2.count(commonChars[i])
commonCount += min(numS1, numS2)
return commonCount
s1 = "aabcc"
s2 = "adcaa"
print(commonCharacterCount(s1, s2)) | true |
4284fc9d0717a6038e791849ac38938c02a2067e | henrypj/codefights | /Intro/03-SmoothSailing/sortByHeight.py | 1,100 | 4.15625 | 4 | #!/bin/python3
import sys
"""
# Description
#
# Some people are standing in a row in a park. There are trees between them
# which cannot be moved. Your task is to rearrange the people by their heights
# in a non-descending order without moving the trees.
#
# Example:
#
# For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be
# sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190].
#
# Input Format
#
# array.integer a
# If a[i] = -1, then the ith position is occupied by a tree. Otherwise a[i] is
# the height of a person standing in the ith position.
# 5 ≤ a.length ≤ 15
# -1 ≤ a[i] ≤ 200
#
# Output Format
#
# array.integer Sorted array a with all the trees untouched.
#
# Solution:
"""
##############
# SOLUTION 1 #
##############
def sortByHeight(a):
j = 0
heights = []
people = sorted(i for i in a if i >= 0)
for i in range(len(a)):
if a[i] == -1:
heights.append(a[i])
else:
heights.append(people[j])
j += 1
return heights
a = [-1, 150, 190, 170, -1, -1, 160, 180]
print(sortByHeight(a)) | true |
f3fb09f4c7e15a294714d49f22ed26606a177183 | henrypj/codefights | /Intro/12-LandOfLogic/longestWord.py | 1,001 | 4.1875 | 4 | #!/bin/python3
import sys
"""
# Description
#
# Define a word as a sequence of consecutive English letters. Find the longest
# word from the given string.
#
# Example
#
# For text = "Ready, steady, go!", the output should be
# longestWord(text) = "steady".
#
# Input/Output
#
# [input] string text
# Guaranteed constraints:
# 4 ≤ text.length ≤ 50.
#
# [output] string
# The longest word from text. It's guaranteed that there is a unique output.
#
# Solution:
"""
##############
# SOLUTION 1 #
##############
import re
def longestWord(text):
wordList = re.findall('[a-zA-Z]{1,}', text)
#maxLen = max(len(word) for word in wordList)
#maxLenWordList = [x for x in wordList if len(x) == maxLen]
return max(wordList, key=len)
print(longestWord("Ready, steady, go!")) # steady
print(longestWord("Ready[[[, steady, go!")) # steady
print(longestWord("ABCd")) # ABCd
print(longestWord("A!! AA[]z[BB")) # AA
| true |
ef962c4110100d457727c7ace0b818e522086f2b | henrypj/codefights | /Intro/06-RainsOfReason/alphabeticShift.py | 947 | 4.21875 | 4 | #!/bin/python3
import sys
"""
# Description
#
# Given a string, replace each its character by the next one in the English
# alphabet (z would be replaced by a).
#
# Example:
#
# For inputString = "crazy", the output should be
# alphabeticShift(inputString) = "dsbaz"
#
# Input Format
#
# string inputString
# Non-empty string consisting of lowercase English characters.
#
# Constraints
# 1 ≤ inputString.length ≤ 10
#
# Output Format
#
# string
# The result string after replacing all of its characters.
#
# Solution:
"""
##############
# SOLUTION 1 #
##############
def alphabeticShift(inputString):
shiftedString = ""
for i in range(len(inputString)):
if inputString[i] == "z":
shiftedString += chr(97)
else:
shiftedString += chr(ord(inputString[i]) + 1)
return shiftedString
print(alphabeticShift("crazy")) # dsbaz
print(alphabeticShift("z")) # a
| true |
aeccdc3087ab5240d0f7be4cb7d405e90dafe6cb | henrypj/codefights | /Intro/06-RainsOfReason/arrayReplace.py | 1,100 | 4.3125 | 4 | #!/bin/python3
import sys
"""
# Description
#
# Given an array of integers, replace all the occurrences of elemToReplace
# with substitutionElem.
#
# Example:
#
# For inputArray = [1, 2, 1], elemToReplace = 1 and substitutionElem = 3, the
# output should be
# arrayReplace(inputArray, elemToReplace, substitutionElem) = [3, 2, 3].
#
# Input Format
#
# array.integer inputArray
#
# Constraints
# 2 ≤ inputArray.length ≤ 10
# 0 ≤ inputArray[i] ≤ 10
#
# integer elemToReplace
#
# Constraints
# 0 ≤ elemToReplace ≤ 10
#
# integer substitutionElem
#
# Constraints
# 0 ≤ substitutionElem ≤ 10
#
# Output Format
#
# array.integer
#
# Solution:
# Wow, my first ever one line Python solution
"""
##############
# SOLUTION 1 #
##############
def arrayReplace(inputArray, elemToReplace, substitutionElem):
return([substitutionElem if item == elemToReplace else item for item in inputArray])
print(arrayReplace([1,2,1], 1, 3)) # [3,2,3]
print(arrayReplace([1,2,3,4,5], 3, 0)) # [1,2,0,4,5]
print(arrayReplace([1,1,1], 1, 10)) # [10,10,10]
| true |
0885a8a982b3b101b1148839bcfe52b3c83e1afc | HashirAKhan/CSCI-127 | /11. Shades of Blue.py | 283 | 4.21875 | 4 | #Name: Hashir Khan
#Date: September 27th, 2018
#This program creates a cone with different shades of blue
import turtle
turtle.colormode(255)
x = turtle.Turtle()
x.shape("turtle")
x.backward(100)
for i in range(0,255,10):
x.forward(10)
x.pensize(i)
x.color(0,0,i)
| true |
2f5fcae235e1562735fbac81b3c1fe9386777b2b | HashirAKhan/CSCI-127 | /12. Color by Hex.py | 204 | 4.21875 | 4 | #Name Hashir Khan
#Date September 28th, 2018
#This program changes color to the entered hex code
import turtle
turt = turtle.Turtle()
turt.shape("turtle")
x = input("Enter a hex code: ")
turt.color(x)
| true |
9147639361b6d1cdea0fc5f568597ddb2055fd7d | rbrashinkar/study | /Programing_study/python_lang/string_operation/replace_blank.python | 239 | 4.34375 | 4 | #!/usr/local/bin/python
#Python Program to Take in a String and Replace Every Blank Space with Hyphen
str1=raw_input("enter the string:")
str2=str1.replace(' ','_')
print("string is:")
print(str1)
print("Modified string is:")
print(str2)
| true |
9865dec24276370e4dc3975b465de111ecd4f03e | kdm357/HAFB-Python | /iteration_protocols.py | 756 | 4.59375 | 5 | """
Learn about iterable, iterator objects
use the built-in:
iter(): create and iterable object
next(): fetch the next element in the iterable object
"""
def first(iterable):
"""
return next member in list (if available)
:param iterable: object
:return: next member or
:except: ValueError for StopIteration
"""
iterator = iter(iterable)
try:
return next(iterator)
except StopIteration:
raise ValueError("iterable is empty")
def main():
"""
test function for words library
:return: nohing
"""
iterable = ["Sring","Summer","Fall","Winter"]
iterator = iter(iterable) # give me an iterator
print(type(iterator), iterator)
if __name__ == '__main__':
main()
exit(0) | true |
82fc29c3c6ba711f8d255d66962ecacb01f80bee | kdm357/HAFB-Python | /gen.py | 1,295 | 4.3125 | 4 | """
Module for demonstration the use of generator execution
"""
def take(count, iterable):
"""
take items frm the front of an iterable
:param count: maximum number of items to retrieve
:param iterable: the source series
:Yields: at most 'count' item fo r'iterator'
"""
counter = 0
for item in iterable:
if counter == count:
return
counter += 1
yield item
def run_take():
"""
Test the take() function
:return:
"""
items = [2,4,5,8,10]
for item in take(3, items):
print(item)
def run_pipeline():
items = [3,6,6,2,1,1]
for item in take(3,distinct(items)):
print(item)
def distinct(iterable):
"""
return unique item by eliminating duplicates
:param iterable: the source series
:yield: unique elements in order from iterable
"""
seen = set()
for item in iterable:
if item in seen:
continue
yield item
seen.add(item)
def run_distinct():
items = [5,7,7,6,5,5]
for item in distinct(items):
print(item)
def main():
"""
test function for words library
:return: nohing
"""
# run_take()
# run_distinct()
run_pipeline()
if __name__ == '__main__':
main()
exit(0) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.