blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f45f0ea56e2ab05a60c1b897cf1dc2076a13fd09 | noevazz/learning_python | /027_negative_indeces.py | 477 | 4.375 | 4 | # Negative indexes are legal
my_list = [4, 7, 10, 6]
print("List=", my_list)
# An element with an index equal to -1 is the last one in the list
print("[-1] index=", my_list[-1])
# The element with an index equal to -2 is the one before last in the list
print("[-2] index=", my_list[-2])
# We can also use the "del" insttruction to delete an element
print("List before deleting the [-2] index=", my_list)
del my_list[-2]
print("List after deleting the [-2] index=", my_list) | true |
0d5eaf303605eeec6370c7a1b1caf06ef909a248 | noevazz/learning_python | /105_polymorphism_and_virtual_methods.py | 434 | 4.375 | 4 | """
The situation in which the subclass is able to modify its superclass behavior
(just like in the example) is called polymorphism.
"""
class One:
def doit(self):
print("doit from One")
def doanything(self):
self.doit()
class Two(One):
def doit(self): # overrides the partent's: doit() is now a "virtual" method
print("doit from Two")
one = One()
two = Two()
one.doanything()
two.doanything() | true |
6116132b63fe41387440472cd5846af34a8ab792 | noevazz/learning_python | /045_recursion.py | 468 | 4.375 | 4 | # recursion is when you invoke a function inside the same function:
def factorialFun(n): # Factorial of N number is equal to N*(N-1)*(N-2) ... *(1)
if n < 0:
return None
if n < 2:
return 1
return n * factorialFun(n - 1)
print(factorialFun(3))
# Yes, there is a little risk indeed. If you forget to consider the conditions which
# can stop the chain of recursive invocations, the program may enter an infinite loop. You have to be careful. | true |
6a022528eb1b7cd8400e72293bc12805dcd6aaef | noevazz/learning_python | /021_while_loop.py | 1,988 | 4.25 | 4 | # loops allow us to execute code several times while a boolean expression is True or while we do not break the loop explicit
# while loop:
money = 0
fanta = 43
while money < fanta:
#save 11 dollar each day to buy a fanta
money += 11
print("I have", money, "dollars")
# there is also inifinite loops:
money_in_bank = 12
while True:
deposit = float(input("enter deposit: "))
money_in_bank += deposit
if money_in_bank > 100:
print("you already have more thatn 100 dollars")
break # break the loop right now
print("\nlet's go to the next exercise\n")
# loops can have an else estatement, it will execute its code at the end of the loop,
# but if the loop is broke (using break) the else code is not executed
control_loop = True
while control_loop:
option = input("you are in a loop, insert your option \n[break: exit using break, normal: exit normally]: ")
if option == "break":
print("Ok let's break the loop")
break # the else is not going to be executed
elif option == "normal":
print("Ok let's stop the loop normally")
control_loop = False # ends the loop normally, the else will be executed
else:
print("continuing...")
else:
print("Hi from the else statement")
print("\nLet's go to the next exercise:\n")
print(":D")
# Note: rember you can use the pass structure if you don't have a specific code to put inside a if/elif/else and also a while:
#while True:
#pass <-- but this will cause the program to be stuck doing nothing
# FINALLY: the continue structure
# The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.
number = 10
while number >= 0:
if number%2 == 0:
number -= 1
continue
print("I have a lot of code to execute but only if", number, "is an odd number, an yes it is")
number -= 1
else:
print("end of the loop")
| true |
58311959e0e85debd79c0aecdd11058d3ac97566 | noevazz/learning_python | /037_you_first_function.py | 903 | 4.4375 | 4 | # in order to use our own function we first need to define them:
def my_first_function():
print("Hello world, this is my first function")
# Now we can call (INVOCATION) our function:
my_first_function()
# remember the "pass" keyword that we saw when we were learning about loops, it can be used if you don't know what to execute:
def other():
pass
# of course if you call this function it will not do anything:
other() # but you can do it to start laying out your program
# Now you can call you function at any time:
my_first_function()
my_first_function()
my_first_function()
# NOTE tha you defined the function to not receive any argument,
# Passing an argument will cause an error because python knows that the functions is not expecting arguments
my_first_function(23, 43, "hello") # this will cause an error
# TypeError: my_first_function() takes 0 positional arguments but 3 were given | true |
2124475661e15275a16886dbb68fc430120db14b | shwetati199/Python-Beginner | /8_for_loop.py | 1,158 | 4.59375 | 5 | #For loop- it is used mostly to loop over a sequence
#It works more like iterator method
namelist=["Shweta","Riya", "Priya", "Supriya"]
print("Namelist: ")
for name in namelist:
print(name)
#For loop don't require indexing variable to get set.
#For loop over String
print("For loop for string")
for i in "Shweta":
print(i)
#Break Statemnets- this is used to break the innermost loop whenever the given condition is true
evennums=[2, 4, 6, 8, 9, 10, 12, 13, 15, 16]
#Ex- we want to only print even numbers from this list and if odd numbers encounter more than two time we have to Print that
# "2 Odds found" and need to break the loop
#Here we will use continue and break to do the given task.
oddcount=0
for i in evennums:
if i%2!=0:
oddcount+=1
if(oddcount==2):
print("2 Odds found")
break
continue
print(i)
#Nested for loops: we can have loop inside loop and this is called as nested for loop
# For example- if we want to print pattern we can use nested loop
for i in range(5):
for j in range(i+1):
print("*", end=" ")
print()
| true |
d2bfb582e28f444727b40bdc7869b9d585450325 | Squidjigg/pythonProjects | /wordCount.py | 318 | 4.125 | 4 | userInput = input(f"What is on your mind today? ")
# split each word into a list
wordList = userInput.split()
#print(wordList) # this is here for debugging only
# count the number of items in the list
wordCount = len(wordList)
print(f"That's great! You told me what is on your mind in {wordCount} words!") | true |
4b5d6378165bf91c01788357a803c0d3caa7f077 | tjkabambe/pythonBeginnerTutorial | /Turtle.py | 851 | 4.28125 | 4 | # Let's draw some drawings with the package turtle
# Import turtle
import turtle
# Lets get a setup in turtle
# 'bgcolor' is 'background color'
turtle.bgcolor("black")
turtle.pensize(2)
turtle.color("red")
turtle.speed(15)
# # Draw a square
# turtle.forward(50)
# turtle.left(90)
# turtle.forward(50)
# turtle.left(90)
# turtle.forward(50)
# turtle.left(90)
# turtle.forward(50)
# turtle.left(90)
# # turtle.done() # allows turtle to stay on the screen
# Nice graph in turtle
# for colors in ["red", "blue", "orange", "yellow", "green", "purple"]:
# turtle.color(colors)
# turtle.circle(150)
# turtle.left(60)
# turtle.done()
# to make it better
for i in range(6):
for colors in ["red", "blue", "orange", "yellow", "green", "purple"]:
turtle.color(colors)
turtle.circle(150)
turtle.left(50)
turtle.done()
| false |
4f81440511b981bb636bf62c7d24afc3aed9172b | tjkabambe/pythonBeginnerTutorial | /Quiz.py | 2,027 | 4.5 | 4 | # Quiz time
# Question 1: Assigning variables
# create 2 variables x and y where any number you want
# find sum of x and y, x divided by y, x minus y, x multiplied by y
x = 4
y = 3
print(x + y)
print(x - y)
print(x * y)
print(x / y)
# Question 2: Lists
# Create a list of all even numbers from 0 to 100
# Print first 10 elements and find the length of this list
# Append a value of your choice to the end of the list (It can be any type!)
mylist = list(range(0, 101, 2)) # Create the list
print(mylist[0:10]) # Print the first 10 elements
print(len(mylist)) # Print length of list
mylist.append(102) # Add element to list
print(mylist)
# Question 3
# Assign a variable to any integer you want
# using an if statement, find whether this integer is divisible by 5
# Get python to print whether it is or isn't
x = 19
if x % 5 == True:
print("x is divisible by 5")
else:
print("x is NOT divisible by 5")
# Question 4
# Using a for loop, get python to print the numbers 0 to 5
for i in range(6):
print(i)
# Question 5
# Draw a pentagon in turtle
import turtle
for i in range(5):
turtle.forward(150)
turtle.left(72)
turtle.done()
# Question 6
# Create a function that tests whether three number (a,b,c) are a pythagorean triple
# ie if a^2 + b^2 = c^2
def pythagorean(a, b, c):
if a ** 2 + b ** 2 == c ** 2:
return print("These 3 numbers are pythagorean triple.")
else:
return print("These 3 numbers are not a pythagorean triple.")
print(pythagorean(3, 4, 5)) # this is true
print(pythagorean(1, 4, 9)) # this is false
# Question 7
# Spot the error
n = 5
while n < 10:
n = n + 1
print(n)
# Question 8
# Create 2 lists (of size 5) and plot these lists against each other using matplotlib
import matplotlib.pyplot as plt
list2 = [1, 3, 5, 8, 11, 16, 22]
list3 = [2, 4, 6, 8, 10, 12, 14]
plt.plot(list2, list3, c="blue", linewidth=2, Label="lines", linestyle="dashed")
plt.xlabel("list2")
plt.ylabel("list3")
plt.title("Question 8 solution")
plt.legend
plt.show()
| true |
3d595b15d88d0e05bad1b86a5d21c9875aceced0 | gehoon/fun | /birthday.py | 1,138 | 4.25 | 4 | #!~/bin/python
## Simulation of the birthday paradox (https://en.wikipedia.org/wiki/Birthday_problem)
import random
## Each Birthdays class comprises n number of birthdays
class Birthdays:
def __init__(self, n=23): # initialization
self.birthday = []
for x in range(n):
self.birthday.append(int(random.random()*365))
def shared(self): # this function returns whether or not there's redundant birthdays
seen = []
for value in self.birthday:
if value not in seen:
seen.append(value)
else:
return True
return False
## main script
## Generate 10000 groups with n number of birthdays, and count how many have redundant birthdays in them.
total = 10000
shared = 0
for x in range(total):
birthdays = Birthdays()
if birthdays.shared():
shared = shared +1
print shared, "groups out of", total, "have members sharing the same birthday."
'''
## Another algorithm for birthday paradox
person = 23
odd = 1.0
for x in range(2,person+1):
odd = odd * (366 - x)/365
print x, "person:", (1-odd)*100, "%"
'''
| true |
903aa0e96b97ceccddca8fd95c85305740457609 | NollHyury/pythonStudies | /basico/exemplos/stringAdvanced.py | 524 | 4.1875 | 4 | seq = "Hyury Luis Da Silva Noll " + "\n"
print(seq)
# deixa a string em letra minuscula
print(seq.lower())
# remove os caractéris especiais
print(seq.strip())
# deixa a string em letra maiuscula
seq = seq.upper()
print(seq)
# converte uma string em uma lista
x = seq.split("Y")
print(x)
# busca o indice onde esta localizado a palavra passada por parametro, e retorna o mesmo.
busca = seq.find("NOLL")
print(busca)
# altera um determinado valor dentro de uma string
busca = seq
busca = busca.replace("HYURY","LUCAS")
print(busca)
| false |
4978ac8ee5c526eb06d5df690de298c9ecba382b | KobiShashs/Python | /2_Strings/9_example.py | 251 | 4.125 | 4 | word = "spaceship"
# e,p,p
print('e' not in word)
#False
print(word.isspace())
#False
print(word.count('p'))
##2
print(word.find('sh'))
#5
print(word.endswith('e'))
#False
print(len(word))
#9
print(word[-2::-4])
#ic
print(word.startswith('spa'))
#True | false |
bd227281abb94c8791e31ce464d1640e4c8502b0 | Py-Contributors/AlgorithmsAndDataStructure | /Python/Algorithms/Maths/RomanToInt.py | 596 | 4.1875 | 4 | # !/usr/bin/env python3.6
'''
Converts Roman Numeral into Decimal Number'''
mapping = (
('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
('V', 5),
('IV', 4),
('I', 1),)
def romanToInt(s):
ans = index = 0
for (numeral, number) in mapping:
while s[index:index + len(numeral)] == numeral:
ans += number
index += len(numeral)
return ans
print(romanToInt('IX')) # 9
print(romanToInt('X')) # 10
print(romanToInt('LVIII')) # 58
| false |
65fd056b3c9cdc37c72a927d314a1c83a21f3ebc | Py-Contributors/AlgorithmsAndDataStructure | /Python/Algorithms/Sieve Algorithms/sieveOfEratosthenes.py | 867 | 4.34375 | 4 | # Sieve of Eratosthenes
# It is an efficient algorithm used to find all the prime numbers smaller than
# or equal to a number(n)
# We will create a list and add all the elements and then remove those elements
# which are not prime
def sieveOfEratosthenes(n):
# Creating an empty list
primeList = []
for i in range(2, n + 1):
# Adding all the elements
primeList.append(i)
i = 2
while i * i <= n:
if i in primeList:
# Here we will remove all the elements that are multiples of i less
# than n + 1 and greater than i
for j in range(i * 2, n + 1, i):
if j in primeList:
primeList.remove(j)
i = i + 1
print(primeList)
n = int(input("Enter the number upto which \
you want to print the prime numbers :"))
sieveOfEratosthenes(n)
| true |
4746f743c4e0919f3a088284abcd9453c2ef3bd8 | Py-Contributors/AlgorithmsAndDataStructure | /Python/Algorithms/Maths/MarathiToEnglish_number.py | 934 | 4.21875 | 4 | '''
English_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
Below is marathi numbers list
This program will convert the input number into english number
'''
marathi_digits = ['०', '१', '२', '१', '४', '५', '६', '७', '८', '९']
a = input("Enter marathi digit: ")
if a in marathi_digits:
print("English Digit: ", marathi_digits.index(a))
# It will go to this condition if marathi number is of more than one digit
else:
c = 0 # counter is to check input is valid or not
n1 = ''
for i in a:
if i in marathi_digits:
n1 += str(marathi_digits.index(i))
c = c + 1
if c != 0:
print("English Digit: ", n1)
else:
print("Enter marathi number only")
'''
OUTPUT-:Enter marathi digit:६७८
English Digit: 678
Enter marathi digit:०
English Digit: 0
Enter marathi digit: seven
Enter marathi number only
'''
| false |
23a893a893954dc4fea0aaaea5e0f927635b193e | Py-Contributors/AlgorithmsAndDataStructure | /Python/Algorithms/DivideAndConquer/MergeSort.py | 1,462 | 4.46875 | 4 | from typing import List
def merge(left: List[int], right: List[int]) -> List[int]:
"""Merges two sorted lists into a single sorted list.
Args:
left (list): The left half of the list to be merged.
right (list): The right half of the list to be merged.
Returns:
list: The sorted list resulting from merging the left and right halves.
"""
if len(left) == 0:
return right
if len(right) == 0:
return left
result = []
index_left = index_right = 0
while len(result) < len(left) + len(right):
if left[index_left] <= right[index_right]:
result.append(left[index_left])
index_left += 1
else:
result.append(right[index_right])
index_right += 1
if index_right == len(right):
result += left[index_left:]
break
if index_left == len(left):
result += right[index_right:]
break
return result
def merge_sort(unsorted_list: List[int]) -> List[int]:
"""Sorts a list of integers using the merge sort algorithm.
Args:
unsorted_list (list): The unsorted list to be sorted.
Returns:
list: The sorted list.
"""
if len(unsorted_list) < 2:
return unsorted_list
midpoint = len(unsorted_list) // 2
return merge(left=merge_sort(unsorted_list[:midpoint]),
right=merge_sort(unsorted_list[midpoint:]))
| true |
1be239ea81488d063113d858ea50bee5559e21f8 | alitadodo/BTVN2 | /exercises1.py | 329 | 4.21875 | 4 | height = float(input("Enter meters: "))
weight = float(input("Input kilogram: "))
BMI = (weight / ((height * height)/10000))
print (BMI)
if BMI < 16:
print ("Severely underweight")
elif BMI < 18.5:
print ("Underweight")
elif BMI < 25:
print ("Normal")
elif BMI < 30 :
print ("Overweight")
else:
print("Obese") | false |
2185d883e7209cd249717e152153d6dfbed0cfbc | jmsrch8/codeDump | /HumphriesCHW10.py | 1,266 | 4.125 | 4 | #! /bin/python3
#name: HumphriesCHW10
#programmer: Cullen Humphries
#date: friday, august 5, 2016
#abstract This program will add records to a file and display records using a module
#===========================================================#
import time
from assign10_module import *
# define main
def main():
#print menu
print('''
MENU
1. Add records to file
2. Display Records in file
3. search records in file
4. change records in file
5. remove recods in file
0. quit''')
#reading user choice
flag = 1
while flag == 1:
try:
choice = input('\nEnter number of menu choice: ')
except:
print('error')
exit()
if choice == '0':
exit()
elif choice == '1':
addrec()
exit()
elif choice == '2':
print('displaying the first 10 entrys in the file:')
disrec()
exit()
elif choice == '3':
input('searching for record... ...press enter to continue...')
flag = 2
elif choice == '4':
input('changing record... ...press enter to continue...')
flag = 2
elif choice == '5':
input('removing record... ...press enter to continue...')
flag = 2
else:
print('\nplease choose 1, 2, 3, 4, 5, or 0')
exit()
#creating simple exit function
def exit():
input('\nPress \'ENTER\' to exit... ')
raise SystemExit
main()
| true |
6ad4dcbbc54350b53f555a6ca5246f5a40089957 | Pereirics/Exercicios_Curso_Python | /ex037.py | 351 | 4.21875 | 4 | n1 = int(input('Escreva um número: '))
m = int(input("""Escolha um método de conversão:
1 para binário
2 para octal
3 para hexadecimal
Insira o valor: """))
if m == 1:
n1 = bin(n1)
elif m == 2:
n1 = oct(n1)
elif m == 3:
n1 = hex(n1)
else:
print('Valor inválido!')
print(f'O valor convertido para a opção escolhida é: {n1}!')
| false |
408192181f07281e220e2a9b9380617a30b5f594 | hujieying/python-learning | /LPTHW/ex33-1.py | 615 | 4.1875 | 4 | # coding:utf-8
# 将这个while循环写成一个函数,将测试条件(i < 6)中的6换成一个变量。
# 使用这个函数重写脚本,并用不同的数进行测试。
# 添加另一个参数,定义第八行的+1,这样可以让它任意递增。
i = 0
numbers = []
maxium = int(raw_input("please input a number!\n"))
step = int(raw_input("please input a step!\n"))
while i < maxium:
print ("At the top i is %d" % i)
numbers.append(i)
i += step
print ("Numbers now:", numbers)
print ("At the bottom i is %d" % i)
print ("The numbers:")
for num in numbers:
print (num) | false |
251bfd3225531b67568ecb419113ccd5a99cf6b2 | jonnytaddesky/taskPython | /ugol.py | 654 | 4.21875 | 4 | # Напишите программу , в которой по извесной начальной скорости
# V и времени полета тела T определяется угол aльфа под которым
# тело брошено по отношению к горизонту (воспользуйтесь соотношением a = arcsin(gT/2V) ).
# Ниже показан вывод программы, которая у вас должна получиться:
import math
g = 9.8
v = float(input('V = '))
t = float(input('T = '))
a = math.asin((g*t)/(2*v))
alpha = (a*180)/math.pi
print('Ugol = {}'.format(alpha)) | false |
dbdd36983477cda4f79005891bc432a7ddc542fa | UnderGrounder96/mastering-python | /03. Implemented Data Structures/1.Stack.py | 316 | 4.1875 | 4 | ##### 13. STACKS
# Last In First OUT
stack = []
stack.append(1)
stack.append(2)
stack.append(3)
print(stack)
last = stack.pop()
print(last)
print(stack)
print(stack[-1]) # getting the item on top of the stack
# checking if the stack is empty
if not stack: # that means we have an empty stack
# do something | true |
823f785ada0a4688d09c16e06e7eed11c3c5b8ac | UnderGrounder96/mastering-python | /10. OOP/05.ClassVsInstanceMethods.py | 539 | 4.1875 | 4 | # 5. CLASS VS INSTANCE METHODS
class Point:
def __init__(self, x, y): # this is an instance method
self.x = x
self.y = y
# 1. defining a Class Method
@classmethod # this is called a decorator and it's a way to extend the behavior of a method
def zero(cls):
return cls(0, 0)
def draw(self): # this is an instance method
print(f"Point ({self.x}, {self.y})")
# 2. calling the Class Method
point = Point.zero() # this is a class method. It's equivant to -> point = Point(0, 0)
point.draw() | true |
30882ebeb9098c8a1dfd0e587dbc8b23d3c4b00b | UnderGrounder96/mastering-python | /07. Functions/2.args.py | 513 | 4.5 | 4 | # *args (arguments)
# *args behaves like a tuple of parameters that are coming in.
# *args allows us to take random numbers of arguments.
# * means a collection of arguments
# EXAMPLE 1
def myfunc(*args):
return sum(args)
myfunc(40,60,100)
# EXAMPLE 2
def myfunc(*args):
for item in args:
print(item)
myfunc(40,60,70,100)
# EXAMPLE 3
def multiply(*numbers): # * means a collection of arguments
total = 1
for number in numbers:
total *= number
return total
print(multiply(2, 3, 4, 5)) | true |
eb3fb66e3983c8ea0d131c308cd32b0ed8c30b0c | UnderGrounder96/mastering-python | /02. Built-in Data Structures/4.sets.py | 963 | 4.625 | 5 | # EXAMPLE 1
myset = set();
myset.add(1)
myset.add(2)
myset.add(3)
mylist = [1,2,3,4,5]
myset2 = set(mylist)
# EXAMPLE 2
numbers = [1, 1, 2, 2, 4, 3]
print(numbers)
# converting the list into a set
set_uniques = set(numbers)
print(set_uniques)
# defining a new set
set_new = { 1, 4}
set_new.add(5)
set_new.remove(5)
len(set_new)
print(set_new)
# Sets shine in the Powerful Mathematical Operations that are supported by them
first = set(numbers)
second = {1, 2, 5, 6}
#union
print(first | second)
# intersection - the numbers that exist in both set
print(first & second)
# difference
print(first - second) # the elements that exist in the "first set" and don't exist in the "second set"
print(second - first) # the elements that exist in the "second set" and don't exist in the "first set"
print(first ^ second) # the elements that exist either in the first or second set but not both
# checking for the existance of 1
if 1 in first:
print("yes") | true |
e083ac37956b22d92143b8cd5a89a807a5c15a01 | asazonov28/andrei | /Student/Lesson2.py | 2,463 | 4.1875 | 4 | # string_sample = 'Hello World'
# number = '12345678'
# number2 = '-8-7-6-5-4-3-2-1'
# print(len(string_sample))
# print(len(number))
# #
# print(string_sample[6:11])
#
# print(string_sample[-7:])
#
# print(string_sample[0:11:2]) #индексация строки с шагом 2
#
# print(string_sample[::-1]) #индексация с обратным шагом
#
# new_string = string_sample
empty_string = ''
string_sample = "Hello world world"
string_sample2 = 'first letteR is lowErcase'
string_sample3 = " .extra whitespace string ."
german_sample = "der Flub$"
name_sample = 'andrei'
print(string_sample.upper())
string_sample = string_sample.upper()
print(string_sample)
print(string_sample.lower())
#
# a, b, c = input('Please enter s')
#
# user_input = string_sample.split()
# print(user_input)
# print(string_sample.count('l')) #подсчет слов или других данных
# print(len(string_sample2)) #подсчет всех символов
#
# print(string_sample.find('world'))
# print(string_sample[6:12].find('world'))
#
# print('world' in string_sample) #проверка
# a = 'Hello'
# b = 'world'
#
# print(a + ' ' + b)
#
# name = 'Andrei'
# age = 41
# profession = 'spetsialist'
# print('Hello ' + name + '. Your age ' + str(age) + '. You are ' + profession + '.')
# name = 'Andrei'
# salary = 1800
# string_sample = "{1}'s salary is {0}"
#
# print(string_sample.format(salary, name))
#
# string_sample = "{}'s salary is {}"
# print(string_sample.format(name, salary))
#
# string_sample = "This {product:} costs {price:.4f} euros"
# print(string_sample.format(price=350, product='Computer'))
# x = 1256455.5662
# y = 123545.522365
# z = 'Hello world'
#
# print('The value of x is %.y')
#
#
# emp_name = 'Andrei'
# emp_age = 45
# emp_salary = 1800
# emp_string = 'Hi, my name is %(name)s! I am %(age)s old. My salary is %(salary).2f' %{'name': emp_name, 'age': emp_age, 'salary': emp_salary}
#
# emp_string2 = f'Hi, my name is {emp_name}! I am {emp_age} old. My salary is {emp_salary: .2}'
# print(emp_string2)
#
# number = 90
#
# if number == 200:
# print('Number is equal to 200')
#
# elif number < 100:
# print('Number is smaller than 100')
# elif number % 2 == 0:
# print('Whole number')
# else:
# print('NOK')
#
# print('Good bye')
#
# sample_string = 'Hello world'
#
# if len(sample_string) > 10:
# print('long string')
# user_input = input('Enter ID: ')
# print(user_input)
| false |
c30c0b73aa515d1541962322d6b33079008d2a66 | Efun/CyberPatriotTutoring | /practice/Archive_8-9_2020/practice_9_27_2020.py | 1,624 | 4.1875 | 4 | from classes.BankAccount import BankAccount
# test = BankAccount('a', 'a', 100)
# print(test.balance)
# write a list of 5 elements containing tennis player names
tennisPlayers = ["serena williams", "roger federer", "rafael nadal", "novak djokovic", "rod laver"]
#print the second element of this list
#print (tennisPlayers[1])
#loops
#for loop will loop through an list like this:
#for varName in listName:
#for each tennis player in the list named tennisPlayers
idx = 0
for tennisPlayer in tennisPlayers:
#print(str(idx) + ".) " + tennisPlayer)
idx += 1
#for loop through numbers
#for varName in range(number)
#i will start at 0
# for x in range(5):
# print(str(x) + ".) " + "hi")
#range(initial_val, max_val, step_size)
#x is set to the initial_val, and then increases by step size until it exceeds the max_val
# for x in range(5, 10, 2):
# print(str(x) + ".) " + "hi")
#print out all tennis players using range instead of in tennisPlayers
#set the variable to be the place in the list where the tennis player is
#how do we get all of the numbers we need?
#x = 0, 1, 2, 3, 4
#tennisPlayers[x]
for x in range(0, 5, 1):
#print(tennisPlayers[x])
#print out every other tennis player starting at serena williams
for x in range(0, 5, 2):
#print(tennisPlayers[x])
#for x in range(5) == for x in range(0, 5, 1)
tennisPlayerA = "Lina"
tennisPlayers.append(tennisPlayerA)
#print(tennisPlayers[5])
userName = input("Type in your username.")
password = input("Type in your passwrord.")
balance = 100
bankAccounts = []
newBankAccount = BankAccount(userName, password, balance)
bankAccounts.append(newBankAccount)
| true |
155359354b2395e4c1b887ad8cb8c9312cb3f0fc | FisicaComputacionalPrimavera2018/ArraysAndVectorOperations | /vectoroperationsUpdated.py | 1,620 | 4.28125 | 4 | import math
#### FUNCTIONS
# The name of the function is "norm"
# Input: array x
# Output: the norm of x
def norm(x):
tmp = 0
for v in x:
tmp += v*v
norm_x = math.sqrt(tmp)
return norm_x
def vectorSum(x, y):
#z = x + y This doesn't work for arrays!
# First we check if the dimensions of x and y
# are the same
if len(x) != len(y):
return "ERROR"
# Now, we know the dimensions are the same
# We create an empty (zeros) vector z, which as the
# same dimensions as x and y
z = [0]*len(x)
# Next step, calculate the components of z
for i in range(0, len(z)):
z[i] = x[i] + y[i]
#z = [ x[0]+y[0], x[1]+y[1], x[2]+y[2] ]
return z # return the sum
def scalarProduct(x, y):
if len(x) != len(y):
return "ERROR"
r = 0
for i in range(0, len(x)):
r = x[i]*y[i]
return r
def angle(x, y):
return math.acos(scalarProduct(x,y) / (norm(x)*norm(y)))
# Define some three-dimensional vectors
x = [5, 3, 5]
y = [5.5, 6, 8]
z = [2, 0, 6.6]
# norm
print norm(x)
# sum
print vectorSum(x, y)
# scalar product
print scalarProduct(x, y)
# angle (homework)
norm_x = norm(x)
norm_y = norm(y)
n = scalarProduct(x,y)
#print math.acos(n/(norm_x*norm_y))
# shorter way:
#print math.acos(scalarProduct(x,y) / (norm(x)*norm(y)))
# even shorter
angle1 = angle(x, y)
print angle1
#print angle(x, y)
# convert to degrees
#print math.degrees(angle(x, y))
# angle of vector A between x,y,z axis
A = [5, 6, 11]
alpha_1 = angle(A, [1, 0, 0])
alpha_2 = angle(A, [0, 1, 0])
alpha_3 = angle(A, [0, 0, 1])
print alpha_1, alpha_2, alpha_3
# vector product (homework)
| true |
77d3c7c625dc887ddc8aaa848f0d199fbfa1a06b | JinalShah2002/MLAlgorithms | /LinearRegression/Prof.py | 2,211 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author Jinal Shah
Suppose you are the CEO of a restaurant franchise and are
considering different cities for opening a new outlet.
The chain already has trucks in various cities and you have data for
profits and populations from the cities.You would like to use this data to
help you select which city to expand to next.
This is the Gradient Descent tester. Since I am only looking to test
Gradient Descent and make sure it works, the given problem has already
been determined to be a Linear Regression problem. For future problems,
the user will have to go through the Machine Learning project development
steps!
"""
# Importing the Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from GradientDescent import LinearRegression
from sklearn.model_selection import train_test_split
# Getting the data
PATH = '/Users/jinalshah/SpiderProjects/ML Algorithm Implementations/Data/Profits.csv'
raw_data = pd.read_csv(PATH)
# Splitting the data into X and y
X = raw_data.copy().drop('Profits',axis=1).values
y = raw_data.copy().drop('Population',axis=1).values
"""
Note: Since this class is only for the sole purpose
of testing the Gradient Descent implementation, the
data has already been preprocessed so no preprocessing
is needed
However, for future data sets, you will need to
preprocess the data. If needed, you will need to
apply feature scaling because gradient descent
doesn't do it for you!
"""
# Plotting the data for insights
plt.scatter(X,y,c='Red')
plt.xlabel('Population')
plt.ylabel('Profits')
plt.title('Profits v.s Population')
plt.show()
# Splitting the Data into training and testing
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=0)
# Building the Linear Regression model
regressor = LinearRegression()
regressor.fit(X_train,y_train)
# Predicting the testing set
y_pred = regressor.predict(X_test)
# Plotting the final hypothesis
plt.scatter(X_train,y_train,c='red')
plt.plot(X_train,regressor.predict(X_train),c='blue')
plt.title('Profits v.s Population')
plt.xlabel('Population')
plt.ylabel('Profits')
plt.show()
# Plotting the Cost Function
regressor.plot()
| true |
751f1777faad91870b7079238aa8d840848021b7 | prabhatpal77/Complete-core-python- | /typeconversion.py | 390 | 4.125 | 4 | #Type conversion function converse the data in the form of required format in the data is possible to convert..
a=input("enter int value")
print(type(a))
b=int(a)
print(type(b))
c=input("enter float value")
print(type(c))
d=float(c)
print(type(d))
i=input("enter complex value")
print(type(i))
j=complex(i)
print(type(j))
p=input("enter bool value")
print(type(p))
q=bool(p)
print(type(q))
| true |
0f5463149ed49570c867f233e6dbc145da9104d6 | prabhatpal77/Complete-core-python- | /identityope.py | 470 | 4.125 | 4 | #Identity operators are used to compare the addresses of the objects which are pointed by the operators ..
#there are 2 identity operators.
# 1. is 2. is not
a=1000
b=2000
c=3000
d=3000
p=[10, 20, 30]
q=[40, 50, 60]
x=[70, 80, 90]
y=[70, 80, 90]
print(a==b)
print(a!=b)
print(a is b)
print(a is not b)
print(c==d)
print(c!=d)
print(c is d)
print(c is not d)
print(p==q)
print(p!=q)
print(p is q)
print(p is not q)
print(x==y)
print(x!=y)
print(x is y)
print(x is not y)
| true |
94492c43f4f858d9e46e6484a4faf4cb1585d487 | prabhatpal77/Complete-core-python- | /filehandl.py | 323 | 4.4375 | 4 | # Through the python program we can open the file, perform the operations on the file and we can close the file..
# 'r', 'w', 'a', 't', 'b', '+' for operations on file
# Open function opens the given file into the specified mode and crete file object..
# reading from file...
x=open("myfile.txt")
print(x.read())
x.close()
| true |
cf89d81fa5fa2fc86a2770f9cf42954ffa049599 | suzibrix/lpthw | /ex4.py | 1,660 | 4.21875 | 4 | # This line assigns 100 to the variable "cars"
cars = 100
# This statement assigns the number "4.0" to the variable "space_in_car"
space_in_a_car = 4.0
# Assigns the number 30 to the variable "drivers"
drivers = 30
# Assigns the number 90 to the variable "passengers"
passengers = 90
# Assigns the difference of variable "cars" and "drivers" to "cars_not_driven"
cars_not_driven = cars - drivers
# Assigns the number stored in "drivers" to the variable "cars_driven"
cars_driven = drivers
# Assigns the multiple of "cars_driven" and "space_in_car" to "carpool_capacity"
carpool_capacity = cars_driven * space_in_a_car
# Assigns the dividend of the total of "passengers" and "cars_driven"
average_passengers_per_car = passengers / cars_driven
#
# Let's show our work
#
# Insert variable $cars into printable string revealing # of cars
print("There are", cars, "cars available.")
# Insert the variable $drivers into printable string displaying number of drivers
print("There are only", drivers, "drivers available.")
# Insert $cars_not_driven into printable string demonstrating number of unused vehicles
print("There will be", cars_not_driven, "empty cars today.")
# Insert variable $carpool_capacity into the number of people that can be driven today
print("We can transport", carpool_capacity, "people today.")
# Insert variable $passengers into the string printing how many passengers are in need of transportation
print("We have", passengers, "to carpool today.")
# Insert the variable of $average_passengers_per_car into a string printing the number of people per car
print("We need to put about", average_passengers_per_car, "in each car.")
| true |
8d33594f74c58174b463aba1f3b365e4ef01fd5e | micgainey/Towers-of-Hanoi | /towers_of_hanoi_count.py | 1,979 | 4.15625 | 4 | """
Towers of Hanoi rules
1. You can't place a larger disk onto a smaller disk.
2. Only 1 disk can be moved at a time.
Towers of Hanoi moves is:
2^n - 1
OR
2 * previous + 1
example with 3 disks
3 towers: A. B. C.
Starting point:
1
2
3
A B C
Move1
2
3 1
A B C
Move2
3 2 1
A B C
Move3
1
3 2
A B C
Move4
1
2 3
A B C
Move5
1 2 3
A B C
Move6
2
1 3
A B C
Move7
1
2
3
A B C
"""
"""
Iterative approach:
for one disk it will take 1 move
for two disks minimum number of moves is 3
...
n - 1 disks = p
2p + 1 = minimum number of moves for n disks
number of disks minimum number of moves
1 1
2 3
3 (2 * 3) + 1 = 7
4 (2 * 7) + 1 = 15
5 (2 * 15) + 1 = 31
6 (2 * 31) + 1 = 63
7 (2 * 63) + 1 = 127
8 (2 * 127) + 1 = 255
9 (2 * 255) + 1 = 511
n - 1 p
n 2p + 1
"""
# This function will return the minimum number of moves it will take to solve TOH with n disks
def towers_of_hanoi_moves(disks):
if disks <= 0:
print('Number of disks must be greater than 0')
return
num_of_moves = 0
for i in range(0, disks):
num_of_moves = (2 * num_of_moves) + 1
# Uncomment below to see the number of moves for each disk
# print(num_of_moves)
return num_of_moves
# print(towers_of_hanoi_moves(9))
num_of_moves = int(input("Enter the number of disks: "))
print(towers_of_hanoi_moves(num_of_moves))
| true |
a5305f23d0038814f95207a3dba6199913518cbd | thewchan/impractical_python | /ch4/storing_route_cipher_key.py | 1,387 | 4.25 | 4 | """
Pseudo-code:
ask for number of length of key
initiate defaultdict
for count in length of key
ask for column number store as temp1
ask for direction store as temp2
defaultdict[temp1] = temp2
"""
from collections import defaultdict
while True:
key_len = input("Enter length of key: ")
try:
key_len = int(key_len)
except ValueError:
print("Please enter a number.")
continue
break
key_stored = defaultdict(int)
for column in range(key_len):
while True:
column_num = input(f"Enter column number for position {column + 1}: ")
try:
column_num = int(column_num)
except ValueError:
print("Please enter a number.")
continue
if (column_num > 0 and column_num <= key_len):
break
else:
print("Please enter a valid column number.")
continue
while True:
direction = input(
f"Enter direction of position {column + 1} (up/down): "
)
if direction.lower() == 'up':
direction = -1
break
elif direction.lower() == 'down':
direction = 1
break
else:
print("Please enter a valid direction (up/down).")
continue
key_stored[column_num] = direction
print("The key you have entered is:\n ", key_stored)
| true |
6a1716818b21e765ba02e275553467a060c21269 | Kids-Hack-Labs/Fall2020 | /Activities/Week02/Code/activity1_suggested_solution.py | 737 | 4.125 | 4 | """
Kids Hack Labs
Fall 2020 - Senior
Week 02: Python Review
Activity 1
"""
#Step 1: Function that takes 2 arguments and displays greater
def greater(num_a, num_b):
if num_a > num_b:
print(num_a, "is greater than", num_b)
else:
print(num_b, "is greater than", num_a)
#step 2: Inputs from user (cast to integer) stored in variables
first = int(input("First number, please: "))
second = int(input("Second number, please: "))
#step 3: Calling function defined in step 1
greater(first, second)
"""
Obs.: Inputs were cast to integers for comparison.
The implementation does not account for
equal numbers. The student is free to improve
the code in that regard.
"""
| true |
1c7b497ffce28f0a1f2faa790eca25693b2814c1 | Kids-Hack-Labs/Fall2020 | /Activities/Week04/Code/act2.py | 1,116 | 4.3125 | 4 | """
Kids Hack Labs
Fall 2020 - Senior
Week 04: Introduction to Classes
Activity 2
"""
#Suggested answer:
class Animal():
def __init__(self, _type, _name, _legs, _sound):
self.type = _type
self.name = _name
self.legs = int(_legs)
self.sound = _sound
def walk(self):
for i in range(self.legs):
print("step", end= " ")
def make_sound(self):
print(self.sound)
def get_name(self):
print("The "+self.type+"'s name is: "+self.name+".")
"""
The following twelve lines should be input in the shell,
once the current module is run. The names and data in the
animals are simply suggestions, and serve to test the
class's functions under different initial parameters
puppy = Animal("dog", "Hacky", 4, "woof!")
puppy.walk()
puppy.make_sound()
puppy.get_name()
kitty = Animal("cat", "Nimbus", 4, "meow!")
kitty.walk()
kitty.make_sound()
kitty.get_name()
flappy = Animal("duck", "Chamille", 2, "Quack!")
flappy.walk()
flappy.make_sound()
flappy.get_name()
"""
| true |
c58359a746beaaa275045aafa9d1509b028a2760 | Kids-Hack-Labs/Fall2020 | /Homework/W02/Code/w02_hw_suggested_solution.py | 1,213 | 4.125 | 4 | """
Kids Hack Labs
Fall 2020 - Senior
Week 02: Python Review
Homework: Number guessing game
"""
#Step 1: random module import
import random
#Step 2: application main entry point
def main():
#setup (steps 2.1 through 2.5)
random.seed()
tries = 5 #total tries granted
guesses = 0 #total guesses made
player_won = False
target = random.randint(1, 63)
#game loop(step 2.6 and sub-steps)
while guesses < tries and not player_won:
player_guess = int(input("Guess a number: "))
guesses += 1
if player_guess == target:
player_won = True
else:
if player_guess < target:
print("You guessed lower than the secret number.")
else:
print("you guessed higher than the secret number.")
#Game end: Steps 2.7 and 2.8
if player_won:
print("You won the game in",guesses,"tries!")
else:
print("You lost the game... The secret number was",target)
if __name__ == "__main__":
main()
"""
Obs.: Students are encouraged to experiment with the code and try
other techniques to generate the numbers or streamline the outputs
to the user.
"""
| true |
5eb8e0b24c3f32f17ec1d13c07aee382aeef9a39 | himajasricherukuri/python | /src/listfunctions.py | 1,949 | 4.21875 | 4 | lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.extend(lucky_numbers)
print(friends)
# extend function allows you take a list and append it on another list
#append- adding individual elements
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.append("creed")
print(friends)
#insert - inserts the element at the given index, shifting elements to the right.
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.insert(1,"kelly")
print(friends)
#remove - searches for the first instance of the given element and removes it
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.remove("jim")
print(friends)
#clear - gives an empty list
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.clear()
print(friends)
#pop- pops /remobves last element in the list
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.pop()
print(friends)
#index- searches for the given element from the start of the list and returns its index.
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
print(friends.index("kevin"))
#count the number of similar elements
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby","kevin"]
print(friends.count("kevin"))
#sort - sort the list in ascending order
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.sort()
lucky_numbers.sort()
print(lucky_numbers)
print(friends)
# reverse a list
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.reverse()
print(friends)
# copy -used to copy attributes from another list
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends2 = friends.copy()
print(friends2)
| true |
b33bd9fe0dffcc22d3f657b10d11d1aff016b5b1 | yourpalfranc/tstp | /14challenge-2.py | 671 | 4.21875 | 4 | ##Change the Square class so that when you print a square object, a message prints telling you the
##len of each of the four sides of the shape. For example, if you ceate a square with Square(29)
##and print it, Python should print 29 by 29 by 29 by 29.
class Square():
square_list = []
def __init__(self, sides):
self.side_length = sides
self.square_list.append(self.side_length)
def print_sides(self):
print(self.side_length, " by ", self.side_length, " by ", self.side_length, " by ", self.side_length)
s1 = Square(29)
s2 = Square(30)
s3 = Square(40)
s4 = Square(50)
##print(s1.side_length)
s1.print_sides() | true |
e489a9c6d7e662cd125a74b2f014614bdc861a9f | yourpalfranc/tstp | /13challenge-2.py | 937 | 4.1875 | 4 | ##Define a method in your Square class called change_size that allows you to pass in a number
##that increases or decreases (if the number is negative) each side of a Square object by that
##number.
class Rectangle():
def __init__(self, width, length):
self.width = width
self.length = length
print("Object Created")
def calculate_perimeter(self):
return (self.width + self.length)*2
class Square(Rectangle):
def change_size(self, newnum):
if newnum >= 0:
print("New Square perimeter: ", my_square.calculate_perimeter() + (newnum * 4))
else:
print("New Square perimeter: ", my_square.calculate_perimeter() + (newnum * 4))
my_rectangle = Rectangle(24, 30)
my_square = Square(10, 10)
print("Rectangle perimeter: ", my_rectangle.calculate_perimeter())
print("Square perimeter: ", my_square.calculate_perimeter())
my_square.change_size(2)
| true |
1cdbf36cf05b93addd8e5797b82747e5448462f8 | druv022/Disease-Normalization-with-Graph-Embeddings | /nerds/util/file.py | 1,216 | 4.21875 | 4 | import shutil
from pathlib import Path
def mkdir(directory, parents=True):
""" Makes a directory after checking whether it already exists.
Parameters:
directory (str | Path): The name of the directory to be created.
parents (boolean): If True, then parent directories are created as well
"""
path_dir = Path(directory)
if not path_dir.exists():
path_dir.mkdir(parents=parents)
def rmdir(directory, recursive=False):
""" Removes an empty directory after checking whether it already exists.
Parameters:
directory (str | Path): The name of the directory to be removed.
recursive (boolean): If True, then the contents are removed (including subdirectories and files),
otherwise, the directory is removed only if it is empty
"""
path_dir = Path(directory)
if not path_dir.exists():
return
if recursive:
shutil.rmtree(path_dir)
else:
if len(list(path_dir.iterdir())) == 0:
path_dir.rmdir()
else:
raise ValueError(
"Cannot remove directory '{}' as it is not empty: consider removing it recursively".format(path_dir))
| true |
e5b94f0ba5cadbd496e8bf15318db7ae8f4d31cf | Abhiram-Agina/PythonProjects_Algebra | /CHAPTER10_ExponentsProperties.py | 1,776 | 4.25 | 4 | # Type in an Expression that includes exponents and I will give you an Answer
# Negative Exponents: Work in progress
SEEquations = input(" Type in a simple expression using exponents, 1 operator, and the same constant (i.e. 3^2 * 3^6) \n ")
terms2 = SEEquations.split(" ")
ExponentTerms = []
for item in terms2:
if '^' in item:
ExponentTerms.append(item)
print(ExponentTerms)
lhs1, rhs1 = ExponentTerms[0].split('^')
lhs2, rhs2 = ExponentTerms[1].split('^')
ExpoNum = int(int(rhs1) + int(rhs2))
counter = 1
sumNum = (int(lhs1) * int(lhs1))
print(" your answer is: ... \n")
if('*' in str(SEEquations)):
print(str(lhs1) + "^" + str(ExpoNum))
while(counter < ExpoNum-1):
sumNum = sumNum * int(lhs1)
counter = counter + 1
print("= " + str(sumNum))
if('/' in str(SEEquations)):
print(str(lhs1) + "^" + str(int(int(rhs1) - int(rhs2))))
while((counter < int(int(rhs1) - int(rhs2)))-1):
sumNum = sumNum * int(lhs1)
counter = counter + 1
print("= " + str(sumNum))
Ans1 = 0
Ans2 = 0
if('+' in str(SEEquations)):
while(counter < int(rhs1)-1):
sumNum = sumNum * int(lhs1)
counter = counter + 1
Ans1 = sumNum
sumNum = (int(lhs1) * int(lhs1))
counter = 1
while(counter < int(rhs2)-1):
sumNum = sumNum * int(lhs1)
counter = counter + 1
Ans2 = sumNum
print("= " + str(int(Ans1 + Ans2)))
if('-' in str(SEEquations)):
while(counter < int(rhs1)-1):
sumNum = sumNum * int(lhs1)
counter = counter + 1
Ans1 = sumNum
sumNum = (int(lhs1) * int(lhs1))
counter = 1
while(counter < int(rhs2)-1):
sumNum = sumNum * int(lhs1)
counter = counter + 1
Ans2 = sumNum
print("= " + str(int(Ans1 - Ans2))) | true |
9fbf604768140b0492442807d028f1c7673d54db | jansenhillis/Python | /A001-Python-HelloWorld/hello_world.py | 514 | 4.34375 | 4 | #1. Hello World
print("Hello World")
#2. Hello Your Name
name = "Jansen"
print("Hello " + name)
print("Hello", name)
#3. Hello Num
# Convert num to a string so concatenation will work
num = "111"
print("Hello " + num)
print("Hello", num)
#4. I love food
food1 = "Chinese"
food2 = "Sushi"
print("I love to eat {} and {}".format(food1, food2))
print(f"I love to eat {food1} and {food2}")
#5. String explore
str = "world"
print(str.capitalize())
print(str.isalpha())
print(str.isdecimal())
print(str.join(food2)) | false |
9e25339de670199da3cab9de8a98cc88c58cb5ca | jansenhillis/Python | /A004-python-functionsBasic2/functionsBasic2.py | 2,414 | 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(seed):
seedList = []
for i in range(seed, -1, -1):
seedList.append(i)
return seedList
# print(downList(10))
# 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(lst):
print(lst[0])
return(lst[1])
# print(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(lst):
return lst[0] + len(lst)
# print(first_plus_length([1,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(lst):
if len(lst) < 2:
return False
shortList = []
secondVal = lst[1]
for item in lst:
if item > secondVal:
shortList.append(item)
print(len(shortList))
return shortList
# print (values_greater_than_second([5, 2, 3, 2, 1, 4]))
# print (values_greater_than_second([5]))
# print (values_greater_than_second([5, 2]))
# 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):
newList = []
for i in range(size):
newList.append(value)
return newList
# print(length_and_value(4, 7))
# print(length_and_value(6, 2)) | true |
aa2b452ad6dc250ff6af924bacd87a7d864a541f | mafdele20/TD_ALGO | /python/exo6.py | 567 | 4.125 | 4 | from math import sqrt
def distance():
x1=int(input(" entrer la premiere coordonnée du point A\n"))
y1=int(input(" entrer la deuxieme coordonnée du point A\n"))
x2=int(input(" entrer la premiere coordonnée du point B\n"))
y2=int(input(" entrer la deuxieme coordonnée du point B\n"))
dis = (((x1 - x2)*2) + ((y1-y2)*2))
if dis < 0:
print("imposible")
else:
sqrte = sqrt(dis)
print("la distance entre A et B est "+str(sqrte))
if __name__ == '__main__':
distance() | false |
2e129574ad41492e099ab2181717ed8aeb79fb1f | simoonsaiyed/CS303 | /Payroll.py | 1,620 | 4.15625 | 4 | # Assignment 3: Payroll.py
# A program that prints out the Payroll dependent on inputs.
def calculate(worked, pay, fedtax, statetax):
worked = float(worked)
gross = worked * pay
fedwitholding = fedtax * gross
statewitholding = statetax * gross
total = statewitholding + fedwitholding
return worked, gross, fedwitholding, statewitholding, total
def main():
# enter inputs
name = input("Enter employee ’s name : ")
hours_worked = int(input("Enter number of hours worked in a week : "))
hourly_pay = float(input("Enter hourly pay rate : "))
federal_tax = float(input("Enter federal tax withholding rate : "))
fedtax = str(float(federal_tax * 100)) + '%'
state_tax = float(input("Enter state tax withholding rate : "))
sttax = str(float(state_tax * 100)) + '%'
worked, gross, fedwitholding, statewitholding, total = calculate(hours_worked, hourly_pay, federal_tax, state_tax)
# print the final statements
print("Employee Name :", name)
print("Hours Worked :", worked)
print("Pay Rate : $" + str(hourly_pay))
print("Gross Pay : $" + str(gross))
print("Deductions:")
fedwitholding = "{:.2f}".format(fedwitholding)
print(" Federal Withholding " + '(' + fedtax + ')' + ': $' + str(fedwitholding))
statewitholding = "{:.2f}".format(statewitholding)
print(" State Withholding " + '(' + sttax + ')' + ': $' + str(statewitholding))
totall = "{:.2f}".format(total)
print(" Total Deductions: $" + str(totall))
netpay = gross - total
netpay = "{:.2f}".format(netpay)
print("Net Pay: $" + str(netpay))
main()
| true |
7b683b972accd14c161f79cb23a585863a9ab556 | rubayetalamnse/Basic-Python-Codes | /string-finction.py | 1,224 | 4.5625 | 5 | print(len("rubayet"))
#string functions------->>>>
passage = "nuclear energy provide zero carbon electricity, most reliable and cheap one. This energy is better than renewable energy! If we talk about wind power or solar or hydro, nuclear takes lowest place and produces maximum energy. And obviously we should come out of oil/gas/coal powered energy sources and their applications"
#len is used to count all the string characters
print(len(passage))
#endswith is used to verify the last word or last character in a string/passage/word/line
print(passage.endswith("applications"))
print(passage.endswith("rubayet"))
print(passage.endswith("e"))
#lets find out how many e or any other characters/words are there in the passage
print(passage.count("e"))
print(passage.count("energy"))
#lets captialize energy in the passage
print(passage.capitalize())
#lets find any word from the given passage, we will find the word "carbon"
print(passage.find("carbon")) # 4 will come as answer
#here indexing starts from 0, so nuclear-->0, energy-->1,provides-->2,zero-->3, carbon-->4
#lets replace the word "provide" with "produce"
print(passage.replace("provide", "produce"))
print("Nuclear is good.\n it \tis best for \\ all.") | true |
eeb24838ff1e76e6e73c80e79741e364e5716782 | rubayetalamnse/Basic-Python-Codes | /geeks-1.py | 353 | 4.15625 | 4 | #printing sum of two numbers
num1 = 10
num2 = 45
sum = num1+num2
print("Sum of {0} and {1} is : {2}".format(num1,num2,sum))
#printing sum of two decimal or float numbers
no1 = input("enter any decimal Number: ")
no2 = input("enter another decimal number: ")
sum2 = float(no1)+float(no2)
print("The sum of {0} and {1} is: {2} ".format(no1,no2,sum2)) | true |
8467ad15dcfeb454383e1ef26143328ccca9ec7d | rubayetalamnse/Basic-Python-Codes | /functions11.py | 2,640 | 4.40625 | 4 | """You're planning a vacation, and you need to decide which city you want to visit. You have shortlisted four cities and identified the return flight cost, daily hotel cost, and weekly car rental cost. While renting a car, you need to pay for entire weeks, even if you return the car sooner.
City Return Flight ($) Hotel per day ($) Weekly Car Rental ($)
Paris 200 20 200
London 250 30 120
Dubai 370 15 80
Mumbai 450 10 70
Answer the following questions using the data above:
1.If you're planning a 1-week long trip, which city should you visit to spend the least amount of money?
2.How does the answer to the previous question change if you change the trip's duration to four days, ten days or two weeks?
3.If your total budget for the trip is $1000, which city should you visit to maximize the duration of your trip? Which city should you visit if you want to minimize the duration?
4.How does the answer to the previous question change if your budget is $600, $2000, or $1500?
Hint: To answer these questions, it will help to define a function cost_of_trip with relevant inputs like flight cost, hotel rate, car rental rate, and duration of the trip. You may find the math.ceil function useful for calculating the total cost of car rental."""
#solve-3----
import math
paris_f,paris_h,paris_c = 200,20,200
london_f,london_h,london_c =250,30,120
dubai_f,dubai_h,dubai_c =370,15,80
mumbai_f,mumbai_h,mumbai_c = 450,10,70
def vacation_cost_trip(flight_cost, hotel_rate,car_rental):
total_cost = flight_cost + hotel_rate + car_rental
return math.ceil(total_cost)
#for 16 days----------------------------------------------------------------
paris_trip = vacation_cost_trip(paris_f,paris_h*16,paris_c*(16/7))
print("to make a 16 days vacation plan in paris, you need to have",paris_trip,"dollars!")
london_trip_expensive = vacation_cost_trip(london_f,london_h*15,london_c*(15/7))
print("to make a 15 days vacation plan in London, you need to have",london_trip_expensive,"dollars!")
dubai_trip = vacation_cost_trip(dubai_f,dubai_h*16,dubai_c*(16/7))
print("to make a 16 days vacation plan in DUBAI, you need to have",dubai_trip,"dollars!")
mumbai_trip = vacation_cost_trip(mumbai_f,mumbai_h*16,mumbai_c*(16/7))
print("to make a 16 days vacation plan in mumbai, you need to have",mumbai_trip,"dollars!")
mumbai_trip_cheap = vacation_cost_trip(mumbai_f,mumbai_h*27,mumbai_c*(27/7))
print("to make 27days vacation plan in mumbai, you need to have",mumbai_trip_cheap,"dollars!")
| true |
933857731a1e75f757c5f57ef7913ca5585b0f7e | rubayetalamnse/Basic-Python-Codes | /celsius-farenheit.py | 598 | 4.3125 | 4 | #Write a Python program to convert temperatures to and from celsius, fahrenheit.
temperature = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.) : ")
degree = int(temperature[0:-1])
temp = temperature[-1]
if temp.upper() == "F":
celsius_temp = float((degree - 32) * 5/9 )
print("The temperature -", temperature, "in celsius is", celsius_temp, "degrees.")
elif temp.upper() == "C":
farenheit_temp = float((9 * degree) / 5 + 32)
print("The temperature -", temperature, "in celsius is", farenheit_temp, "degrees.")
else:
print("Input proper temperature.") | true |
94529887c259ec0c647cf90102487626a0b36fd5 | rubayetalamnse/Basic-Python-Codes | /for-break.py | 241 | 4.1875 | 4 | for i in range(5,20):
print(i)
if i==10:
break
#when i ==10, the loop ends. We see values from 5 to 10 in the terminal.
else:
print("as we used break at 10, 5 to 10 is printed. after that this else loop won't be printed") | true |
622019a68abba6e0c1d31bdec0ad3c2d7778809a | rubayetalamnse/Basic-Python-Codes | /functions6.py | 1,310 | 4.15625 | 4 | #If you borrow $100,000 using a 10-year loan with an interest rate of 9% per annum, what is the total amount you end up paying as interest?
import math
#for loan emi------------------------
loan = 100000
loan_duration = 10*12 #10 years
interest_rate = .09/12 #compounded monthly
#reusing our previous function to calculate emi---------
def loan_emi_interest(amount,duration,interest,down_payment):
loan_amount = amount-down_payment
try:
emi_interest = (loan_amount * interest * ((1+interest) ** duration)) /(((1+interest) **duration)-1)
except ZeroDivisionError:
emi_interest = loan_amount/duration
return math.ceil(emi_interest)
#calling our function to calculate emi with interest------------
emi_with_interest =loan_emi_interest(amount = loan, duration =loan_duration, interest=interest_rate, down_payment=0)
print("EMI WITH Interest:",emi_with_interest)
#calling our function to calculate emi without interest------------
emi_without_interest =loan_emi_interest(amount = loan, duration =loan_duration, interest=0, down_payment=0)
print("EMI without Interest:",emi_without_interest)
#total interest-------
total_interest = emi_with_interest - emi_without_interest
print("total interest per month:",total_interest)
print("total interest for 10 year:",total_interest*120) | true |
c906588466eab7370fdbf6f6c8ec7706130706a2 | rubayetalamnse/Basic-Python-Codes | /basic-tuple2.py | 250 | 4.1875 | 4 | #got to know something new:----------------
#let's create a tuple----->
numbers = (1,2,3,4,5,6,7,8,9,10)
#reverse tuple ----
b = numbers[::-1]
print(b)
#output---(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
c = numbers[::2]
print(c)
#output--->(1, 3, 5, 7, 9) | false |
c81b693f9dcca328b6d547ed885ed5403a266cbf | rubayetalamnse/Basic-Python-Codes | /q4b.py | 845 | 4.125 | 4 | #Use a for loop to display the type of each value stored against each key in person
person = {
"Name":"Rubayet",
"Age": 21,
"HasAndroidPhone": True
}
for i in range(len(person)):
print(type(person.keys()))
print(type(person.values()))
for value in person:
print(type(value))
for key in person:
print(type(key))
#worked----------------------------------------------------------------
for j in person.values():
print(type(j))
my_list = ["blue","yellow","green","white",1,True]
my_list.append(30)
print(my_list)
print('My favorite color is', my_list[1])
print('I have {} pet(s).'.format(my_list[4]))
if my_list[5]==True:
print("I have previous programming experience")
else:
print("I do not have previous programming experience")
my_list.pop(0)
print("The list has {} elements.".format(len(my_list)))
| true |
59a8c9b981bb0203fae5aabe709451ef4706a7c5 | edpretend/learn_python | /defs/def_txt.py | 1,264 | 4.34375 | 4 | """文本处理函数库"""
def watch_txt(filename):
"""watch txt and read"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
message = "Sorry, the file " + filename + " does not exist."
print(message)
else:
print(contents)
def word_time(filename):
"""read one word of all time"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
message = "Sorry, the file " + filename + " does not exist."
print(message)
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about" + str(num_words) +
" words.")
def one_word_time(filename, word):
"""read one word of all time"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
message = "Sorry, the file " + filename + " does not exist."
print(message)
else:
word_time = contents.lower().count(str(word))
print("The word '" + str(word) + "' in the file '" + filename + "' has about " +
str(word_time) + " time.") | true |
86e7af0c89f72ae192f7c2e6936f7cbb28c47068 | Joyce-w/Python-practice | /09_is_palindrome/is_palindrome.py | 752 | 4.1875 | 4 | def is_palindrome(phrase):
"""Is phrase a palindrome?
Return True/False if phrase is a palindrome (same read backwards and
forwards).
>>> is_palindrome('tacocat')
True
>>> is_palindrome('noon')
True
>>> is_palindrome('robert')
False
Should ignore capitalization/spaces when deciding:
>>> is_palindrome('taco cat')
True
>>> is_palindrome('Noon')
True
"""
lowercase = phrase.lower().replace(' ', '')
lowercase_lst = list(lowercase)
reverse = list(lowercase)
reverse.reverse()
for idx in range(len(lowercase_lst)):
if lowercase[idx] != reverse[idx]:
return False
else:
return True
| true |
fcc5cb61e1df70e4020dc3c6f25b76c55ba07533 | alisson-fs/POO-II | /Lista de exercicios 1/Q2.py | 2,729 | 4.15625 | 4 | #Aluno: Alisson Fabra da Silva Matricula: 19200409
'''Neste exercício criei uma classe Biblioteca que recebe os livros que vão estar disponiveis
e criei a classe livro, que recebe todas as cadacteristicas de cada livro.'''
class Biblioteca:
def __init__(self, livros: list):
self.__livros = livros
self.__livros_emprestados = []
def pegar_livro(self, titulo):
for i in self.__livros:
if i.titulo == titulo:
self.__livros.remove(i)
self.__livros_emprestados.append(i)
print('Livro emprestado com sucesso!')
def devolver_livro(self, titulo):
for i in self.__livros_emprestados:
if i.titulo == titulo:
self.__livros.append(i)
self.__livros_emprestados.remove(i)
print('Livro devolvido com sucesso!')
def pesquisar_livro(self, titulo):
possui_livro = False
for i in self.__livros:
if i.titulo == titulo:
possui_livro = True
print(f'Titulo: {i.titulo}')
print('Autores:', end=' ')
for j in range(len(i.autores)):
if j < len(i.autores) - 1:
print(f'{i.autores[j]}', end=', ')
else:
print(f'{i.autores[j]}.')
print(f'Ano: {i.ano} \n Editora: {i.editora} \n Edição: {i.edicao} \n Volume: {i.volume}')
if possui_livro == False:
print('Não possuimos este livro.')
class Livros:
def __init__(self, titulo: str, autores: list, ano: int, editora: str, edicao: str, volume: int):
self.__titulo = titulo
self.__autores = autores
self.__ano = ano
self.__editora = editora
self.__edicao = edicao
self.__volume = volume
@property
def titulo(self):
return self.__titulo
@property
def autores(self):
return self.__autores
@property
def ano(self):
return self.__ano
@property
def editora(self):
return self.__editora
@property
def edicao(self):
return self.__edicao
@property
def volume(self):
return self.__volume
def main():
lista_livros = []
lista_livros.append(Livros('Calculo', ['Descartes', 'Pitagoras', 'Arquimedes',], 2000, 'Matemática é vida', '10', 1))
lista_livros.append(Livros('Harry Potter e a Pedra Filosofal', ['J. K. Rowling'], 1997, 'Rocco', '1', 1))
BU = Biblioteca(lista_livros)
BU.pegar_livro('Calculo')
BU.pesquisar_livro('Calculo')
BU.devolver_livro('Calculo')
BU.pesquisar_livro('Calculo')
BU.pesquisar_livro('Harry Potter e a Pedra Filosofal')
main() | false |
a53af1d873b2238aa568577ae9ebd48bd7d8a846 | rgederin/python-sandbox | /python-code/src/collections/set.py | 2,859 | 4.46875 | 4 | x = {'foo', 'bar', 'baz', 'foo', 'qux', 'bar'}
print(type(x))
print(x)
x = set(['foo', 'bar', 'baz', 'foo', 'qux'])
print(type(x))
print(x)
x = set(('foo', 'bar', 'baz', 'foo', 'qux'))
print(type(x))
print(x)
_str = "quux"
print(list(_str))
print(set(_str))
# A set can be empty. However, recall that Python interprets empty curly braces ({}) as an empty dictionary,
# so the only way to define an empty set is with the set() function
x = set()
print(type(x))
print(x)
x = {}
print(type(x))
print(x)
# You might think the most intuitive sets would contain similar objects—for example, even numbers or surnames:
s1 = {2, 4, 6, 8, 10}
s2 = {'Smith', 'McArthur', 'Wilson', 'Johansson'}
# Python does not require this, though. The elements in a set can be objects of different types:
x = {42, 'foo', 3.14159, None}
print(x)
# Don’t forget that set elements must be immutable. For example, a tuple may be included in a set:
x = {42, 'foo', (1, 2, 3), 3.14159}
print(x)
# The len() function returns the number of elements in a set, and the in and not in operators can be used to test for
# membership:
x = {'foo', 'bar', 'baz'}
print(len(x))
print('bar' in x)
print('qux' in x)
## Operating on a Set
# Given two sets, x1 and x2, the union of x1 and x2 is a set consisting of all elements in either set.
x1 = {'foo', 'bar', 'baz'}
x2 = {'baz', 'qux', 'quux'}
print(x1 | x2)
# Set union can also be obtained with the .union() method. The method is invoked on one of the sets, and the other is
# passed as an argument:
print(x1.union(x2))
# The way they are used in the examples above, the operator and method behave identically. But there is a subtle
# difference between them. When you use the | operator, both operands must be sets. The .union() method, on the other
# hand, will take any iterable as an argument, convert it to a set, and then perform the union.
y = x1.union(('baz', 'qux', 'quux'))
print(y)
# Below is a list of the set operations available in Python. Some are performed by operator, some by method,
# and some by both. The principle outlined above generally applies: where a set is expected, methods will typically
# accept any iterable as an argument, but operators require actual sets as operands.
# x1.intersection(x2[, x3 ...])
x1 = {'foo', 'bar', 'baz'}
x2 = {'baz', 'qux', 'quux'}
print(x1.intersection(x2))
print(x1 & x2)
# x1.difference(x2[, x3 ...])
print(x1.difference(x2))
print(x1 - x2)
# Modifying a Set
# Although the elements contained in a set must be of immutable type, sets themselves can be modified. Like the
# operations above, there are a mix of operators and methods that can be used to change the contents of a set.
x1 = {'foo', 'bar', 'baz'}
x2 = {'foo', 'baz', 'qux'}
x1 |= x2
print(x1)
x1.update(['corge', 'garply'])
print(x1)
x = {'foo', 'bar', 'baz'}
x.add('qux')
print(x) | true |
113acba3954da223bf206b2f3c61df537db7f878 | syedareehaquasar/Python_Interview_prepration | /Hashing_Questions/is_disjoint.py | 982 | 4.21875 | 4 | Problem Statement
You have to implement the bool isDisjoint(int* arr1, int* arr2, int size1, int size2) function, which checks whether two given arrays are disjoint or not.
Two arrays are disjoint if there are no common elements between them. The assumption is that there are no duplicate elements in each array.
Input
Two arrays of integers and their lengths.
Output
It returns true if the two arrays are disjoint. Otherwise, it returns false.
arr_one = [4,5,6,9,8]
arr_two = [0,3]
def is_subset(arr_one, arr_two):
len_one = len(arr_one)
len_two = len(arr_two)
arr_one_hash = {}
for value in arr_one:
arr_one_hash[ value ] = 1
#print( arr_one, arr_two, arr_one_hash)
'''for value in arr_two:
if not arr_one_hash.get(value):
return True'''
if not any( arr_one_hash.get( value) for value in arr_two ): return True
else: return False
print ( is_subset(arr_one, arr_two))
| true |
f4b23e71cb3395d3f90a8f823407ddea41724000 | shreyasandal05/HelloWorld | /utils.py | 203 | 4.1875 | 4 | def find_max(numbers):
"""This prints maximum number within a list"""
maximum = numbers[0]
for number in numbers:
if maximum < number:
maximum = number
print(maximum)
| true |
01d4b92425ebe77a583c5c6b7ea257deeac918ce | pspencil/cpy5python | /practical02/q04_determine_leap_year.py | 245 | 4.28125 | 4 | #Filename:q04_determine_leap_year.py
#Author:PS
#Created:201302901
#Description:To determine whether a year is a leap year
year=int(input("Enter a year: "))
if (year%4==0 and year%100!=0) or year%400==0:
print("Leap")
else:
print("Not leap")
| false |
21334ff4ca556f71bdba054c54693575d5d94bfc | Yesid4Code/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 2,921 | 4.5625 | 5 | #!/usr/bin/python3
""" A Square class definition """
class Square:
""" Initialization of the class """
def __init__(self, size=0, position=(0, 0)):
""" Initialization of the class """
self.size = size
self.position = position
def area(self):
""" Calculate the square's area """
return self.__size ** 2
@property
def size(self):
""" The size of the square """
return self.__size
@size.setter
def size(self, value):
""" Set the size of the square and check if it's >= 0 """
if type(value) is not int:
raise TypeError("size must be an integer")
if value < 0:
raise ValueError("size must be >= 0")
self.__size = value
@property
def position(self):
""" The position of the Square """
return self.__position
@position.setter
def position(self, value):
"""setter of __position
Args:
value (tuple): position of the square in 2D space
Returns:
None
"""
if type(value) is not tuple:
raise TypeError("position must be a\
tuple of 2 positive integers")
elif len(value) != 2:
raise TypeError("position must be a\
tuple of 2 positive integers")
elif type(value[0]) is not int or type(value[1]) is not int:
raise TypeError("position must be a\
tuple of 2 positive integers")
elif value[0] < 0 or value[1] < 0:
raise TypeError("position must be a\
tuple of 2 positive integers")
else:
raise TypeError("position must be a\
tuple of 2 positive integers")
# if type(value) != tuple or len(value) != 2 or \
# type(value[0]) != int or value[0] < 0 or \
# type(value[1]) != int or value[1] < 0:
# raise TypeError("position must be a\
# tuple of 2 positive integers")
# else:
# self.__position = value
def my_print(self):
""" prints in stdout the square with the character # """
if self.__size > 0:
print("\n" * self.__position[1], end="")
for i in range(self.__size):
print(" " * self.__position[0], end="")
print("#" * self.__size)
else:
print()
| true |
168d8066d57bbf9e622187a32f93bd123531092d | AJKemps/cs-module-project-recursive-sorting | /src/sorting/sorting.py | 1,320 | 4.3125 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(left, right):
# elements = len(left) + len(right)
# merged_arr = [0] * elements
merged_arr = []
# Your code here
left_point = right_point = 0
while left_point < len(left) and right_point < len(right):
if left[left_point] < right[right_point]:
merged_arr.append(left[left_point])
left_point += 1
else:
merged_arr.append(right[right_point])
right_point += 1
merged_arr.extend(left[left_point:])
merged_arr.extend(right[right_point:])
return merged_arr
# TO-DO: implement the Merge Sort function below recursively
def merge_sort(arr):
# Your code here
if len(arr) <= 1:
return arr
midpoint = len(arr) // 2
left, right = merge_sort(arr[:midpoint]), merge_sort(arr[midpoint:])
return merge(left, right)
# STRETCH: implement the recursive logic for merge sort in a way that doesn't
# utilize any extra memory
# In other words, your implementation should not allocate any additional lists
# or data structures; it can only re-use the memory it was given as input
def merge_in_place(arr, start, mid, end):
# Your code here
pass
def merge_sort_in_place(arr, l, r):
# Your code here
pass
| true |
5e653857300e785e7c2755977af5951cbd0bc909 | HeyMikeMarshall/GWARL-Data | /03-Python/2/Activities/01-Stu_QuickCheckup/Solved/quick_check_up.py | 483 | 4.15625 | 4 | # Print Hello User!
print("Hello User!")
# Take in User Input
hru = input("How are you doing today?")
# Respond Back with User Input
print(f"I am glad to hear you are {hru}.")
# Take in the User Age
age = int(input("If you don't mind my asking, how old are you?"))
# Respond Back with a statement based on age
if (age > 50):
print("dang, you're old!")
elif (age < 5):
print("are you allowed to be using the computer?")
else: print(f"Ah, {age}, a good age to be.")
| true |
d8e26246147eeb15860e2946038dea1519814e13 | truongpt/warm_up | /practice/python/study/linked_list.py | 1,004 | 4.1875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def prepend(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def insert_after_node(self, pre_node, data):
if not pre_node:
print("Previous node is not existence")
return
new_node = Node(data)
new_node.next = pre_node.next
pre_node.next = new_node
def print(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
| true |
33de70bb95f336872fccd00f1445e1d8e8bc14d1 | abhiwalia15/practice-programs | /num_divisible_by_another_num.py | 271 | 4.4375 | 4 | # Python Program to find numbers divisible by thirteen from a list using anonymous function
# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,13]
def num_divisible_by_num(n):
for i in my_list:
if (i%n == 0):
print(i)
num_divisible_by_num(13)
| false |
d74f64f71ca96b45315053e9dc379be4c6e2384b | andrewermel/curso-em-video | /chefao 37.py | 676 | 4.25 | 4 | #escreva um programa que leia um numero interio qualquer e peça para o usuario escolher qual sera a base de conversão:
# 1 para binario
# 2 para octal
# 3 para hexadecimal
# exercicio
num=int(input('digite um numero inteiro:'))
print('''Escolha uma das bases para conversão:
[1] converter para BINARIO
[2] converter para OCTAL
[3] converter para HEXADECIMAL''')
op= int(input('Sua opção:'))
if op== 1:
print('{} convertido para BINARIO é igual {}'.format(num, bin(num)[2:]))
elif op==2:
print('{} convertido para OCTAL é igual a {}'.format(num, oct(num)[2:]))
elif op== 3:
print('{} convertido para HEXADECIMAL é igual a {}'.format(num, hex(num)[2:]))
| false |
837417ff10a136800d60313bca2657459e48b71b | sailskisurf23/sidepeices | /prime.py | 556 | 4.28125 | 4 | #Ask user for Inputs
userinput1 = int(input("This program determines primality. Enter an integer greater than 0: "))
#Define function that returns divisors of a number
def divisor(number):
divisors = []
for x in range(1, (number+1)):
if number % x == 0:
divisors.append(x)
return divisors
#apply divisor function to userinput1
divlist = divisor(userinput1)
#Print primality of userinput1
if len(divlist) <= 2 :
print(str(userinput1) + " is a prime number")
else:
print(str(userinput1) + " is NOT a prime number")
| true |
bf34ef2231cd514deb40a267976b5b7ede184893 | sailskisurf23/sidepeices | /factorial.py | 337 | 4.21875 | 4 | uservar = int(input("Enter an integer you would like to factorialize: "))
def factorialize(var1):
"""Returns the factorial of var1"""
counter = 1
result = 1
while counter <= var1:
result = result * counter
counter = counter + 1
return result
print(str(uservar) +"! = " + str(factorialize(uservar)))
| true |
5e30f36955b95279a0e0c9cded56c35cf7d67184 | sailskisurf23/sidepeices | /dice.py | 2,879 | 4.34375 | 4 | #1. Write a function that rolls two sets of dice to model players playing a game with dice.
#It will accept two arguments, the number of dice to roll for the first player, and the number of dice to roll
#for the second player. Then, the function will do the following:
#* Model rolling the appropriate number of dice for each player.
#* Sum the total values of the corresponding dice rolls.
#* Print which player rolled the higher total.
#* Return the total sum of each players rolls in a tuple.
#Add functionality to Game
#Adjust game for any number of players
#Ask user how many players there are
#For each player ask how many rolls they get and then print each roll along with their sum
#After last player, print winner(s)
#Ask user if they want to play again
import random
import sys
def rolls_result(numrolls):
'''Roll a 6 sided die 'numrolls' times, returns sum of rolls and list of results'''
sumrolls = 0
result_list = []
for i in range(numrolls):
result = random.randint(1,6)
sumrolls += result
result_list.append(result)
return sumrolls, result_list
def dice(playerscores):
'''Input the score for each player, return list of winner(s)'''
maxscore = max(playerscores)
winnerlist = []
for i in range(len(playerscores)):
if playerscores[i] == maxscore:
winnerlist.append(f"Player{i+1}")
return winnerlist
def winnerstring(winnerlist):
'''Input the list of winners, return a string exclaiming the winner1(s)'''
if len(winnerlist) == 1:
return f"{winnerlist[0]} is the winner!!!"
elif len(winnerlist) > 1:
winstring = " are winners!!!"
for i in winnerlist:
winstring = i + ", " + winstring
return winstring
else:
return "Something's wrong, there are no winners..."
if __name__ == '__main__':
#Ask user if they want to play ()
playagain = 'y'
while playagain == 'y':
playagain = input("Would you like to play a game of dice? (y/n): ")
if playagain == 'n':
print("Goodbye!")
sys.exit()
#Ask user for number of players
num_of_players = int(input("Input number of players: "))
print("Thanks!")
#Ask user how many times each player rolls;
#Show them their score
numrollslist = []
playerscores = []
for x in range(1,num_of_players+1):
numrolls = int(input(f"Input number of times Player{x} rolls: "))
numrollslist.append(numrolls)
score = rolls_result(numrolls)
playerscores.append(score[0])
print(score)
#Determine winners
winnerlist = dice(playerscores)
#Print list of winners
print("The scores are: " + str(playerscores))
print(winnerstring(winnerlist))
print("")
| true |
9fa447c3fae1328014bd7775bd7688bb16b2a180 | KSVarun/Coding-Challanges | /remove_consonents.py | 825 | 4.1875 | 4 | # Given a string s, remove all consonants and prints the string s that contains vowels only.
# Input: The first line of input contains integer T denoting the number of test cases. For each test case, we input a string.
# Output: For each test case, we get a string containing only vowels. If the string doesn't contain any vowels, then print "No Vowel"
# Constraints:
# 1<=T<=100
# The string should consist of only alphabets.
# Examples:
# Input: geEks
# Output: eE
# Input: what are you doing
# Output: a ae ou oi
def removecons(st):
vowels = ["a", "i", "u", "o", "e"]
for x in st:
if x.lower() not in vowels and x != " ":
st = st.replace(x, "")
if st:
return(st)
else:
return("No Vowel")
for _ in range(int(input())):
st = input()
print(removecons(st))
| true |
879904d1eb93a81fde6a938d5802df3fb36094ff | ToWorkit/Python_base | /错误处理/try.py | 967 | 4.1875 | 4 | try:
print('try')
# 注意差看区别
# r = 10 / 0
r = 10 / 2
print('result:', r)
except ZeroDivisionError as e:
print('except: ', e)
finally:
print('finally')
print('END')
print('-----------------------------')
# 多个except捕获不同类型的错误
try:
print('try')
r = 10 / int('5')
print('result:', r)
except ValueError as e:
print('ValueError:', e)
# 运算错误
except ZeroDivisionError as e:
print('ZeroDivisionError:', e)
else:
print('No Error')
finally:
print('finally')
print('END')
print('------------------')
# Python的错误其实也是class,所有的错误类型都继承自BaseException,所以在使用except时需要注意的是,它不但捕获该类型的错误,还把其子类也“一网打尽”
def foo(s):
return 10 / int(s)
def bar(s):
print(foo(s) * 2)
def main():
try:
bar('2')
except Exception as e:
print('Error:', e)
finally:
print('Finally')
main()
| false |
847252b2b65da4adf71fedb141400e8f74d97e5e | remon/pythonCodes | /python_bacics_101/Arithemtic_operators_en.py | 2,020 | 4.21875 | 4 | # Examples on how to uses Python Arithmetic Operators
'''
What is the operator in Python?
Operators are special symbols in Python that carry out arithmetic or logical computation.
The value that the operator operates on is called the operand.
for example: 2 + 3 = 5
Here, + is the operator that performs addition.
2 and 3 are the operands and 5 is the output of the operation.
what is Arithmetic Operators means ?
Operator | Description
-----------------------------------------------
+ Addition | Adds values on either side of the operator.
- Subtraction | Subtracts right hand operand from left hand operand.
* Multiplication | Multiplies values on either side of the operator
/ Division | Divides left hand operand by right hand operand
% Modulus | Divides left hand operand by right hand operand and returns remainder
** Exponent | Performs exponential (power) calculation on operators
// Floor Division | he division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero
when do we use it ?
we use this kind of every where form basic math operation to loops or condition statements
'''
from __future__ import print_function
a = 20 ; b = 10
# Addition operator
c = a + b
print("Addition value =" , c)
# Subtraction operator
c = a - b
print("Subtraction value = " , c)
# Multipliction operator
c = a * b
print("Multipliction value = " , c)
# Division operator
c = a / b
print("Division value = " , c)
# Mod operator
c = a % b
print("Mod value = " , c)
# Exponent or power operator
a = 2 ; b = 3
c = a ** b
print("Exponent value = " , c)
# floor Division or integer division operator
'''
Note :
In Python 3 the division of 5 / 2 will return 2.5 this is floating point division
the floor Division or integer divisio will return 2 mean return only the integer value
'''
a = 9 ; b = 4
c = a // b
print("Integer Division value = " , c)
| true |
fb6b67ad09585fe97647f5fc40bf1934a4e7dfd7 | remon/pythonCodes | /Lists/List_Methods/append_en.py | 1,291 | 4.75 | 5 | #added by @Azharoo
#Python 3
"""
The append() method adds an item to the end of the list.
The item can be numbers, strings, another list, dictionary etc.
the append() method only modifies the original list. It doesn't return any value.
"""
#Example 1: Adding Element to a List
my_list = ['python', 'codes', 1, 2, 3]
my_list.append('Azharo')
print (my_list) #['python', 'codes', 1, 2, 3, 'Azharo']
#Example 2: Adding List to a List
aList = [123, 'xyz', 'abc', 78];
bList = [2018, 'Lolo'];
aList.append(bList)
print ("Updated List : ", aList ) #Updated List : [123, 'xyz', 'abc', 78, [2018, 'Lolo']]
""" Notes
1) The difference between append and extend
append:
Appends any Python object as-is to the end of the list (i.e. as a last element in the list).
The resulting list may be nested and contain heterogeneous elements (i.e. list, string, tuple, dictionary, set, etc.)
extend:
Accepts any iterable as its argument and makes the list larger.
The resulting list is always one dimensional list (i.e. no nesting) and it may contain heterogeneous elements in it (e.g. characters, integers, float) as a result of applying list(iterable).
2) Similarity between append and extend
Both takes exactly one argument.
Both modify the list in-place.
As a result, both returns None
""" | true |
1a9fa90752b2629767100945f27c5bffa4a9807f | remon/pythonCodes | /Turtle/draw_rectangle_en.py | 755 | 4.5625 | 5 | #added by @Azharoo
#Python 3
#draw a simple rectangle
# Example - 1
import turtle
t = turtle.Turtle()
window = turtle.Screen()
window.bgcolor("black")
t.hideturtle()
t.color("red")
def slanted_rectangle(length,width):
for steps in range(2):
t.fd(width)
t.left(90)
t.fd(length)
t.left(90)
slanted_rectangle(length=200,width=100)
# Example - 2
#draw a slanted rectangle
import turtle
t = turtle.Turtle()
window = turtle.Screen()
window.bgcolor("black")
t.hideturtle()
t.color("red")
def slanted_rectangle(length,width,angle):
t.setheading(angle)
for steps in range(2):
t.fd(width)
t.left(90)
t.fd(length)
t.left(90)
slanted_rectangle(length=200,angle=45,width=100) | false |
0a78a10b44750efbf098df50ab885e38eb12058e | remon/pythonCodes | /Functions/python_exmple_fibonacci_en.py | 641 | 4.375 | 4 | #this file print out the fibonacci of the function input
#importing numpy for execute math with lists
import numpy as np
#define the function that takes one input
def fibonacci_cube(num):
#define a list that contains 0 and 1 , because the fibonacci always starts with 0 and 1
lis = [0,1]
#this for loop takes the range of the parameter and 2
for i in range(2,num):
#appending the sum of the previuos two numbers to the list
lis.append(lis[i-2] + lis[i-1])
#finally returning the cube of the fibonacci content
return np.array(lis)**3
#calling the function with 8 as an example
print fibonacci_cube(8)
| true |
6c568207157997c04d5aacba36d8dfdb911dd03b | remon/pythonCodes | /Lists/List_Methods/reverse_ar.py | 1,918 | 4.90625 | 5 | #added by @Azharoo
#Python 3
"""
The reverse() يعكس عناصر قائمة محددة.
The reverse() لا تأخذ أي عوامل.
The reverse() لا يعيد أي قيمة. يقوم فقط عكس العناصر وتحديث القائمة.
"""
#مثال 1 : Reverse a List
# Operating System List
os = ['Windows', 'macOS', 'Linux']
print('Original List:', os)
# List Reverse
os.reverse()
# updated list
print('Updated List:', os)
#Example 2: Reverse a List Using Slicing Operator
# Operating System List
os = ['Windows', 'macOS', 'Linux']
print('Original List:', os)
# Reversing a list
#Syntax: reversed_list = os[start:stop:step]
reversed_list = os[::-1]
# updated list
print('Updated List:', reversed_list)
#Example 3: Accessing Individual Elements in Reversed Order
# Operating System List
os = ['Windows', 'macOS', 'Linux']
# طباعة القائمة بشكل معكوس
for o in reversed(os):
print(o)
# مثال 4 : (شرح الاستاذ الفاضل ريمون )
def my_f(list):
list1 = list.reverse()
return list1
list =[10,20,40]
print(my_f(list)) ## الناتج هنا None
def my_f(list):
list1 = list.reverse()
return list
list =[10,20,40]
print(my_f(list))## [40, 20, 10]
"""
لماذا الناتجين مختلفين
ببساطة
فى المرة الاولى
reverse()
هى قامت بالتعديل على القائمة لكن لاتقوم باخراج القائمة الجديدة
لكن تم التعديل بالفعل على القائمة واذا تمت طباعة القائمة نجد ان
قيم العناصر قد انقلبت بالعكس
وهو ماحدث فى الكود الحالى عندما قمنا بارجاع قيمة القائمة
وتمت طباعة القيمة بالفعل
بينما فى المرة الاولى … ما طلبنا اخراجه هو العملية نفسها … وليست القيمة
"""
| false |
591ce87b8211499434dc4f19086d6a8eb042f843 | remon/pythonCodes | /Functions/strip_en.py | 618 | 4.25 | 4 | #strip() returns a copy of the string
#in which all chars have been stripped
#from the beginning and the end of the string
#lstrip() removes leading characters (Left-strip)
#rstrip() removes trailing characters (Right-strip)
#Syntax
#str.strip([chars]);
#Example 1
#print Python a high level
str = "Python a high level language";
print str.strip( 'language' )
#Examlpe 2
str = "Python a high level language , Python")
#print a high level language ,
print str.strip("Python")
#print a high level language , Python
print str.lstrip("Python")
#print Python a high level language ,
print str.rstrip("Python")
| true |
57e7fdb1ff3591f58ec76cf85638980d3f5a6171 | remon/pythonCodes | /Lists/comprehensions_en.py | 1,012 | 4.5625 | 5 |
# Added by @ammarasmro
# Comprehensions are very convenient one-liners that allow a user to from a
# whole list or a dictionary easily
# One of the biggest benefits for comprehensions is that they are faster than
# a for-loop. As they allocate the necessary memory instead of appending an
# element with each cycle and reallocate more resources in case it needs them
sample_list = [x for x in range(5)]
print(sample_list)
# >>> [0,1,2,3,4]
# Or to perform a task while iterating through items
original_list = ['1', '2', '3'] # string representations of numbers
new_integer_list = [int(x) for x in original_list]
# A similar concept can be applied to the dictionaries
sample_dictionary = {x: str(x) + '!' for x in range(3) }
print(sample_dictionary)
# >>> {0: '0!', 1: '1!', 2: '2!'}
# Conditional statements can be used to preprocess data before including them
# in a list
list_of_even_numbers = [x for x in range(20) if x % 2 == 0 ]
print(list_of_even_numbers)
# >>> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
| true |
aa3f18d2d26c103253f0df89c11c30c5bd9a754e | vdn-projects/omnilytics-challenge | /read_print_data.py | 998 | 4.125 | 4 | import os
def is_float(obj):
"""
Check if object is float datatype or not
Args:
obj: input object in string
Returns:
True if it is float, else False
"""
try:
float(obj)
except ValueError:
return False
return True
if __name__=="__main__":
base_path = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(base_path, "output.txt")
with open(file_path, "r") as f:
content = f.read()
objs = [obj.strip() for obj in content.split(",")]
for obj in objs:
if obj.isnumeric():
result = f"{obj} - integer"
elif obj.isalpha():
result = f"{obj} - alphabetical strings"
elif obj.isalnum():
result = f"{obj} - alphanumeric"
elif is_float(obj):
result = f"{obj} - real number"
else:
raise ValueError(f"Unknown object type: '{result}', please check your code.")
print(result) | true |
0858e00dbefe600268bf106ce92459396828b6f8 | laineyr19/MAGIC | /Week 3/text_based_adventure_game-2/game_02.py | 317 | 4.15625 | 4 | def main():
'''Getting your name'''
play_name=(raw_input("What's your name? > "))
play_age=(raw_input("enter your age? >"))
print ("hi"+" "+play_name)
result="my name is {name} and my age is {age}".format (name=play_name, age=play_age)
print(result)
if __name__ == '__main__':
main() | true |
7264c06c4327d762d4f072a4c903cc6fd79cf3c4 | krishnachouhan/calculator | /calculator/sum.py | 1,200 | 4.25 | 4 | # Sum Module
def sum(a, b, verbose=0):
'''
Writing this Sample doc. This is useful as when you type __doc(sum)__, this text is printed.
hence its a good practice to use this.
Here,
- parameters are to be explained.
- return values are to be explained.
- finally, dependencies are to explained
'''
try:
return a+b
except:
if verbose==1:
print("a+b Couldn't be done simply, Trying other alternaives.")
temp=None
try:
if verbose==2:
print("""Second level of Verbose here we are explaining the simply preformed operations.
a+b Couldn't be done simply, Trying other alternaives, as this mmight be a list.""")
if type(a[0])==type(''):
temp=''
if type(a[0])==type(0):
temp=0
for i in a:
if type(i)==type(0):
temp = temp + i
elif type(i)==type(''):
temp = str(temp)+i
except:
if verbose==1:
print("""Possible Unsupported operation, please check the variable-type.""")
return a+b | true |
60a15f880a910137d6c267daf14baad13a638fc3 | abramova-alex/first | /Fourth.py | 546 | 4.28125 | 4 | #Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit and print out the converted temperature.
celsius = raw_input('Print temperature in Celsius: ')
celsius = float(celsius)
fahrenheit = celsius * 9 / 5 + 32
print 'In Celsius', celsius, ' converting to', fahrenheit, 'in Fahrenheit\n'
fahrenheit = raw_input('Print temperature in Fahrenheit: ')
fahrenheit = float(fahrenheit)
celsius = (fahrenheit - 32) * 5 / 9
print 'In Fahrenheit', fahrenheit, ' converting to', celsius, 'in Celsius\n' | false |
ee26f9872314401c7e376ac3018ef80dd5f23e58 | agandhasiri/Python-OOP | /program 4 Contest problems/everywhere.py | 996 | 4.15625 | 4 | Tests = int(input()) # no of test cases
len_list=[] # for length of each test case list with distinct names
for v in range(Tests): # a loop for every test case
n = int(input()) # no of work trips for each test case
list = [] # a list for distinct names
i=0
while True:
name = input() # name of the place
if name not in list: # checking for the name in the list
list.append(name) # adding that name to the list, if it is not in the list.
i+=1 # counting every trip
if n==i: # if the count is equal to n(no of trips)
break # it stops taking trip name
len_list.append(len(list)) # add length of every test case list to a new list
for j in len_list: # print length of every distinct names list
print(j)
| true |
218275d05a30d062ce99d9dd2f4cb2dea08523ca | xhemilefr/ventureup-python | /exercis5.1.py | 314 | 4.21875 | 4 | def reverse_string(string):
reversed_string = ""
for x in string:
reversed_string = x + reversed_string
return reversed_string
def check_palindrome(string):
temp = string.lower()
if temp == reverse_string(temp):
return True
return False
print(check_palindrome("Pasddsap")) | true |
0b8a3bfb2f1514d77b83bf94c59fefb20f1b5bd8 | mabbott2011/PythonCrash | /conditionals.py | 536 | 4.125 | 4 | # Conditionals
x = 4
#basic if
if x < 6:
print('This is true')
#basic If Else
y = 1
if y > 6:
print("This is true")
else:
print("This is false")
# Elif
color = 'red'
#color = 'blue'
#color = 'purple'
if color == 'red':
print('Color is red')
elif color == 'blue':
print('Color is blue')
else:
print('Color is neither red or blue')
#Nested if
if color == 'red':
if x < 10:
print('This is true')
#But lets write this better
if color == 'red' and x < 10:
print('This is a true statement')
| true |
63b4bdc7b80b17cd676b6c404c15a9ccb27f6d7e | ADcadia/py-calc | /coin-toss-calculator.py | 474 | 4.125 | 4 | # Enter the number of times you will toss the coin.
import random
def tossCoin():
num = random.randint(0, 1)
if num == 0:
return "Heads"
else:
return "Tails"
timesToToss = int(input("How many times will you toss the coin? \n"))
headsCounter = 0
tailsCounter = 0
for i in range(timesToToss):
if tossCoin() == "Heads":
headsCounter = headsCounter+1
else:
tailsCounter = tailsCounter+1
print("Heads: ", headsCounter, "\nTails: ", tailsCounter)
| true |
8c396abb6742f4e88cd68d47c057420fb5f3f253 | stoneboyindc/udacity | /P1/problem_2.py | 1,862 | 4.4375 | 4 | import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
result = []
try:
listDirs = os.listdir(path)
for i in listDirs:
item = os.path.join(path, i)
if os.path.isdir(item):
result += find_files(suffix, item)
if os.path.isfile(item):
if item.endswith(suffix):
result.append(item)
except FileNotFoundError:
print (path, "does not exist.")
except NotADirectoryError:
if path.endswith(suffix):
result.append(path)
return result
## Locally save and call this file ex.py ##
# Code to demonstrate the use of some of the OS modules in python
# Test code below
# Test Case 1 - Normal case - Use provided `testdir.zip` file
print (find_files(".c", "C:\\Temp\\testdir\\testdir")) # ['C:\\Temp\\testdir\\testdir\\subdir1\\a.c', 'C:\\Temp\\testdir\\testdir\\subdir3\\subsubdir1\\b.c', 'C:\\Temp\\testdir\\testdir\\subdir5\\a.c', 'C:\\Temp\\testdir\\testdir\\t1.c']
# Test Case 2 - Edge case - Use a file as an input argument for path
print (find_files(".c", "C:\\Temp\\testdir\\testdir\\subdir1\\a.c")) # ['C:\\Temp\\testdir\\testdir\\subdir1\\a.c']
# Test Case 3 - Edge case - Use provided `testdir.zip` file but the wrong input
print (find_files(".cpp", "C:\\Temp\\testdir\\testdirX")) # [] with an error message printed out C:\\Temp\\testdir\\testdirX does not exist.
| true |
b1562cd790de07deaec97f593a6a48ec057e6214 | Rohitthapliyal/Python | /Decision statements/12.py | 328 | 4.125 | 4 | week=int(input("enter week number:\n"))
if week==1:
print("sunday")
elif week==2:
print("monday")
elif week==3:
print("tuesday")
elif week==4:
print("wednesday")
elif week==5:
print("thursday")
elif week==6:
print("friday")
elif week==7:
print("saturday")
else:
print("invalid")
| false |
b9d3484d14d0a0148a32d94715c1a30009ce3b3f | Rohitthapliyal/Python | /Python_basics/14.py | 280 | 4.15625 | 4 | import math
class Power:
x=int(input("enter any number:\n"))
y=int(input("enter base:\n"))
def show(ob):
ob.power=math.pow(ob.x*ob.y)
def output(ob):
print("power of the number is=",ob.power)
obj=Power()
obj.show()
obj.output()
| true |
fb3d6821b831097d592a05993c5f6d9d24c98706 | mepujan/IWAcademyAssignment_3_python | /algorithms_and_dataStructure/insertion_sort.py | 315 | 4.1875 | 4 | def insertion_sort(data):
for i in range(1,len(data)):
key= data[i]
j=i-1
while j >=0 and key < data[j]:
data[j+1] = data[j]
j -= 1
data[j+1] = key
data =[5,3,2,6,4,1,3,7]
print("Before Sorting = ",data)
insertion_sort(data)
print("After Sorting= ",data) | false |
c2c4f82acaa1cfa7cc082ddcdf5819a21d64f3fd | BadrChoujai/hacker-rank-solutions | /Python/13_Regex and Parsing/Re.findall() & Re.finditer().py | 1,211 | 4.125 | 4 | # Problem Link: https://www.hackerrank.com/challenges/re-findall-re-finditer/problem
# ----------------------------------------------------------------------------------
import re
m = re.findall(r'(?i)(?<=[^aeiou])[aeiou]{2,}(?=[^aeiou])', input())
if len(m) > 0:
print(*m, sep = '\n')
else:
print('-1')
# (?i) is for making case insensitive
# Lookbehind:
# (?<=[expression])[pattern] #positive lookbehind
# (?<![expression])[pattern] #negative lookbehind
# (?=...) -> It is called lookahead assertion
# eg.
# Matches if ... matches next, but doesn’t consume any of the string.
# This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.
# (?<=...) -> It is called Positive Lookbehind
# eg.
# Matches if the current position in the string is preceded by a match for ... that ends at the current position.
# This is called a positive lookbehind assertion. (?<=abc)def will find a match in abcdef,
# since the lookbehind will back up 3 characters and check if the contained pattern matches.
# References:
# https://www.hackerrank.com/challenges/re-findall-re-finditer/forum/comments/88272 | true |
2ecded57167e4ff843aea14dcc97e141de899a38 | Sunil-Archive-Projects/Python-Experiments | /Python_Basics/classes.py | 370 | 4.1875 | 4 | #defining classes
class myClass():
def firstMethod(self):
#self refers to itself
print("First Method")
def secondMethod(self,str):
#self refers to itself
print "Second Method",str
#defining subclasses
# subClass inherits superClass myClass
class subClass(myClass):
x=0
def main():
obj=subClass()
obj.firstMethod()
obj.secondMethod("Arg1")
main()
| true |
063d16a81a5348f33bc809d857d7ad71d16ee58c | elmasria/mini-flow | /src/linear.py | 689 | 4.25 | 4 | from neuron import Neuron
class Linear(Neuron):
def __init__(self, inputs, weights, bias):
Neuron.__init__(self, inputs)
# NOTE: The weights and bias properties here are not
# numbers, but rather references to other neurons.
# The weight and bias values are stored within the
# respective neurons.
self.weights = weights
self.bias = bias
def forward(self):
"""
Set self.value to the value of the linear function output.
Your code goes here!
"""
self.value = self.bias.value
for w, x in zip(self.weights, self.inbound_neurons):
self.value += w.value * x.value
| true |
bac53da6089ab51d4d094411fdcbc2a9741a50c4 | schnitzlMan/ProjectEuler | /Problem19/Problem19.py | 1,400 | 4.125 | 4 | # strategy -
#count all the days - approximately 100 * 365.25 - not too large.
#keep track of the month to add correctly
#devide the day by %7 - if no rest, sunday if you counted correctly
#count the numbers of sundays
#months = {"jan": 31, "feb": 28, "mar":31, "apr":30, "may":31, "jun":30,
# "jul": 31, "aug": 31, "sep":30, "oct":31, "nov":30, "dec":31}
daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31]
monthchar = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
dayschar = ["sun", "mon", "tue", "wed", "thu", "fri", "sat", "sun"]
days = 1 #1.1.1900 was a Monday -count Mon=1 Sun = 7
sundays = 0
for year in range(1900,2001):
#print("year ", year)
for mon in range(len(daysInMonth)):
print("year", year, "mon ", monthchar[mon], "firstDay ", dayschar[days%7])
if (days%7 == 0 and year > 1900):
sundays += 1
days += daysInMonth[mon] # next first of month
if mon == 1:
if year%4 ==0:
if year%100 != 0:
if year % 400 != 0:
days +=1
print("Schaltjahr - add 1")
# print(mon, daysInMonth[mon], days, sundays)
#print(mon, months[mon])
#days += 365
#if (i%4 == 0 ):
# days+1
# if (i%400 == 0):
# print(i)
# days += 1
print(sundays)
| true |
62f40aec64258193e15abedd7a346425bbc877b3 | pranakum/Python-Basics | /week 2/course_1_assessment_6/q8.py | 426 | 4.34375 | 4 | '''
Write code to create a list of word lengths for the words in original_str using the accumulation pattern and assign the answer to a variable num_words_list. (You should use the len function).
'''
original_str = "The quick brown rhino jumped over the extremely lazy fox"
#code
str = original_str.split()
print (str)
num_words_list = []
for word in str:
num_words_list.append(len(word))
print (num_words_list)
| true |
7e31942b56635ec1122e4ee36ae7127759ff1d29 | H-B-P/WISHK | /Resources/PYTHON/repeater.py | 593 | 4.28125 | 4 | import sys #Imports sys, the library containing the argv function
the_string=str(sys.argv[1]) #The string to repeat is the first argument given.
target_number_of_repeats=int(sys.argv[2]) #The number of repeats is the second argument given.
number_of_repeats=0 #Set this variable to zero, as there are no repeats at the start of program.
while (number_of_repeats<target_number_of_repeats):#Until the statement in the brackets is false.
print (the_string) #Output the string, again. (This section must be indented!)
number_of_repeats=number_of_repeats+1 #Add 1 to the number of repeats.
| true |
56a6965014a8d529400257f90556692bb619861d | platinum2015/python2015 | /cas/python_module/v07_nested_functions_2.py | 440 | 4.1875 | 4 | def derivative(my_function):
'''Returns a function that computes the numerical derivative of the given
function my_function'''
def df(x, h=0.0001):
return ((my_function(x+h) - my_function(x-h)) / (2*h))
return df
def f(x):
'''The mathematical function f(x) = x^3'''
return x*x*x
df = derivative(f) #f'
ddf = derivative(df) #f''
for x in range(-10, 10):
print x, f(x), df(x), ddf(x)
| true |
0b7360bdf8002a8b0c5542ea2cfa08784855be7b | platinum2015/python2015 | /cas/python_module/Day1_SampleSolutions/p02_braking_distance_SOLUTION.py | 1,095 | 4.375 | 4 | # Compute the distance it takes to stop a car
#
# A car driver, driving at velocity v0, suddenly puts on the brake. What
# braking distance d is needed to stop the car? One can derive, from basic
# physics, that
# d=0.5*v_0^2 / mu * g
#
# Develop a program for computing d using the above formula when the initial
# car velocity v0 and the friction coefficient mu are provided via the
# raw_input function.
#
# Run the program for two cases: v0 = 120 and v0 = 50 km/h, both with mu = 0.3
# (mu is dimensionless).
#
# Hint: Remember to convert the velocity from km/h to m/s before inserting the
# value in the formula!
g = 9.81 # Assigns g value
# Inputs become floats
v0_in_kmh = float(raw_input("Please enter the initial velocity(v0) in km/h "))
mu = float(raw_input("Please, enter the friction coefficient (mu) "))
# Conversion from km/h to m/s
v0 = (v0_in_kmh*1000.)/3600.
# Computes braking distance
distance = (0.5*v0**2)/(mu*g)
# Prints the result
print "The braking distance of a car traveling at %.2f km/h is %.2f m" % (v0_in_kmh, distance)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.