blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ec5b56efd27c6d6c232e3c21f80bdccba626b68b | ramlingamahesh/python_programs | /conditionsandloops/FindNumbers_Divisible by Number.py | 646 | 4.15625 | 4 | # Python Program - Find Numbers divisible by another number
print("Enter 'x' for exit.");
print("Enter any five numbers: ");
num1 = input();
if num1 == 'x':
exit();
else:
num2 = input();
num3 = input();
num4 = input();
num5 = input();
number1 = int(num1);
number2 = int(num2);
number3 = int(num3);
number4 = int(num4);
number5 = int(num5);
numbers_list = [number1, number2, number3, number4, number5,];
check_num = int(input("Enter a number to check divisibility test: "));
res = list(filter(lambda x: (x % check_num == 0), numbers_list));
print("Number divisible by",check_num,"are",res); | true |
5209c52949500091bda483d0b6b7fba199098637 | shohanurhossainsourav/python-learn | /program28.py | 341 | 4.375 | 4 | matrix = [
[1, 2, 3],
[4, 5, 6],
]
print(matrix[0][2])
# print matrix value using nested loop
matrix = [
[1, 2, 3],
[4, 5, 6],
]
for row in matrix:
for col in row:
print(col)
matrix1 = [
[1, 2, 3],
[4, 5, 6],
]
# 0 row 2nd coloumn/3rd index value changed to 10
matrix1[0][2] = 10
print(matrix1[0][2])
| true |
ff6a9327111545c69ad4f59c5b5f2878def92431 | ikki2530/holbertonschool-machine_learning | /math/0x02-calculus/10-matisse.py | 740 | 4.53125 | 5 | #!/usr/bin/env python3
"""Derivative of a polynomial"""
def poly_derivative(poly):
"""
-Description: calculates the derivative of a polynomial.
the index of the list represents the power of x that the
coefficient belongs to.
-poly: is a list of coefficients representing a polynomial
- Returns: new list of coefficients representing the derivative
of the polynomial
"""
if poly and type(poly) == list:
new_coef = []
lg = len(poly)
if lg == 1:
new_coef.append(0)
for i in range(lg):
if i != 0:
coef = poly[i]
grade = i
new_coef.append(coef * grade)
else:
return None
return new_coef
| true |
d82167ca61a739e2d8c6919137e144a987ee22a3 | ikki2530/holbertonschool-machine_learning | /math/0x00-linear_algebra/8-ridin_bareback.py | 1,123 | 4.3125 | 4 | #!/usr/bin/env python3
"""multiply 2 matrices"""
def matrix_shape(matrix):
"""
matrix: matrix to calcuted the shape
Return: A list with the matrix shape [n, m],
n is the number of rows and m number of columns
"""
lista = []
if type(matrix) == list:
dm = len(matrix)
lista.append(dm)
lista = lista + matrix_shape(matrix[0])
return lista
else:
return lista
def mat_mul(mat1, mat2):
"""
Description: performs matrix multiplication, 2D matrices
Returns: a new matrix with the results of the multiplication
if it is possible, None otherwise
"""
shape1 = matrix_shape(mat1)
shape2 = matrix_shape(mat2)
suma = 0
resultado = []
temp = []
if shape1[1] == shape2[0]:
for k in range(len(mat1)):
for i in range(len(mat2[0])):
for j in range(len(mat1[0])):
suma += mat1[k][j] * mat2[j][i]
temp.append(suma)
suma = 0
resultado.append(temp)
temp = []
return resultado
else:
return None
| true |
181117260d2bcdc404dcd55a6f51966afa880e83 | ikki2530/holbertonschool-machine_learning | /supervised_learning/0x07-cnn/0-conv_forward.py | 2,649 | 4.53125 | 5 | #!/usr/bin/env python3
"""
performs forward propagation over a convolutional layer of a neural network
"""
import numpy as np
def conv_forward(A_prev, W, b, activation, padding="same", stride=(1, 1)):
"""
- Performs forward propagation over a convolutional layer of a
neural network.
- A_prev is a numpy.ndarray of shape (m, h_prev, w_prev, c_prev) containing
the output of the previous layer, m is the number of examples,
h_prev is the height of the previous layer,
w_prev is the width of the previous layer and c_prev is the number
of channels in the previous layer.
- W is a numpy.ndarray of shape (kh, kw, c_prev, c_new) containing
the kernels for the convolution, kh is the filter height,
kw is the filter width, c_prev is the number of channels in
the previous layer and c_new is the number of channels in the output.
- b is a numpy.ndarray of shape (1, 1, 1, c_new) containing the biases
applied to the convolution.
- activation is an activation function applied to the convolution.
- padding is a string that is either same or valid, indicating the
type of padding used.
- stride is a tuple of (sh, sw) containing the strides for the convolution,
sh is the stride for the height, sw is the stride for the width.
Returns: the output of the convolutional layer.
"""
m, h_prev, w_prev, c_prev = A_prev.shape
kh, kw, c_prev, c_new = W.shape
sh, sw = stride
if padding == "same":
ph = int(((h_prev - 1)*sh + kh - h_prev) / 2)
pw = int(((w_prev - 1)*sw + kw - w_prev) / 2)
if padding == "valid":
ph = 0
pw = 0
# Add zero padding to the input image
A_padded = np.pad(A_prev, ((0, 0), (ph, ph), (pw, pw), (0, 0)))
zh = int(((h_prev + (2*ph) - kh) / sh) + 1)
zw = int(((w_prev + (2*pw) - kw) / sw) + 1)
Z = np.zeros((m, zh, zw, c_new))
for y in range(zh):
for x in range(zw):
for k in range(c_new):
vert_start = y * sh
vert_end = (y * sh) + kh
horiz_start = x * sw
horiz_end = (x * sw) + kw
a_slice_prev = A_padded[:, vert_start:vert_end,
horiz_start:horiz_end, :]
# Element-wise product between a_slice and W.
# Do not add the bias yet.
prev_s = a_slice_prev * W[:, :, :, k]
# Sum over all entries of the volume prev_s.
sum_z = np.sum(prev_s, axis=(1, 2, 3))
z1 = sum_z + b[:, :, :, k]
Z[:, y, x, k] = activation(z1)
return Z
| true |
d5435c2f2cca0098f13f5d2ca37100b58eed8515 | David-Papworth/qa-assessment-example-2 | /assessment-examples.py | 2,639 | 4.1875 | 4 | # <QUESTION 1>
# Given a word and a string of characters, return the word with all of the given characters
# replaced with underscores
# This should be case sensitive
# <EXAMPLES>
# one("hello world", "aeiou") β "h_ll_ w_rld"
# one("didgeridoo", "do") β "_i_geri___"
# one("punctation, or something?", " ,?") β "punctuation__or_something_"
def one(word, chars):
for char in chars:
word = word.replace(char, '_')
return word
# <QUESTION 2>
# Given an integer - representing total seconds - return a tuple of integers (of length 4) representing
# days, hours, minutes, and seconds
# <EXAMPLES>
# two(270) β (0, 0, 4, 30)
# two(3600) β (0, 1, 0, 0)
# two(86400) β (1, 0, 0, 0)
# <HINT>
# There are 86,400 seconds in a day, and 3600 seconds in an hour
def two(total_seconds):
days = total_seconds // 86400
total_seconds %= 86400
hours = total_seconds // 3600
total_seconds %= 3600
minutes = total_seconds // 60
total_seconds %= 60
return (days, hours, minutes, total_seconds)
print(two(86400))
# <QUESTION 3>
# Given a dictionary mapping keys to values, return a new dictionary mapping the values
# to their corresponding keys
# <EXAMPLES>
# three({'hello':'hola', 'thank you':'gracias'}) β {'hola':'hello', 'gracis':'thank you'}
# three({101:'Optimisation', 102:'Partial ODEs'}) β {'Optimisation':101, 'Partial ODEs':102}
# <HINT>
# Dictionaries have methods that can be used to get their keys, values, or items
def three(dictionary):
new_dict = {}
for key, value in dictionary.items():
new_dict[value] = key
return new_dict
# <QUESTION 4>
# Given an integer, return the largest of the numbers this integer is divisible by
# excluding itself
# This should also work for negative numbers
# <EXAMPLES>
# four(10) β 5
# four(24) β 12
# four(7) β 1
# four(-10) β 5
def four(number):
last_possible = 1
if number < 0:
number = number * -1
for x in range(2, number//2 + 1):
if number % x == 0:
last_possible = x
return last_possible
print(four(-10))
# <QUESTION 5>
# Given an string of characters, return the character with the lowest ASCII value
# <EXAMPLES>
# five('abcdef') β 'a'
# four('LoremIpsum') β 'I'
# four('hello world!') β ' '
def five(chars):
asc=1000000000
for char in chars:
asc1 = ord(char)
if asc1 < asc:
asc = asc1
return chr(asc)
print(five('LoremIpsum')) | true |
0875700b5375f46ffcb44da81fff916e10808e6d | siddarthjha/Python-Programs | /06_inheritance.py | 1,338 | 4.28125 | 4 | """
Concept of Inheritance.
"""
print('I am created to make understand the concept of inheritance ')
class Upes:
def __init__(self, i, n):
print('I am a constructor of Upes ')
self.i = i
self.n = n
print('Ok i am done bye....')
def fun(self):
print('I am a function of Upes class')
print('Function of Upes exited....')
class Cse:
def __init__(self, i, n, s):
print('I am a constructor of Cse')
self.i = i
self.n = n
self.s = s
print('Ok i am done bye.....')
def func(self):
print('I am a function of Cse class')
print('Function of Cse class exited....')
class Cit(Upes, Cse):
__c = 10
def __init__(self, i, n):
self.i = i
self.n = n
print('I am a constructor of CseOg class')
print('Ok i am done')
print('The Abstraction variable is this and its value is %d' % Cit.__c)
def func(self):
print('I am function of class CseOg(Overrided method of Cse Class)')
print('Function of CseOg class is exited....')
obj = Cit(40, 'Sid')
obj.fun()
# obj.funct()
obj.func()
print(issubclass(Cit, Cse))
print(isinstance(obj, Cit))
# print(Cit.__c) # The __c is hidden to the class
| true |
b9f0b7f7699c8834a9c3a7b287f7f68b09b100ee | GabrielByte/Programming_logic | /Python_Exersice/ex018.py | 289 | 4.34375 | 4 | '''
Make a program that calculates sine, cosine and tangent
'''
from math import sin, cos, tan, radians
angle = radians(float(input("Enter an angle: ")))
print(f"This is the result; Sine: {sin(angle):.2f}")
print(f"Cosine: {cos(angle):.2f}")
print(f"and Tangent: {tan(angle):.2f}")
| true |
45e8158ac5e78c5deea43e77bebb2773c3aee215 | GabrielByte/Programming_logic | /Python_Exersice/ex017.py | 230 | 4.1875 | 4 | '''
Make a program that calculates Hypotenouse
'''
from math import pow,sqrt
x = float(input("Enter a number: "))
y = float(input("Enter another one: "))
h = sqrt(pow(x,2) + (pow(y,2)))
print(f"This is the result {h:.2}")
| true |
38b524a20fa88a549e0926230a63571a113c6249 | tabssum/Python-Basic-Programming | /rename_files.py | 997 | 4.21875 | 4 | #!/usr/bin/python
import os
import argparse
def rename_files():
parser=argparse.ArgumentParser()
parser.add_argument('-fp','--folderpath',help="Specify path of folder to rename files")
args=parser.parse_args()
#Check for valid folderpath
if args.folderpath :
#Get files in particular folder
file_list=os.listdir(args.folderpath)
print(file_list)
os.chdir(args.folderpath)
if len(file_list) > 0:
for file_name in file_list:
#string fun translate removes second parameter ele from string
new_name=file_name.translate(None,"0123456789")
#Finally to rename files in folder os.rename
os.rename(file_name,new_name)
else:
print("Folder is empty")
else :
print("Specify Folder Name in cmd")
rename_files()
#Exception Conditione
#1.renaming file that does not exist
#2.renaming a file name to name that already exist in folder.
| true |
dbccaa5b83a7764eb172b0e1653f7f086dd7b95e | smakireddy/python-playground | /ArraysAndStrings/PrisonCellAfterNDays.py | 2,265 | 4.21875 | 4 | """"
There are 8 prison cells in a row, and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
Otherwise, it becomes vacant.
(Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.)
We describe the current state of the prison in the following way: cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0.
Given the initial state of the prison, return the state of the prison after N days (and N such changes described above.)
Example 1:
Output: [0,0,1,1,0,0,0,0]
Explanation:
The following table summarizes the state of the prison on each day:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
Example 2:
Input: cells = [1,0,0,1,0,0,1,0], N = 1000000000
Output: [0,0,1,1,1,1,1,0]
Note:
cells.length == 8
cells[i] is in {0, 1}
1 <= N <= 10^9
"""
from typing import List
# [0,1,0,1,1,0,0,1], N = 7
# 1[0,1,1,0,0,0,0,0]
# 2[0,0,0,0,1,1,1,0]
# 3[0,1,1,0,0,1,0,0]
# 4[0,0,0,0,0,1,0,0]
# 5[0,1,1,1,0,1,0,0]
# 6[0,0,1,0,1,1,0,0]
# 7[0,0,1,1,0,0,0,0]
# output [0,0,1,1,0,0,0,0]
class PrisonCellAfterNDays:
@staticmethod
def prisonAfterNDays(cells: List[int], N: int) -> List[int]:
length = len(cells)
cells_copy = cells.copy()
for i in range(N):
# print("i ->{} ".format(i))
for i in range(1, length - 1):
if cells[i - 1] == cells[i + 1]:
cells_copy[i] = 1
else:
cells_copy[i] = 0
cells_copy[0] = 0
cells_copy[length - 1] = 0
cells = cells_copy.copy()
# print("cell_copy ->{} ".format(cells_copy))
return cells_copy
if __name__ == "__main__":
# obj = PrisonCellAfterNDays()
cells = [0, 1, 0, 1, 1, 0, 0, 1]
N = 7
res = PrisonCellAfterNDays.prisonAfterNDays(cells, N)
print(res)
| true |
7d543273ad847de56beaae7761f9280640cfe012 | smakireddy/python-playground | /ArraysAndStrings/hackerrank_binary.py | 1,396 | 4.15625 | 4 | """
Objective
Today, we're working with binary numbers. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given a base- integer, , convert it to binary (base-). Then find and print the base- integer denoting the maximum number of consecutive 's in 's binary representation. When working with different bases, it is common to show the base as a subscript.
Example
The binary representation of is . In base , there are and consecutive ones in two groups. Print the maximum, .
Input Format
A single integer, .
Constraints
Output Format
Print a single base- integer that denotes the maximum number of consecutive 's in the binary representation of .
Sample Input 1
5
Sample Output 1
1
Sample Input 2
13
Sample Output 2
2
"""
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
result = ""
cnt, max = 0, 0
while n > 0:
remainder = 0 if n % 2 == 0 else 1
flag = True
n = math.floor(n / 2)
print("remainder ->", remainder)
result = str(remainder) + result
if remainder == 1 and flag:
cnt += 1
flag = True
else:
flag = False
if n != 0:
cnt = 0
if max < cnt:
max = cnt
print("Binary -> ", result)
print("Count of consecutive 1's -> ", max)
| true |
29bf475491bbb765a9e739822fe09e7e383a1fef | aototo/python_learn | /week2/week2 bisection.py | 878 | 4.15625 | 4 | print("Please think of a number between 0 and 100!")
high = 100
low = 0
nowCorrect = int(( high + low ) / 2)
print('Is your secret number '+ str(nowCorrect) + '?')
while True:
input_value = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if input_value =='l':
low = nowCorrect
nowCorrect = int((high + low)/2)
print('Is your secret number '+ str(nowCorrect) + ' ?')
elif input_value =='h':
high = nowCorrect
nowCorrect = int((high+low)/2)
print('Is your secret number '+ str(nowCorrect) + ' ?')
elif input_value =='c':
print('Game over. Your secret number was: '+str(nowCorrect))
break
else:
print('Sorry, I did not understand your input.')
print('Is your secret number '+ str(nowCorrect) + ' ?')
| true |
7bbe2bf4078108379bff6f1b4edcf1d61dad66fd | Jeremiah-David/codingchallenges | /python-cc.py | 1,363 | 4.15625 | 4 | # Write a function called repeatStr which repeats the given string
# string exactly n times.
# My Solution:
def repeat_str(repeat, string):
result = ""
for line in range(repeat):
result = result + string
return (result)
# Sample tests:
# import codewars_test as test
# from solution import repeat_str
# @test.describe('Fixed tests')
# def basic_tests():
# @test.it('Basic Test Cases')
# def basic_test_cases():
# test.assert_equals(repeat_str(4, 'a'), 'aaaa')
# test.assert_equals(repeat_str(3, 'hello '), 'hello hello hello ')
# test.assert_equals(repeat_str(2, 'abc'), 'abcabc')
# Evens times last
# Given a sequence of integers, return the sum of all the integers that have an even index, multiplied by the integer at the last index.
# If the sequence is empty, you should return 0.
def even_last(numbers):
print("input is", numbers)
count = 0
answer = []
if numbers == []:
return 0
for number in numbers:
if count%2 == 0:
answer.append(number)
print("Array before sums together", answer)
count = count + 1
findsum = sum(answer)
print("The sum of array", findsum)
x = findsum * numbers[-1]
print('should be final', x)
return x
| true |
55e74e7fa646c954cefac68cd885b63a639191a3 | attaullahshafiq10/My-Python-Programs | /Conditions and loops/4-To Check Prime Number.py | 646 | 4.1875 | 4 | # A prime number is a natural number greater than 1 and having no positive divisor other than 1 and itself.
# For example: 3, 7, 11 etc are prime numbers
# Other natural numbers that are not prime numbers are called composite numbers.
# For example: 4, 6, 9 etc. are composite numbers
# Code
num = int(input("Enter a number: "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number") | true |
bb69af4b9a1f55be425c9dbd16d19768cef3345d | winkitee/coding-interview-problems | /11-20/15_find_pythagorean_triplets.py | 911 | 4.28125 | 4 | """
Hi, here's your problem today. This problem was recently asked by Uber:
Given a list of numbers, find if there exists a pythagorean triplet in that list.
A pythagorean triplet is 3 variables a, b, c where a2 + b2 = c2
Example:
Input: [3, 5, 12, 5, 13]
Output: True
Here, 5^2 + 12^2 = 13^2.
"""
def findPythagoreanTriplets(nums):
# -> You always have to find exactly position in the range.
for i in range(1, len(nums) - 1):
front = nums[i - 1]
back = nums[i]
front_pow = pow(front, 2)
back_pow = pow(back, 2)
result_index = i + 1
while result_index < len(nums):
result = nums[result_index]
if pow(result, 2) == (front_pow + back_pow):
return True
result_index += 1
return False
print(findPythagoreanTriplets([3, 12, 5, 13]))
print(findPythagoreanTriplets([3, 5, 6, 11, 12, 5, 13]))
| true |
5c1c1b11dc666990e8344bf2cd5cc8e2a663d46f | winkitee/coding-interview-problems | /71-80/80_make_the_largest_number.py | 586 | 4.15625 | 4 | """
Hi, here's your problem today. This problem was recently asked by Uber:
Given a number of integers, combine them so it would create the largest number.
Example:
Input: [17, 7, 2, 45, 72]
Output: 77245217
def largestNum(nums):
# Fill this in.
print(largestNum([17, 7, 2, 45, 72]))
# 77245217
"""
class largestNumKey(str):
def __lt__(x, y):
return x + y > y + x
def largestNum(nums):
largest_num = "".join(sorted(map(str, nums), key=largestNumKey))
return '0' if largest_num[0] == '0' else largest_num
print(largestNum([17, 7, 2, 45, 72]))
# 77245217
| true |
dd07fe905d62c6de15dd052c2b54ff82de8ced23 | winkitee/coding-interview-problems | /31-40/34_contiguous_subarray_with_maximum_sum.py | 876 | 4.21875 | 4 | """
Hi, here's your problem today. This problem was recently asked by Twitter:
You are given an array of integers. Find the maximum sum of all possible
contiguous subarrays of the array.
Example:
[34, -50, 42, 14, -5, 86]
Given this input array, the output should be 137. The contiguous subarray with
the largest sum is [42, 14, -5, 86].
Your solution should run in linear time.
"""
#def max_subarray_sum(arr):
# pass
def max_subarray_sum(arr):
max_sum = float('-inf')
current_sum = max_sum
for num in arr:
if num > current_sum:
current_sum = max(num, current_sum + num)
else:
current_sum += num
max_sum = max(current_sum, max_sum)
return max_sum
print(max_subarray_sum([34, -50, 42, 14, -5, 86]))
# 137
print(max_subarray_sum([1, 1, 1, 2, 3]))
# 8
print(max_subarray_sum([-1, 1, -1, 2, -3]))
# 2
| true |
3a65bf1e00e3897174298a3dc7162b4c75c90742 | GabuTheGreat/GabuTheGreat.github.io | /challange/recursion_1.py | 467 | 4.1875 | 4 | n= int(input("Enter number the first number: "))
def isPrime(num):
"""Returns True if num is prime."""
if (num == 1) or (num % 2 == 0) or (num % 3 == 0) :
return False
if (num == 2) or (num == 3) :
return True
check_var= 5
set_var = 2
while check_var * check_var <= num:
if num % check_var == 0:
return False
check_var += set_var
set_var = 6 - set_var
return True
print(isPrime(n)) | true |
fbb50bc38f14354555cef3e2bf8cd66e2a3f9270 | toufiq007/Python-Tutorial-For-Beginners | /chapter three/while_loop.py | 412 | 4.21875 | 4 |
#loop
#while loop
# steps
# first declare a variable
# second write the while loop block
# in while loop block you must declare a condition
# find the odd and even number by using while number between 0-100
i = 0;
while i<=100:
print(f'odd number {i}')
i+=2
# find the even and even number by using while number between 0-100
i = 1;
while i<=100:
print(f'even number {i}')
i+=2
| true |
74bee5049a2462c78824fdee03bc35c9bcd6759e | toufiq007/Python-Tutorial-For-Beginners | /chapter twelve/lambda_expresion_intro.py | 512 | 4.25 | 4 |
# lambda expression --> anonymous function
# it means when a function has no name then we called it anonymous function
# syntex
# 1: first write lambda keyword
# 2: second give the parameters
# 3: then give : and give the operator tha'ts it
def add(x,y):
return x+y
print(add(10,5))
add = lambda a,b : a+b
print(add(10,12))
# add1 = lambda x,y : x+y
# print(add1(10,10))
# print(add)
# print(add1)
# multiply = lambda a,b : a*b
# print(multiply(5,2))
# print(multiply)
| true |
4024a43132422ded8732257256bfb91b98cf3582 | toufiq007/Python-Tutorial-For-Beginners | /chapter thirteen/iterator_iterable.py | 515 | 4.21875 | 4 |
# iterator vs iterables
numbers = [1,2,3,4,5] # , tuple and string alls are iterables
# new_number = iter(numbers)
# print(next(new_number))
# print(next(new_number))
# print(next(new_number))
# print(next(new_number))
# print(next(new_number))
square_numbers = map(lambda x:x**2,numbers)
# map , filter this all build functions are iterators
# print(next(square_numbers))
# print(next(square_numbers))
# print(next(square_numbers))
# print(next(square_numbers))
# print(next(square_numbers))
| true |
e7557d739edf11756cbec9759a5e7afaefa7955e | toufiq007/Python-Tutorial-For-Beginners | /chapter two/exercise3.py | 975 | 4.125 | 4 |
# user_name,user_char = input('enter your name and a single characte ==>').split(',')
name,character = input('please enter a name and character ').split(',')
#another times
# print(f'the lenght of your name is = {len(name)}')
# print(f'character is = {(name.lower()).count((character.lower()))}')
# (name.lower()).count((character.lower()))
# print(user_name)
# print(f'the lenth of the username is = {len(user_name)}')
# char = user_name.count(user_char)
# print(f'the character in this username is = {char}')
# print(f'character count is = {user_name.count(user_char)}')
# make case insensitive method
# print(f'character count is = {user_name.upper().count(user_char.upper())}')
#remove space problem
# name => name.strip() => name.strip().lower()
# character => character.strip() => character.strip().lower()
print(f'the length of you name is {name.strip()}')
print(f'character is = {name.strip().lower().count(character.strip().lower())}')
| true |
bd809f3954aded9bef550a88b32eb1a958b7b1b5 | toufiq007/Python-Tutorial-For-Beginners | /chapter thirteen/zip_part2.py | 978 | 4.1875 | 4 |
l1= [1,2,3,4,5,6]
l2 = [10,20,30,40,50,60]
# find the max number of those list coupe item and store them into a new list
def find_max(l1,l2):
new_array = []
for pair in zip(l1,l2):
new_array.append(max(pair))
return new_array
print(find_max(l1,l2))
# find the smallest numbers and stored them into a new list
# another_list = []
# for pair in zip(l1,l2):
# another_list.append(min(pair))
# print(another_list)
# l = zip(l1,l2)
# # print(list(l))
# print(dict(l))
# you have a list like
# [(1,2),(3,4),(5,6)]
couple = [(1,2),(3,4),(5,6)]
# you should convert this tuple into different list
l1,l2 = zip(*couple)
print(l1)
print(l2)
# l1,l2 = zip(*couple)
# print(l1)
# print(l2)
# zip_item = tuple(zip(l1,l2))
# print(zip_item)
# unpack_file,file = zip(*zip_item)
# print(unpack_file)
# print(file)
# new_list = []
# for pair in zip(l1,l2):
# new_list.append(max(pair))
# print(new_list)
| true |
60b9af30be744aec3de24fd4f422c688570644f3 | toufiq007/Python-Tutorial-For-Beginners | /chapter eleven/args_as_arguement.py | 452 | 4.28125 | 4 |
# Args as arguements
def multiply_nums(*args):
print(args)
print(type(args)) # [1,2,3,4,5]
mutiply = 1
for i in args:
mutiply *= i
return mutiply
# when you pass a list or tuple by arguemnts in your function then you must give * argument after give your list or tuple name
number = [1,2,3,4,5]
print(multiply_nums(*number)) # when you pass the * arguements then the items of the list will unpack.
| true |
21647313d550a72c49db44ddb740922b2199c2e1 | toufiq007/Python-Tutorial-For-Beginners | /chapter eight/set_intro.py | 984 | 4.375 | 4 | # set data type
# unordered collection of unique items
# i a set data type you can't store one data in multipying times it should be use in onetime
# set removes which data are in mulple times
# the main use of set is to make a unique collection of data it means every data should be onetimes in a set
# s = {1,2,3,42,42,22,23,2,3}
# print(s)
# s2 = [1,2,3,5,4,65,4,2,3,8,9,10,21,20,10,1,3,8,9]
# s2 = set(s2)
# print(s2)
# you can change a list by using set and change a set to list by using list method
# set_list = list(set(s2))
# print(set_list)
# set methods
s = {1,2,3,4,5}
# s.add(4)
# s.remove(6)
# s.discard(3)
# s2 = s.copy()
# s.clear()
# print(s)
# print(s2)
# in a set you can'nt store list, tuple and dictionary
# you only store number like integer,floating number and also you store string
s = {1,2.2,1.1,'string','hello'}
# there is no matter which is printing before and after because set is a unordered collection of data
print(s)
| true |
080bf5bb5c575a0dfc6b1d805c252097b2fe6389 | joannarivero215/i3--Lesson-2 | /Lesson3.py | 1,577 | 4.15625 | 4 | #to comment
#when naming file, do not add spaces
#age_of_dog = 3, meaningful variable name instead of using x
names = ["corey", "philip", "rose","daniel"] #assigning variables values to varibale name in a list(need braket)
print names #without quotation to print value
print names[1] #says second name
print '\n'
for x in range(0,len(names)): #len is length of vaules, begins with 0. x signifies the integer assigned to the name
print names[x] #indent is to inculde in for loop
print '\n'
for current_names in names: #does the same as previous example only treats names as an individual string
print current_names
print type(current_names)
print '\n'
name=raw_input("Type your name here: ") #user inputs varibale name, raw input is used to take in answer as a string (better to not have hackers)
print "Your name is", name
print '\n'
if 1>2: #add collon for loop, only prints if true
print "Hello"
elif 1<2: #acts like another if, another condition. Goodbye is said because its true
print "Goodbye"
else:
print "I have nothing to say"
hello=23!=34 #!= is not equal to
print hello
#age of dog problem
print'\n'
age_of_dog=input("How old is your dog? ")
output=22+(age_of_dog -2)*5
if age_of_dog<=0:
print "Hold on! Say whaaaaaaat"
elif age_of_dog==1: #== is equal too
print "about 14 human years"
elif age_of_dog==2:
print "about 22 human years"
elif age_of_dog>2: #not using else because it would fall under every other answer not previously stated (including less then 2)
print "human years: ", output #comma to print both
| true |
095615f1bac4635998d783a8c1e6aad0f17c1930 | hmedina24/Python2021 | /Practice/basic_python_practice/practice04.py | 431 | 4.3125 | 4 | #Create a program that asks the user for a number and then prints out a list of all the divisors that number.
#(If you don't know what a divisor is, it is a number that divides evely into another number.) For example, 13 is a divisor of 26 /13 has no remainder.)
def main():
num = int(input("Enter a number"))
divisor = [i for i in range(1,num+1) if num % i == 0]
print(divisor)
if __name__ == "__main__":
main() | true |
077dd6078669f3ff73df753fa86ace4b7c38ccae | hmedina24/Python2021 | /Sort_Algorithms /insertionSort.py | 582 | 4.15625 | 4 | def insertionSort(arr):
#traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
#move elements of arr[0..i-1], that greater
#than key, to one position ahead
#of their current position
j = i-1
while(j >= 0 and key < arr[j]):
arr[j+1] = arr[j]
j-= 1
arr[j + 1] = key
for i in range(len(arr)):
print("%d" %arr[i])
def main():
#lets create an array
nums = [9,3,6,2,7,1,5,4]
insertionSort(nums)
if __name__ == "__main__":
main()
| true |
257f16e47cff4e8ac9c09a2c612c26514a144272 | eternalAbyss/Python_codes | /Data_Structures/zip.py | 585 | 4.34375 | 4 | # Returns an iterator that combines multiple iterables into one sequence of tuples. Each tuple contains the elements in
# that position from all the iterables.
items = ['bananas', 'mattresses', 'dog kennels', 'machine', 'cheeses']
weights = [15, 34, 42, 120, 5]
print(list(zip(items, weights)))
item_list = list(zip(items, weights))
# print(dict(zip(items, weights)))
# print(list(zip(*item_list)))
for i, item in enumerate(items):
print(i,item)
# Transpose trick
data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
data_transpose = tuple(zip(*data))
print(data_transpose) | true |
c24e68e1d77ba3e532987225382ae2f325424426 | muha-abdulaziz/langs-tests | /python-tests/sqrt.py | 419 | 4.3125 | 4 | """
This program finds the square root.
"""
x = int(input('Enter an integer: '))
def sqrt(x):
'''
This program finds the square root.
'''
x = x
ans = 0
while ans ** 2 < abs(x):
ans = ans + 1
if ans ** 2 != abs(x):
print(x, "is not a perfect square.")
else:
if x < 0:
ans = -ans
print('Square root of ' + str(x) + ' is ' + str(ans)) | true |
4e77c72219eec3043169f21e5ea39683d274d768 | vssousa/hacker-rank-solutions | /data_structures/linked_lists/merge_two_sorted_linked_lists.py | 982 | 4.34375 | 4 | """
Merge two linked lists
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
def MergeLists(headA, headB):
merge_head = None
current_node = None
while headA or headB:
# evaluate data in the linked lists
if not headB or (headA and headB and headA.data <= headB.data):
current_head = Node(data=headA.data)
headA = headA.next
else:
current_head = Node(data=headB.data)
headB = headB.next
# update the head in the merge list
if not merge_head:
merge_head = current_head
# create links on the merge list
if current_node:
current_node.next = current_head
current_node = current_head
return merge_head | true |
866d69100bf11fa6508f0831af38d793fcbc1203 | CapstoneProject18/Twitter-sentiment-analysis | /s3.py | 711 | 4.34375 | 4 | #function to generate list of duplicate values in the list
def remove_Duplicate(list):
final_list = []
for letter in list: #empty final list to store duplicate values in list
if letter not in final_list: #if letter is not in the list it appends that letter to final list
final_list.append(letter)
return final_list #it returns finalist
list = ["a","v","q","d","a","w","v","m","q","v"]
print(remove_Duplicate(list))
| true |
6a95042055f70c57d1b7f162d425999f4ea0b9ef | rhaeguard/algorithms-and-interview-questions-python | /string-questions/reverse_string_recursion.py | 368 | 4.28125 | 4 | """
Reverse the string using recursion
"""
def reverse_recurse(string, st, end):
if st > end:
return ''.join(string)
else:
tmp_char = string[st]
string[st] = string[end]
string[end] = tmp_char
return reverse_recurse(string, st+1, end-1)
def reverse(string):
return reverse_recurse(list(string), 0, len(string)-1) | true |
29780713ccfde18c564112343872fc00415e994b | rhaeguard/algorithms-and-interview-questions-python | /problem_solving/triple_step.py | 449 | 4.4375 | 4 | """
Triple Step: A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3
steps at a time. Implement a method to count how many possible ways the child can run up the
stairs.
"""
def triple_steps(step_size):
if step_size == 1 or step_size == 0:
return 1
elif step_size == 2:
return 2
else:
return triple_steps(step_size-1) + triple_steps(step_size-2) + triple_steps(step_size-3)
| true |
4a5ff8792e2f2106205376b2e4ac135045abf3d9 | akashgkrishnan/HackerRank_Solutions | /language_proficiency/symmetric_difference.py | 741 | 4.34375 | 4 | # Given sets of integers, and , print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either or but do not exist in both.
# Input Format
# The first line of input contains an integer, .
# The second line contains space-separated integers.
# The third line contains an integer, .
# The fourth line contains space-separated integers.
# Output Format
# Output the symmetric difference integers in ascending order, one per line.
# Sample Input
# 4
# 2 4 5 9
# 4
# 2 4 11 12
# Sample Output
# 5
# 9
# 11
# 12
input()
a = set(map(int, input().split()))
input()
b = set(map(int, input().split()))
A = list(a.symmetric_difference(b))
for i in sorted(A):
print(i)
| true |
c4b02fa604cfbaeda727970e16450d9caceb3cd0 | namanm97/sl1 | /7a.py | 744 | 4.375 | 4 | # 7A
# Write a python program to define a student class that includes name,
# usn and marks of 3 subjects. Write functions calculate() - to calculate the
# sum of the marks print() to print the student details.
class student:
usn = " "
name = " "
marks1 = 0
marks2 = 0
marks3 = 0
def __init__(self,usn,name,marks1,marks2,marks3): #Constructor
self.usn = usn
self.name = name
self.marks1 = marks1
self.marks2 = marks2
self.marks3 = marks3
def calculate(self): # Member Function
print ("usn : ", self.usn, "\nname: ", self.name,"\nTotal is ", (self.marks1 + self.marks2 + self.marks3)/3)
print ("Result of Named object of student calling calculate ")
s1 = student("1MSIS16048", "Parineethi Chopra", 78, 76,62)
s1.calculate()
| true |
de429dafc1e0289e1db3f2959c3898bf108da63f | zbloss/PythonDS-MLBootcamp | /Python-Data-Science-and-Machine-Learning-Bootcamp/Machine Learning Sections/Principal-Component-Analysis/PCA.py | 1,536 | 4.125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# PCA is just a transformation of the data that seeks to explain what features really
# affect the data
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
cancer.keys()
cancer['feature_names']
# We are going to see which components are the most important to this dataset
# i.e. we want to see which features most affect whether a tumor is cancer or benign
df = pd.DataFrame(cancer['data'], columns=cancer['feature_names'])
cancer['target_names']
# Usually PCA is done first to see which features are more important than others
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(df)
scaled_data = scaler.transform(df)
# Perform PCA
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
pca.fit(scaled_data)
x_pca = pca.transform(scaled_data)
scaled_data.shape
x_pca.shape
# Now we have transformed all of our 30 variables down to just 2 variables
plt.figure(figsize=(8,6))
plt.scatter(x_pca[:,0], x_pca[:,1], c=cancer['target'], cmap='plasma')
plt.xlabel('First Principal Component')
plt.ylabel('Second Principal Component')
# We now need to understand what the components are
pca.components_
# we create a dataframe that shows the two outcomes 0,1 and the relationship each feature has on it
df_comp = pd.DataFrame(pca.components_, columns=cancer['feature_names'])
df_comp
plt.figure(figsize=(10,6))
sns.heatmap(df_comp, cmap='plasma')
| true |
46ec9a084ae3e98e217ccd160257b870111b8c4e | coshbar/Trabalhos | /Phyton/Max_Subarray.py | 627 | 4.1875 | 4 | #Have the function MaxSubarray(arr) take the array of numbers stored in arr and determine the largest sum that can be formed by any contiguous subarray in the array.
#For example, if arr is [-2, 5, -1, 7, -3] then your program should return 11 because the sum is formed by the subarray [5, -1, 7].
#Adding any element before or after this subarray would make the sum smaller.
def ArrayChallenge(arr): maxsum = 0
for i in range(len(arr)):
for j in range(i, len(arr)):
tempsum = sum(arr[i:j + 1])
if tempsum > maxsum:
maxsum = tempsum
arr = maxsum
return arr
print ArrayChallenge(raw_input())
| true |
507d763a8196d7f37aeacc592130234b38cf3fa4 | stevenjlance/videogame-python-oop-cli | /game.py | 2,753 | 4.40625 | 4 | import random
class Player:
# Class variables that are shared among ALL players
player_list = [] #Each time we create a player, we will push them into this list.
player_count = 0
def __init__(self, name):
## These instance variables should be unique to each user. Every user will HAVE a name, but each user will probably have a different name.
self.name = name
self.strength = random.randint(8, 12) # The stat values will all be random, but within a range of reasonableness
self.defense = random.randint(8, 12)
self.speed = random.randint(8, 12)
self.max_health = random.randint(18, 24) # The max health value will be random, but higher than the others.
self.health = self.max_health # Set the current health equal to the max health.
print("Player " + self.name + " has entered the game. \n Strength: " + str(self.strength) + "\n Defense: " + str(self.defense) + "\n Speed: " + str(self.speed) + "\n Maximum health: " + str(self.max_health) + ".\n")
## We're going to also manipulate the two class variables - While each user has their own specific defense or strength, the users all share the class variables defined above this method.
Player.player_list.append(self) ## The player will be added to the list of players.
Player.player_count += 1 ## The player count should go up by one.
print("There are currently " + str(Player.player_count) + " player(s) in the game.\n\n")
def attack(self, target):
## With a CLI, we want to print out all the information our users need to play this game.
## Let's show the attacker and defender's names here.
print("Player " + self.name + " attacks " + target.name + "!!!")
print(self.name + "'s strength is " + str(self.strength) + " and target " + target.name + "'s defense is " + str(target.defense) + ".")
## The battle will go differently depending on who is stronger.
if self.strength < target.defense:
print("Due to the target's strong defense, the attack only does half damage...")
damage = self.strength / 2
elif self.strength > target.defense:
print("Since the target is weaker than you are, the attack does double damage!")
damage = self.strength * 2
else:
print("These players are evenly matched. The attack goes through normally.")
damage = self.strength
target.health -= damage
## Let's print out the new totals so that we know the final results of the fight.
print(target.name + " now has " + str(target.health) + "/" + str(target.max_health) + " health remaining.\n\n")
## All other methods you code for the player class will fit best below this line.
## Make sure to indent instance methods properly so the computer knows they're part of the class.
| true |
9a52340002ffd0ac3b93cb796958deee21219aef | eguaaby/Exercises | /ex06.py | 428 | 4.34375 | 4 | # Check whether the input string
# is a palindrome or not
def ex6():
user_input = raw_input("Please enter a word: ")
palindrome = True
wordLength = len(user_input)
for i in range(0, wordLength/2 + 1):
if user_input[i] != user_input[wordLength-1-i]:
palindrome = False
if palindrome:
print "The word is a palindrome!!"
else:
print "The word is not a palindrome"
ex6() | true |
4b5b369fafd5657f10492685af047a6604254d05 | sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions | /ex5_1_2.py | 901 | 4.1875 | 4 | # Chapter 5
# Exercise 1 & 2: Write a program which repeatedly reads numbers until the user enters
# βdoneβ. Once βdoneβ is entered, print out the total, count, average of the
# numbers, maximum and minimum of the numbers. If the user enters anything other than a number, detect their mistake
# using try and except and print an error message and skip to the next number.
total = 0
count = 0
while True:
line = input('Enter a number:')
try:
if line =='done':
break
line = float(line)
total = total + line
count = count + 1
if count == 1:
min = line
max = line
else:
if min > line:
min = line
elif max < line:
max = line
except:
print('Invalid input')
avg = total/count
print(total, count, avg, min, max)
| true |
eb4b36ee61f4541e2334038e366428a3b570d815 | sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions | /ex7_2.py | 1,030 | 4.1875 | 4 | # Chapter 7
# Exercise 2: Write a program to prompt for a ο¬le name, and then read through the
# ο¬le and look for lines of the form:
# X-DSPAM-Confidence:0.8475
# When you encounter a line that starts with βX-DSPAM-Conο¬dence:β pull apart
# the line to extract the ο¬oating-point number on the line. Count these lines and
# then compute the total of the spam conο¬dence values from these lines. When you
# reach the end of the ο¬le, print out the average spam conο¬dence.
# Enter the file name: mbox.txt
# Average spam confidence: 0.894128046745
# Enter the file name: mbox-short.txt
# Average spam confidence: 0.750718518519
count = 0
total = 0
fh = open('C:/Users/sandeep.kundala/Documents/python/mbox-short.txt')
for line in fh:
line = line.rstrip()
if line.startswith('X-DSPAM-Confidence:'):
count = count+1
atpos = line.find(':')
total = total + float(line[atpos+1:])
else:
continue
avg = total/count
print('Average spam confidence:', avg)
| true |
eee346b98c2726facf971db72ef2c5d6be0a7ee9 | sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions | /ex8_4.py | 472 | 4.3125 | 4 | # Chapter 8
# Exercise 4: Write a program to open the ο¬le romeo.txt and read it line by line. For each line,
# split the line into a list of words using the split function.
# For each word, check to see if the word is already in a list. If the word is not in
# the list, add it to the list.
fh = input('Enter file: ')
fopen = open(fh)
word = []
for line in fopen:
words = line.split()
for s in words:
word.append(s)
word.sort()
print(word)
| true |
697a943b2cceb74f2503fd1130bd3fa263ff57cf | Robbot/Teclado | /The Complete Python/Section1/main.py | 1,533 | 4.28125 | 4 | # Coding exercise 2
name = input("What is your name? ")
print(f"Hello, {name}")
age = int(input("What is your age? "))
print(f"You are {age*12} months old")
# Coding exercise 3
nearby_people = {'Rolf', 'Jen', 'Anna'}
user_friends = set() #This is an empty set
friend = input("What is the name of your friend? ")
user_friends.add(friend)
print(nearby_people.intersection(user_friends))
#Coding exercise 4
lottery_numbers = {13, 21, 22, 5, 8}
"""
A player looks like this:
{
'name': 'PLAYER_NAME',
'numbers': {1, 2, 3, 4, 5}
}
Define a list with two players (you can come up with their names and numbers).
"""
players = [
{
'name': 'Rob',
'numbers': {5,6,10,12,21,22}
},
{
'name': 'Rolf',
'numbers': {5,10,13,21,22,48}
}
]
"""
For each of the two players, print out a string like this: "Player PLAYER_NAME got 3 numbers right.".
Of course, replace PLAYER_NAME by their name, and the 3 by the amount of numbers they matched with lottery_numbers.
You'll have to access each player's name and numbers, and calculate the intersection of their numbers with lottery_numbers.
Then construct a string and print it out.
Remember: the string must contain the player's name and the amount of numbers they got right!
"""
won1 = (len((players[0]['numbers']).intersection(lottery_numbers)))
print(f"Player {players[0]['name']} got {won1} numbers right. ")
won2 = (len((players[1]['numbers']).intersection(lottery_numbers)))
print(f"Player {players[1]['name']} got {won2} numbers right. ") | true |
d5b582a3938073bfb5355322b4fe492b41de1d73 | johnahnz0rs/CodingDojoAssignments | /python/python_fundamentals/scores_and_grades.py | 829 | 4.3125 | 4 | # Write a function that generates ten scores between 60 and 100. Each time a score is generated, your function should display what the grade is for a particular score. Here is the grade table:
# Score: 60 - 69; Grade - D
# Score: 70 - 79; Grade - C
# Score: 80 - 89; Grade - B
# Score: 90 - 100; Grade - A
def scores_and_grades():
import random
print "Scores and Grades"
for x in range(0,10):
temp = random.randint(60, 100)
print "Score: " + str(temp) + "; Your grade is " + find_grade(temp)
print "End of the program. Bye!"
return
# enter a number score, get a letter grade
def find_grade(score):
if score >= 60 and score <=69:
return 'D'
elif score >= 70 and score <= 79:
return 'C'
elif score >= 80 and score <= 89:
return 'B'
elif score >= 90 and score <= 100:
return 'A'
# scores_and_grades() | true |
30ef3b36e9f9dddbf5526b068c1451796e78da89 | nd-cse-34872-su21/cse-34872-su21-examples | /lecture02/cheatsheet.py | 366 | 4.25 | 4 | #!/usr/bin/env python3
v = [1, 2, 3] # Create dynamic array
v.append(4) # Append to back of array
v.insert(0, 0) # Prepend to front of array
print(len(v)) # Display number of elements
for e in v: # Traverse elements
print(e)
# Traverse elements with index
for i, e in enumerate(v):
print(f'{i}: {e}')
| true |
f1705276ec52154591de27009366f0e8c5e278be | anejaprerna19/LearninPython | /passwordchecker.py | 396 | 4.25 | 4 | #Password Checker Assignment from Udemy Course
#In this simple assignment, we take user inputs for username and password and then calculate and print the length of password.
username= input("What is your username? ");
password= input("Enter the password ");
pass_length= len(password)
hidden_pass= '*' * pass_length
print(f'{username}, your password {hidden_pass} is {pass_length} letters long ') | true |
839764c040251100e370a5b0f24b8c3e8044961f | dhitalsangharsha/GroupA-Baic | /question5.py | 204 | 4.125 | 4 | '''5) Take an arbitrary input string from user and print it 10 times.'''
string=input("enter a string:")
print("\nprinting {} 10 times ".format(string))
for i in range(1,11):
print(str(i)+':',string) | true |
fc46ee5a3d68857277ffca31aa3925943c139988 | irffanasiff/100-days-of-python | /day5/range.py | 382 | 4.1875 | 4 | # for number in range(1, 10, 3):
# print(number)
# total = 0
# for number in range (1, 101):
# total += number
# print(total)
#! sum of all the even numbers from 1 to 100
total =0
for number in range(0,101,2):
total += number
print(total)
#? or
total =0
for number in range (1,101):
if number%2==0:
total+= number
else:
total+=0
print(total) | true |
68ceeb0a35ee5de2f89d64d842496f112689b9ed | florinbrd/PY-- | /python developer zero to mastery/Practice Exercises - pynative.com/Basic Exercises/Exercise10.py | 509 | 4.15625 | 4 | # Question 10: Given a two list of ints create a third list such that should contain only odd numbers from the first list and even numbers from the second list
def odd_list(list1, list2):
list3 = []
for item1 in list1:
if item1 % 2 == 0:
list3.append(item1)
for item2 in list2:
if item2 % 2 == 0:
list3.append(item2)
return list3
work_list1 = [1, 2, 3, 4, 5, 6, 7, 8]
work_list2 = [10, 11, 12, 13, 14, 15]
print(odd_list(work_list1, work_list2))
| true |
5d2ac7e730a592f9063af6ae5366608611060c67 | florinbrd/PY-- | /python developer zero to mastery/Practice Exercises - pynative.com/Basic Exercises/Exercise02.py | 398 | 4.3125 | 4 | # Question 3: Accept string from the user and display only those characters which are present at an even index
def even_char(string_defined):
print(f'Your original string is: {string_defined}')
for item in range(0, len(string_defined)-1, 2):
if item % 2 == 0:
print("index[", item,"]", string_defined[item] )
word = str(input('Enter your string: '))
even_char(word)
| true |
0669fa9486066c0a53b54f782a5f9d4d0e816264 | shashaank-shankar/OFS-Intern-2019 | /Python Exercises/Condition Statements and Loops/Exercise 1.py | 341 | 4.25 | 4 | # Write a Python program to find those numbers which are divisible by 7 and multiple of 5, between 1500 and 2700 (both included).
input = int(input("Enter a number: "))
if input >= 1500 and input <= 2700:
if input%7 == 0:
if input%5 == 0:
print(input + " is between 1500 and 2700. It is also divisable by 7 and 5.")
| true |
11f50308cb6450ee304af690d61f072c70924277 | shashaank-shankar/OFS-Intern-2019 | /Python Exercises/Condition Statements and Loops/Exercise 2.py | 1,088 | 4.5 | 4 | # Write a Python program to convert temperatures to and from celsius, fahrenheit.
print("\nThis program converts Celsius and Farenheit temperatures.")
def tempConvert (type):
if type == "C":
# convert to C
new_temp = (temp_input - 32) * (5/9)
new_temp = round(new_temp, 2)
print("\n" + str(temp_input) + "F is equal to " + str(new_temp) + "C.")
elif type == "F":
# convert to F
new_temp = (temp_input * (9/5)) + 32
new_temp = round(new_temp, 2)
print("\n" + str(temp_input) + "C is equal to " + str(new_temp) + "F.")
# repeats until 'C' or 'F' is entered
while True:
type_input = input("\nEnter 'C' to convert to Celsius\nEnter 'F' to convert to Farenheit\nEnter 'E' to Exit: ")
type_input = type_input.upper()
if type_input == "C":
temp_input = float(input("\nEnter a temperature in Farenheit: "))
tempConvert("C")
elif type_input == "F":
temp_input = float(input("\nEnter a temperature in Celsius: "))
tempConvert("F")
elif type_input == "E":
break | true |
54518c4f1dcd313da6458e664f7f8c1fa2b95b5c | Susama91/Project | /W3Source/List/list10.py | 273 | 4.21875 | 4 | #Write a Python program to find the list of words that are longer than n
#from a given list of words.
def lword(str1,n):
x=[]
txt=str1.split()
for i in txt:
if len(i)>n:
x.append(i)
print(x)
lword('python is a open',2)
| true |
d1573d6ad748eaceb5747f80a42477914ece741b | ItsPepperpot/dice-simulator | /main.py | 644 | 4.1875 | 4 | # Dice rolling simulator.
# Made by Oliver Bevan in July 2019.
import random
def roll_die(number_of_sides):
return random.randint(1, number_of_sides)
print("Welcome! How many dice would you like to roll?")
number_of_dice = int(input()) # TODO: Add type checking.
print("Okay, and how many sides would you like the dice to have?")
number_of_sides_on_die = int(input())
print(f"You roll {number_of_dice} dice. They read:")
sum_of_dice_values = 0
for i in range(0, number_of_dice):
die_value = roll_die(number_of_sides_on_die)
sum_of_dice_values += die_value
print(die_value, end=" ")
print(f"\nThey sum to {sum_of_dice_values}.")
| true |
1f4d2489bcfa31d9c1d3b2e82828c1533fac81d2 | MarvvanPal/foundations-sample-website | /covid_full_stack_app/covid_full_stack_app/controllers/database_helpers.py | 2,107 | 4.65625 | 5 | # connect to the database and run some SQL
# import the python library for SQLite
import sqlite3
# this function will connect you to the database. It will return a tuple
# with two elements:
# - a "connection" object, which will be necessary to later close the database
# - a "cursor" object, which will neccesary to run SQL queries.
# This function is like opening a file for reading and writing.
# this function takes one argument, a string, the path to a database file.
def connect_to_database(database_filename):
# connect to the database file, and create a connection object
try:
db_connection = sqlite3.connect(database_filename)
except sqlite3.DatabaseError:
print("Error while connecting to database file {filename}".format(
filename=database_filename))
# create a database cursor object, neccesary to use SQL
db_cursor = db_connection.cursor()
return db_connection, db_cursor
# close the connection to the database, like closing a file.
def close_conection_to_database(db_connection):
db_connection.close()
return
# This function will change either the structure or contents of your database.
# This expects SQL commands like "CREATE" or "INSERT"
def change_database(db_connection, db_cursor, sql_command):
try:
db_cursor.execute(sql_command)
except sqlite3.DatabaseError:
print("tried to execute the folllwing SQL, but failed:", sql_command)
# commit changes - like with git.
db_connection.commit()
return
# this function will run any SQL query and return a list of tuples,
# where each tuple represents a row in the database.
# the intent here is to use this for seeing what is inside the database.
# SQL commands like "SELECT" are expected here
def query_database(db_cursor, sql_query):
try:
db_cursor.execute(sql_query)
except sqlite3.DatabaseError:
print("tried to execute the folllwing SQL, but failed:", sql_query)
# list of tuples, where each tuple represents a row in the database
query_response = db_cursor.fetchall()
return query_response
| true |
7e603d0a3d96c50104630187b700ccab8cf035d7 | hemang249/py-cheatsheet | /conditions.py | 479 | 4.15625 | 4 | # Common Conditional Statements used in Python 3
# Basic if-else Condition
x = 5
if x == 5:
print("x = 5")
else:
print("x != 5")
# Basic Logical operations
# and or not
a = 0
b = 1
boolean = False
if a == 0 and b == 1:
print("a = 0 and b = 1")
if a == 0 or b == 1:
print("Either a = 0 or b = 1")
if not boolean :
print(boolean)
# elif statements
x = 1
if x == 1:
print("x = 1")
elif x == 2:
print("x = 2")
elif x == 3:
print("x = 3")
| true |
8ad114e4e5f63a56c8d560f60d05e19dcd77ee42 | KimberleyLawrence/python | /for_loop_even_numbers.py | 245 | 4.1875 | 4 | a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
for number in a:
# % 2 == 0 is dividing the number by 2, and seeing if there is any remainders, any remainders mean that the number is not even.
if number % 2 == 0:
print number
| true |
37e9fa37ff5e6cc968b0031e802538c1c902ad9c | Kristy16s/Think-Python-2-Exercises-By-Chapter | /2.1 Exercises.py | 1,285 | 4.4375 | 4 | # 2.10 Exercises
# Date 8/4/2021
"""
Exercise 1
Repeating my advice from the previous chapter, whenever you learn a new feature,
you should try it out in interactive mode and make errors on purpose to see what
goes wrong.
"""
# Weβve seen that n = 42 is legal. What about 42 = n?
# 42 = n
"""
File "<input>", line 1
42 = n
^
SyntaxError: cannot assign to literal
# Obviously, we can't assign numbers to a literal
"""
# How about x = y = 1?
x = y = 1
print("x = ", x)
print("y = ", y)
"""
x = 1
y = 1
"""
# In some languages every statement ends with a semi-colon, ;. What happens if
# you put a semi-colon at the end of a Python statement?
print("testing");
"""
testing
# the solution has no difference, but Python doesn't need it
"""
# What if you put a period at the end of a statement?
# print("testing").
"""
print("testing").
^
SyntaxError: invalid syntax
# We can't add a period at the end of a statement.
# period or the dot allows you to choose the suggested methods (functions) and
properties (data) of objects.
"""
# In math notation you can multiply x and y like this: x y. What happens if
# you try that in Python?
x = y = 1
print(xy)
"""
print(xy)
NameError: name 'xy' is not defined
# We must put * between x and y.
"""
| true |
41228a26ab53da47dabc59d4d0414c23e806d902 | shanksms/python_cookbook | /iterators-generators/generator-examples.py | 1,272 | 4.6875 | 5 | """
Hereβs a generator that produces a range of floating-point numbers.
Below function returns a generator object. A generator object is also an iterator. an Iterator is an Iterable.
That is why you can use it in while loop.
"""
def frange(start, stop, increment):
i = start
while i < stop:
yield i
i += increment
'''
The mere presence of the yield statement in a function turns it into a generator.
Unlike a normal function, a generator only runs in response to iteration.
Hereβs an experiment you can try to see the underlying mechanics of how such a function works:
'''
def countdown(n):
print('Starting to count from n')
while n > 0:
yield n
n -= 1
print('Done')
if __name__ == '__main__':
for x in frange(0, 4, 0.5):
print(x)
"""
The key feature is that a generator function only runs in response to "next" operations carried out in iteration.
Once a generator function returns, iteration stops.
However, the for statement thatβs usually used to iterate takes care of these details,
so you donβt normally need to worry about them.
"""
c = countdown(3)
print('printing c', c)
print(next(c))
print(next(c))
print(next(c))
print(next(c))
| true |
40a0f176eba2fed30a0c5ed96d9ee6fbe654a70a | ssummun54/wofford_cosc_projects | /Assignments/8and10.py | 1,719 | 4.15625 | 4 | # 8and10.py
# This progam runs two functions. The first function uss Newton's Method to find the
# square root of a number. The second function creates an acronym based on the phrase
# given by the user.
#importing math for square root
from math import *
#function for problem 8
def nextGuess(guess, newton): #(this is from runProblem8(someNumber, times)
#starts guess
estimate = guess/2
# looping for starting with one and ending with the actual number the user input
for i in range (1, newton + 1):
estimate = (estimate + (guess / estimate))/2
return estimate
#function for problem 10
def acronym(phrase):
#splitting phrase
phrase = phrase.split()
#new string where the letters will concactenate
newString = ""
for firstLetter in phrase:
newString = newString + firstLetter[0].upper()
return newString
#calls for problem 8 work
def runProblem8():
#inputs
someNumber = eval(input("Please enter a number: "))
times = eval(input("How many times do you wish to run Newton's Method? "))
#difference
difference = round(float(sqrt(someNumber)) - round(nextGuess(someNumber, times), 10),14)
#results
print("The estimated square root of", someNumber, "is", round(nextGuess(someNumber, times), 10), "which has an error of", float(abs(difference)))
def runProblem10():
phrase = input("Please enter a phrase: ")
print("The acronym for your phrase is", acronym(phrase))
def main():
print("Running Program 1 (Problem 8)...")
runProblem8()
print("Running Program 2(Problem 10)...")
runProblem10()
main()
| true |
d92640d7336759a48656c7df4bd333ceecca69aa | ssummun54/wofford_cosc_projects | /Assignments/numerology.py | 615 | 4.4375 | 4 | # numerology.py
# This program sums up the Unicode values of the user's full name and displays the corresponding Unicode character
# A program by Sergio Sum
# 3/24/17
def main():
name = input("Please enter your full name: ")
# not counting spaces by turning to list
name = name.split()
#joining list
name = "".join(name)
# accumulator
counter = 0
# getting unicode values for for values in name:
counter = counter + ord(values)
print("Your value is:", counter)
print("The Unicode character for your value is:", chr(counter))
main()
| true |
3ed869277d2d7958bc4d4012434c826f03e88eaf | dexterchan/DailyChallenge | /MAR2020/ScheduleTasks.py | 648 | 4.1875 | 4 |
#A task is a some work to be done which can be assumed takes 1 unit of time.
# Between the same type of tasks you must take at least n units of time before running the same tasks again.
#Given a list of tasks (each task will be represented by a string),
# and a positive integer n representing the time it takes to run the same task again,
# find the minimum amount of time needed to run all tasks.
#Here's an example and some starter code:
def schedule_tasks(tasks, n):
# Fill this in.
print(schedule_tasks(['q', 'q', 's', 'q', 'w', 'w'], 4))
# print 6
# one of the possible orders to run the task would be
# 'q', 'w', idle, idle, 'q', 'w' | true |
d6d4cc0dae2f1a1fc7a650798ee6dad83d6b57ed | dexterchan/DailyChallenge | /NOV2019/WordSearch.py | 2,069 | 4.15625 | 4 | #skills: array traversal
#You are given a 2D array of characters, and a target string. Return whether or not the word target word exists in the matrix.
# Unlike a standard word search, the word must be either going left-to-right, or top-to-bottom in the matrix.
#Example:
#[['F', 'A', 'C', 'I'],
# ['O', 'B', 'Q', 'P'],
# ['A', 'N', 'O', 'B'],
# ['M', 'A', 'S', 'S']]
#Given this matrix, and the target word FOAM, you should return true, as it can be found going up-to-down in the first column.
class Solution:
def findWord(self, matrix, word):
numrow = len(matrix)
numcol = len(matrix[0])
wordlen = len(word)
for i in range(0, numrow):
for j in range(0, numcol):
chkL2R = self.__checkL2R(i, j, matrix, word, numrow, numcol)
chkU2D = self.__checkU2D(i, j, matrix, word, numrow, numcol)
if(chkL2R or chkU2D):
return True
return False
def __checkL2R(self, x, y, matrix, word, numrow, numcol):
#check if reach boundary
element = []
if(y+len(word)>numcol):
return False
for i in range(len(word)):
element.append(matrix[x][y+i])
strRef = "".join(element)
if(strRef == word):
return True
else:
return False
def __checkU2D(self, x, y, matrix, word, numrow, numcol):
# check if reach boundary
element = []
if (x + len(word) > numrow):
return False
for i in range(len(word)):
element.append(matrix[x+i][y])
strRef = "".join(element)
if (strRef == word):
return True
else:
return False
def word_search(matrix, word):
solu = Solution()
return solu.findWord(matrix, word)
if __name__ == "__main__":
matrix = [
['F', 'A', 'C', 'I'],
['O', 'B', 'Q', 'P'],
['A', 'N', 'O', 'B'],
['M', 'A', 'S', 'S']]
print (word_search(matrix, 'FOAM') )
# True
print(word_search(matrix, 'BSl')) | true |
e76e31b3bce987ce0ed9b4a39f29ad6eb1221d92 | dexterchan/DailyChallenge | /MAR2020/FilterBinaryTreeLeaves.py | 2,112 | 4.15625 | 4 | #Hi, here's your problem today. This problem was recently asked by Twitter:
#Given a binary tree and an integer k, filter the binary tree such that its leaves don't contain the value k. Here are the rules:
#- If a leaf node has a value of k, remove it.
#- If a parent node has a value of k, and all of its children are removed, remove it.
#Here's an example and some starter code:
#Analysis
#dfs to the leaf with recursive function: func(node) -> boolean
# if leaf value is k, return true else false
# if non leaf node
# check return value of recursive function.... if yes, remove that child
# if all children removed, and its value is k,
# return true to its caller
# else return false
# Time complexity O(N) Space complexity O(N) --- memory stack usage when doing recursion
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __repr__(self):
return f"value: {self.value}, left: ({self.left.__repr__()}), right: ({self.right.__repr__()})"
class Solution():
def filter_recursive(self, node:Node,k:int)->bool:
if node.left is None and node.right is None:
return node.value == k
leftRet = True
rightRet = True
if node.left is not None:
leftRet = self.filter_recursive(node.left, k)
if node.right is not None:
rightRet = self.filter_recursive(node.right, k)
if leftRet:
node.left = None
if rightRet:
node.right = None
return leftRet and rightRet and node.value==k
def filter(tree, k):
# Fill this in.
solu = Solution()
solu.filter_recursive(tree, k)
return tree
if __name__ == "__main__":
# 1
# / \
# 1 1
# / /
# 2 1
n5 = Node(2)
n4 = Node(1)
n3 = Node(1, n4)
n2 = Node(1, n5)
n1 = Node(1, n2, n3)
print(str(filter(n1, 1)))
# 1
# /
# 1
# /
# 2
# value: 1, left: (value: 1, left: (value: 2, left: (None), right: (None)), right: (None)), right: (None) | true |
2ea7d16b392e87f58bb97d39e40df65120963c28 | JoseCintra/MathAlgorithms | /Algorithms/MatrixDeterminant.py | 2,070 | 4.46875 | 4 | """
Math Algorithms
Name: MatrixDeterminant.py
Purpose: Calculating the determinant of 3x3 matrices by the Sarrus rule
Language: Python
Author: JosΓ© Cintra
Year: 2021
Web Site: https://github.com/JoseCintra/MathAlgorithms
License: Unlicense, described in http://unlicense.org
Online demo: https://onlinegdb.com/ByWG_1BUd
Notes:
1) This algorithm is available without guarantees and must be tested before being made available in production environments
2) The data entry is fixed in the body of the algorithm, but can be changed by the user, if necessary
3) The input values are not being validated according to the allowed range !!! This is up to the user
4) The output data is being displayed without a concern for formatting
5) The goal here is just to highlight the solution of the problem through the algorithm stripped of any paradigm, with the hope that it will be useful to students in the field
"""
# Defining the matrix 3x3
# Change this to perform calculations with other matrices
a = [
[3, 1, 2],
[0, 2, 0],
[0, 4, 1]
]
det = 0 # Determinant
r = 0 # Current line of the matrix in the loop
c = 0 # Current row of the matrix in the loop
l = len(a) - 1 # Lenght of Matrix (index)
# Calculating the determinant of the matrix
print("Matrix determinant\n")
for i in range(len(a)):
prod = 1
r = 0
c = i
for j in range(len(a)):
prod = prod * a[r][c]
r = r + 1
c = c + 1
if (c > l):
c = 0
det = det + prod
r = 0
c = l
for i in range(len(a)):
prod = -1
r = 0
for j in range(len(a)):
prod = prod * a[r][c]
r = r + 1
c = c - 1
if (c < 0):
c = l
c = i
det = det + prod
# print results
print("Matrix A:")
for row in range(len(a)):
for col in range(len(a[row])):
print(a[row][col], end='')
print(" ", end='')
print("")
print("\nDeterminant of the matrix A:", det)
| true |
a893cd5e53c840925e54c60af40514bb8fa51d07 | mansoniakki/PY | /Reverse_Input_String.py | 412 | 4.40625 | 4 | print("##################This script with reverse the string input by user###########")
name=input("Please enter first and last name to reverse: ")
print("name: ", name)
words=name.split()
print("words: ", words)
for word in words:
lastindex = len(word) -1
print("lastindex ", lastindex)
for index in range(lastindex, -1, -1):
print(word[index], end='')
print(end= ' ')
print(end='\n')
| true |
63582443b16149b97f551b6a9f80845fa8b60a30 | rbenf27/dmaimcoolshek6969 | /PYTHON/COLOR GUESSER.py | 530 | 4.125 | 4 |
import random
color = random.randint(1,7)
if color == 1:
color = "yellow"
if color == 2:
color = "green"
if color == 3:
color = "orange"
if color == 4:
color = "blue"
if color == 5:
color = "red"
if color == 6:
color = "purple"
user_choice = input("Choose a color from the rainbow...so think about those 6 colors, ONLY!!")
if user_choice == color:
print("good job! you guessed correctly")
else:
print("THE COMPUTER THOUGHT OF SOMETHING DIFFERENT, SORRY....") | true |
f31a9a0fe3a3642263c05c365dffa4db220de581 | rbrown540/Python_Programs | /Calculate.py | 2,967 | 4.40625 | 4 | # Richard Brown - SDEV 300
# March 16, 2020
# Lab_One - This program prompts the user to select a math function,
# then performs that function on two integers values entered by the user.
print ('\nWelcome to this awesome Python coded calculator\n')
# provide user with the math function options
print ('Select 1 for ADDITION ( + )')
print ('Select 2 for SUBTRACTION ( - )')
print ('Select 3 for DIVISION ( / )')
print ('Select 4 for MULTIPLICATION ( * )')
print ('Select 5 for MODULUS ( % )')
# prompt user for selection
userSelection = int(input('\nPlease make your selection: '))
userInputOne = int(input('\t>> Please provide the first integer value: '))
userInputTwo = int(input('\t>> Please provide the second integer value: '))
# determine which selection the user chose, and then execute the math function
# on the set of integers input by the user
# Selection 1
if userSelection == 1:
print ('\nYou have chosen to ADD the two values:', userInputOne,
'and', userInputTwo)
userAdditionAnswer = userInputOne + userInputTwo
print ('\nThe sum of those two integers is:', userAdditionAnswer)
# Selection 2
if userSelection == 2:
print ('\nYou have chosen to SUBTRACT the two values', userInputOne,
'and', userInputTwo)
userSubtractionAnswer = userInputOne - userInputTwo
print ('\nThe difference of those two integers is: ',
userSubtractionAnswer)
# Selection 3
if userSelection == 3:
print ('\nYou have chosen to DIVIDE the two values: ', userInputOne,
'and', userInputTwo)
# alert to user that the value entered is not valid
# and then re-prompts for valid value
if userInputTwo <= 0:
userInputTwo = int(input('\nThis program is unable to divide by zero '
'or negative numbers,\nPlease select a non-zero'
' positive integer value: '))
userDivisionAnswer = userInputOne / userInputTwo
print ('\nThe quotient of those two integers is: ', int(userDivisionAnswer))
# Selection 4
if userSelection == 4:
print ('\nYou have chosen to MULTIPLE the values: ', userInputOne, 'and',
userInputTwo)
userMultiplicationAnswer = userInputOne * userInputTwo
print ('\nThe product of those two integers is: ',
userMultiplicationAnswer)
# Selection 5
if userSelection == 5:
print ('\nYou have chosen to find the REMAINDER of: ', userInputOne,
'and', userInputTwo)
# alert to user that the value entered is not valid
# and re-prompts for valid value
if userInputTwo <= 0:
userInputTwo = int(input('\nThis program is unable to divide by zero '
'or negative numbers,\nPlease select a non-zero'
' positive integer value: '))
userModulusAnswer = userInputOne % userInputTwo
print ('\nThe remained of those to two integers is: ', userModulusAnswer)
# saying good-bye
print ('\nThank you for using this awesome Python programmed calculator')
| true |
f366a69f898f1bc46e0495605878eefb3dcb438e | richa18b/Python | /oops.py | 2,829 | 4.15625 | 4 | import random
import sys
import os
class Animal :
_name = None #this is equivalent to __name = ""
_height = 0 #_ means that it is a private variable
_weight = 0
_sound = ""
#constructor
def __init__(self,name,height,weight,sound):
self._name = name
self._height = height
self._weight = weight
self._sound = sound
#Getters and Setters for all attributes
def get_name(self):
print(self._name)
def set_name(self, name):
self._name = name
def get_height(self):
print(self._height)
def set_height(self, height):
self._height = height
def get_weight(self):
print(self._weight)
def set_weight(self, weight):
self._weight = weight
def get_sound(self):
print(self._sound)
def set_sound(self, sound):
self._sound = sound
def get_type(self):
print('Animal')
def toString(self):
return "{} is {} cms tall, {} kgs in weight and says {}".format(self._name,
self._height,
self._weight,
self._sound)
cat = Animal('Cat',33,10,'Meoww')
print(cat.toString())
#Inheritance
class Dog(Animal):
_owner = ""
def __init__(self,name,height,weight,sound,owner):
self._owner = owner
super(Dog,self).__init__(name,height,weight,sound)
def set_owner(self,owner):
self._owner = owner
def get_owner(self):
return self._owner
def get_type(self):
print('Dog')
#Overriding the function that's in the super class
def toString(self):
return "{} is {} cms tall, {} kgs in weight and says {}. His owner is {}".format(self._name,
self._height,
self._weight,
self._sound,
self._owner)
#Performing method overloading
def multiple_sounds(self,how_many = None): #A way of saying that we do not require attributes to be passed in our function
if how_many is None :
print(self.get_sound())
else :
print(self.get_sound() * how_many)
spot = Dog("Spot",53,27,"Ruff","Ash")
print(spot.toString())
#Polymorphism
class AnimalTesting :
def get_type(self,animal) :
animal.get_type()
test_animals = AnimalTesting()
test_animals.get_type(cat)
test_animals.get_type(spot)
| true |
7d6e9b19d7f2ba2da75911fc61a300d39cf1857f | kunlee1111/oop-fundamentals-kunlee1111 | /Coin.py | 1,790 | 4.21875 | 4 | """
------------------------------------------------------------------------------------------------------------------------
Name: Coin.py
Purpose:
Simulates 1000 flips of a coin, and tracks total count of heads and tails.
Author: Lee.K
Created: 2018/11/30
------------------------------------------------------------------------------------------------------------------------
"""
import random
class Coin():
"""
Class that contains three functions: intialization method, returns the value of the face. sets the value of face.
"""
def __init__(self): #initialization method
self.face = 'heads' #Heads on top initially
def get_face(self):
"""
returns the value of the face attribute
:return: String (heads or tails)
"""
return self.face
def flip(self):
"""
randonly sets the value of the face attributes to heads ot tails
:return: String (heads or tails)
"""
return str(random.choice(["heads", "tails"]))
if __name__ == '__main__': #simulates 1000 flips of a coin, keeping track of total count of heads and tails.
a = 0 #iteration variable
total_Heads = 0 #total numer of Heads
total_Tails = 0 #total number of Tails
coin = Coin() #class coin variable
while a <= 1000:
coin.flip() #for 1000 times, coin is flipped.
a += 1 #increase in iteration
if coin.get_face() == 'heads': #if coin flipped is heads, total Heads increase by one
total_Heads += 1
else: #if coin flipped is tails, total tails increase by one
total_Tails += 1
print ("Total Heads Count is"+ total_Heads + "Total Tails Count is"+ total_Tails) #print the output | true |
d64728f99b0089fbca68bdef03db6982d570d8d4 | gingij4/Forritun | /bmistudull.py | 560 | 4.53125 | 5 | weight_str = input("Weight (kg): ") # do not change this line
height_str = input("Height (cm): ") # do not change this line
height_float = (float(height_str) / 100)
weight_float = float(weight_str)
bmi = (weight_float / (height_float)**2)
print("BMI is: ", bmi) # do not change this line
#BMI is a number calculated from a person's weight and height. The formula for BMI is:
#weight / height2
#where weight is in kilograms and heights is in meters
#Write a program that prompts for weight in kilograms and height in centimeters and outputs the BMI. | true |
7db3286c9184aa0405e47981b84fa87624ac8cee | rjrobert/daily_coding_problems | /daily12.py | 1,580 | 4.125 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2
What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
"""
# Ends up being fibonacci algorithm fib(n)
def fib(n):
# memo = [0] * (n + 1)
# memo[0] = 1
# memo[1] = 1
# return fib_helper(n, memo)
last_two = 1
last_one = 1
curr = 2
for i in range(n - curr):
last_two = last_one
last_one = curr
curr = last_one + last_two
return curr
def fib_helper(n, memo):
if memo[n] > 0:
return memo[n]
if n < 2:
return 1
memo[n] = fib_helper(n - 1, memo) + fib_helper(n - 2, memo)
return memo[n]
def fib2(n, steps):
memo = [0] * (n + 1)
memo[0] = 1
memo[1] = 1
return fib_helper2(n, memo, steps)
def fib_helper2(n, memo, steps):
if memo[n] > 0:
return memo[n]
if n < 2:
return 1
for i in steps:
if n >= i:
memo[n] += fib_helper2(n - i, memo, steps)
return memo[n]
print(fib(4))
assert(fib(4) == 5)
print(fib2(4, {1, 3, 5}))
assert(fib2(4, {1, 3, 5}) == 3)
| true |
1901e6e18d17b4595391d581443e672a924e2089 | cse210-spring21-team4/cse210-tc06 | /src/mastermind/game/player.py | 1,259 | 4.15625 | 4 | class Player:
"""A person taking part in a game.
The responsibility of Player is to record player moves and hints.
Stereotype:
Information Holder
Attributes:
_name (string): The player's name.
_move (Move): The player's last move.
"""
def __init__(self, players=list):
"""The class constructor.
Args:
self (Player): an instance of Player.
players (list): a list of player names
"""
self.__moves = {player: [] for player in players}
def get_moves(self, player=str):
"""Returns a player's move/hint record. If the player
hasn't moved yet this method returns None.
Args:
self (Player): an instance of Player.
"""
if player in self.__moves.keys():
return self.__moves[player]
return None
def record_move(self, player=str, move_hint=tuple):
"""Sets the player's last move to the given instance of Move.
Args:
self (Player): an instance of Player.
move_hint (tuple): a tuple of strings of the player's move,
followed by the resulting hint.
"""
self.__moves[player].append(move_hint)
| true |
e17792c43909aeb873441ff67efb33b42c2d1f84 | vburnin/PythonProjects | /CompoundInterestLoops.py | 2,028 | 4.53125 | 5 | import locale
locale.setlocale(locale.LC_ALL, '')
# Declare Variables
nDeposit = -1
nMonths = -1
nRate = -1
nGoal = -1
nCurrentMonth = 1
# Prompt user for input, check input to make sure its numerical
while nDeposit <= 0:
try:
nDeposit = int(input("What is the Original Deposit (positive value): "))
except ValueError:
print("Input must be a positive numeric value")
if nDeposit <= 0:
print("Input must be a positive numeric value")
while nRate <= 0:
try:
nRate = float(input("What is the Interest Rate (positive value): "))
except ValueError:
print("Input must be a positive numeric value")
if nRate <= 0:
print("Input must be a positive numeric value")
while nMonths <= 0:
try:
nMonths = int(input("What is the Number of Months (positive value): "))
except ValueError:
print("Input must be a positive numeric value")
if nMonths <= 0:
print("Input must be a positive numeric value")
while nGoal < 0:
try:
nGoal = int(input("What is the Goal Amount (can enter 0 but not negative): "))
except ValueError:
print("Input must be zero or greater")
if nGoal < 0:
print("Input must be zero or greater")
# Calculate Monthly Rate and save deposit for second loop
nMonthRate = nRate * 0.01 / 12
nAccountBalance = nDeposit
# For each month output the month and the current balance to screen
while nCurrentMonth <= nMonths:
nAccountBalance += nAccountBalance * nMonthRate
print("Month:", nCurrentMonth, "Account Balance is:", locale.currency(nAccountBalance))
nCurrentMonth += 1
# Reset Month Counter
nCurrentMonth = 0
# Find amount of months it will take to reach goal by looping monthly calculation until goal reached
while nGoal > nDeposit:
nDeposit += nDeposit * nMonthRate
nCurrentMonth += 1
# Output the amount of months it would take to reach the goal and the goal
print("It will take:", nCurrentMonth, "months to reach the goal of", locale.currency(nGoal))
| true |
343e43016f793b6f56dcca61a38bc7ee7eb479a5 | ajuliaseverino/tutoring | /tut/basics.py | 1,420 | 4.21875 | 4 | # print('Hello world')
# x = 5.6
# print(x)
#
# print("\nFor loop from 0 to 9.")
# for i in range(10):
# print(i)
def input_switch():
"""A function definition.
Calling the function by typing input_switch() will run this code.
The code does *not* get run when you create the function.
"""
user_input = input("type some stuff ")
print("you typed {}".format(user_input))
if user_input == "yes":
print("ok, good")
elif user_input == "no":
print("ok, bad")
else:
print("khsdf")
# print("\nFunctions with arguments now.")
def pos_neg(some_data_asdf):
"""Arguments (some_data_asdf) are used when there's some data you don't know in advance, but you *do* know
what you want to do with that data.
"""
if some_data_asdf < 0:
return some_data_asdf - 2
else:
return some_data_asdf + 2
# Runs the identity function, but with all the 'some_data_asdf' replaced by 5.
# identity(-5)
# identity(5)
# identity(6)
# print("\nVery very simple calculator now.")
def simple_calculator(right_hand_side, operator, left_hand_side):
if operator == "+":
return right_hand_side + left_hand_side
elif operator == "-":
return right_hand_side - left_hand_side
elif operator == "*":
return right_hand_side * left_hand_side
elif operator == "/":
return right_hand_side / left_hand_side
| true |
66536ba1353fcefb8951dec0ad9f47e4557f30b3 | Hamsik2rang/Python_Study | /References_Of_Object/Tuple.py | 764 | 4.40625 | 4 | # tuple
# tuple is immutable object. so when you create tuple once, you can't change or delete element(s) in it.
t = (1,)
print(t)
print(" remark: you can't create tuple that have an element without using comma(,). because it is confused with parenthesis operation.\n")
t = (1,2,3)
print(t)
t = 1,2,3
print(t)
# indexing
t = 1,2,3,4
print(f"t is {t}, and t[2] is {t[2]}\n")
# slicing
t = 1,2,3,4
print(f"t is{t}, and t[1:3] is {t[1:3]}\n")
# add tuple
t1 = 1,2
t2 = 3,4
print(f"t1 is {t1}, t2 is {t2}, then t1 + t2 is {t1+t2}\n")
# repeat tuple
t = 1,2
print(f"t is {t}, t * 3 is {t*3}\n")
# count
t = 1,2,1,1,4,2
print(f"t is {t}, and count of 1 in t is {t.count(1)}\n")
# get Index
t = 1,2,3,4
print(f"t is {t}, and index of 4 in t is {t.index(4)}\n")
| true |
cd0e80bafd2a6c761dab0c92e11c4aa82b145466 | Hamsik2rang/Python_Study | /Day14/Sources/Day14_6.py | 514 | 4.375 | 4 | # Generator
# Generator is a function contain 'yield' keyword.
# Generator works like iterator object.
def my_generator():
# When Interpreter(Compiler) meet 'yield' keyword, Literally yield program flow(resources) to main routine.
# It means return value there is next 'yield' keyword, and stop routine until next call.
yield 0
yield 1
yield 2
def not_generator():
return 10
ptr = my_generator()
print(next(ptr))
print(next(ptr))
print(next(ptr))
for i in not_generator():
print(i) | true |
87578912fbfeadc41774c42416ce99bc646a57cf | Hamsik2rang/Python_Study | /Day13/Sources/Day13_11.py | 958 | 4.125 | 4 | # Multiple Inheritance
# Python support Multiple Inheritance.
class Dragon:
def breath(self):
print("λΈλ μ€!!!! νΌν΄μ§!!!!!")
class Elf:
def heal(self):
print("μΉμ λ§λ²")
class Player(Dragon, Elf):
def attack(self):
print("μ!")
me = Player()
me.breath()
me.heal()
me.attack()
# Diamond Inheritance
class A:
def foo(self):
print("A")
class B(A):
def foo(self):
print("B")
class C(A):
def foo(self):
print("C")
class D(B, C):
pass
d = D()
# Generally, Programmer(User) don't know what letter will be printed
d.foo()
# In python, it follow Method Resolution Order, MRO.
# when you want to check this order, use mro() function like this:
D.mro()
# MRO is same with Inheritance argument order.
# when class D was defined, Inheritance argument order is B->C. (class D(B, C): ...)
# +a. All Python objects inherit 'Object' class. like this:
print(int.mro())
| true |
c00c114531ecc3ccf2d29dd7457ed7c6c68ede60 | daniellehoo/python | /week 1/math2.py | 467 | 4.1875 | 4 | # in Python you can do math using the following symbols:
# + addtion
# - subtaction
# * multiplication
# / division
# ** exponent (not ^)
# > greater than
# >= greater than or equal to
# < less than
# <= less than or equal to
# and more!
answer = (40 + 30 - 7) * 2 / 3
print("what is the answer to life, the universe, and everything?", int(answer))
print ("is it try that 5 * 2 > 3 * 4?")
print (5 * 2 > 3 * 4)
# float(42)
# int (42.0) will cut off decimal, won't | true |
114d909c19bfde24e1e4cbccf337b15d6479e418 | zerformza5566/CP3-Peerapun-Sinyu | /assignment/Exercise5_1_Peerapun_S.py | 436 | 4.25 | 4 | firstNumber = float(input("1st number : "))
secondNumber = float(input("2nd number : "))
plus = firstNumber + secondNumber
minus = firstNumber - secondNumber
multiply = firstNumber * secondNumber
divide = firstNumber / secondNumber
print(firstNumber, "+", secondNumber, "=", plus)
print(firstNumber, "-", secondNumber, "=", minus)
print(firstNumber, "*", secondNumber, "=", multiply)
print(firstNumber, "/", secondNumber, "=", divide) | true |
5e0aa09e18545eb0db0f8e21b613e29007b6e25a | nicolesy/codecademy | /projects/codecademy_project_cho_han.py | 1,342 | 4.53125 | 5 | # codecademy_project_cho_han.py
# Create a function that simulates playing the game Cho-Han. The function should simulate rolling two dice and adding the results together. The player predicts whether the sum of those dice is odd or even and wins if their prediction is correct.
# The function should have a parameter that allows for the player to guess whether the sum of the two dice is "Odd" or "Even". The function should also have a parameter that allows the player to bet an amount of money on the game.
# test Test test
import random
def roll_dice(guess, comp):
if guess == comp:
result = "You win!"
else:
result = "You lose."
return result
money = 100
while money > 0:
user_guess = input("Is it even, or odd? ")
user_bet = input("How much would you like to bet? ")
user_bet = int(user_bet)
calc_1 = random.randint(1,6)
calc_2 = random.randint(1,6)
computer_calc = calc_1 + calc_2
print(f"The random number is {computer_calc}")
if computer_calc % 2 == 0:
computer_calc = "even"
else:
computer_calc = "odd"
if roll_dice(user_guess, computer_calc) == "You win!":
money += user_bet
else:
money -= user_bet
print(f"{roll_dice(user_guess, computer_calc)} You have ${money} remaining.")
else:
print("You are out of money.") | true |
18868e88cc99d47da4052c5231e1d78d4cba6332 | dmproia/java1301_myPythonPrograms | /lab8.py | 934 | 4.28125 | 4 | #============================
# PROGRAM SPECIFICATIONS
# NARRATIVE DESCRIPTION:Lab8
#
# @author (David Proia)
# @version(1/27/12)
#==============================
repeat = "Y"
print ("This program is designed to tell allow you to tell if you have a right triangle or not" )
print ()
while (repeat == "Y"):
X = float(input("What is the length of side A of triangle? "))
Y = float(input("What is the length of side B of triangle? "))
Z = float(input("What is the length of side C of triangle? "))
if (X >= Y) and (X >= Z):
A = Y
B = Z
C = X
elif (Y >= X) and (Y >= Z):
A = Z
B = X
C = Y
elif (Z >= X) and (Z >= Y):
A = Y
B = X
C = Z
if (A**2) + (B**2) == (C**2):
print ("This is a right triangle!")
else:
print("This is not a right triangle")
repeat = input("Press Y to make more conversion or Q to quit: ")
| true |
215504ad95354baf30674044d4eb285dc87e8193 | Nayalash/ICS3U-Problem-Sets | /Problem-Set-Five/mohammad_race.py | 1,491 | 4.28125 | 4 | # Author: Nayalash Mohammad
# Date: October 19 2019
# File Name: race.py
# Description: A program that uses the Tortoise and Hare Algorithm to simulate a race.
# Import Required Libraries
import random
import time
# Helper Function To Display Name and Progress
def display(name, progress):
print(name + ": " + str(progress) + "/" + str(length))
# Ask user for length of the race
length = int(input("How long is this race? MIN = 20: "))
# Start Progress at zero
tortoiseProg = 0
hareProg = 0
# Initialize Moves Dictionaries
hareMoves = {0: 0, 1: 0, 2: 9, 3: 9, 4: -12, 5: 1, 6: 1, 7: 1, 8: -2, 9: -2}
tortoiseMoves = {0: 3, 1: 3, 2: 3, 3: 3, 4: 3, 5: -6, 6: -6, 7: 1, 8: 1, 9: 1}
# While Condition, Until Lengths are not less than zero
while hareProg < length or tortoiseProg < length:
# Pick from the nine moves
moveChoice = random.randint(0, 9)
# Add moves to the progress counter
tortoiseProg += tortoiseMoves[moveChoice]
hareProg += hareMoves[moveChoice]
if(tortoiseProg < 0):
tortoiseProg = 0
if(hareProg < 0):
hareProg = 0
# Display place every iteration
if(hareProg < length and tortoiseProg < length):
display("Tortoise", tortoiseProg)
display("Hare", hareProg)
time.sleep(0.5) # Slow Down Text Scrolling
# Display Outcome
if(hareProg == tortoiseProg):
print("The Hare and the Tortoise have tied.")
elif(hareProg > tortoiseProg):
print("The Hare has won!")
else:
print("The Tortoise has won!")
| true |
94d53ee92c8275a4b71070097047f3085972db20 | Nayalash/ICS3U-Problem-Sets | /Problem-Set-Seven/mohammad_string_blank.py | 1,094 | 4.25 | 4 | # Author: Nayalash Mohammad
# Date: November 01 2019
# File Name: string_blank.py
# Description: A program that replaces multiple spaces with one
# Main Code
def main():
# Ask for string
string = input("Enter a string with multiple blank spaces...\n")
# Regex the string, and join it
newString = ' '.join(string.split())
print("********************************")
# Display Results
print("Your Formatted String is: ")
print(newString)
# Re-Run
menu()
# Menu Method
def menu():
print("To Run Program: type run, To Quit: type quit, For Help: type help")
# Ask user for what they would like to do
option = input()
if (option == "run"):
main() # Run App
menu()
elif (option == "quit"):
exit()
elif (option == "help"):
print('To run program, type `run` below, or `quit` to quit the program. Refer to docs for more info.')
print('Type your spaced out text, and the program will format it for you.')
menu()
else:
print("Invalid Input")
menu()
# Init Program
print("Welcome To String Formatter")
menu()
| true |
2c3dd09d52eaa860167288b7192be1bcca2b176a | Nayalash/ICS3U-Problem-Sets | /Problem-Set-One/digit_breaker.py | 277 | 4.125 | 4 | # Author: Nayalash Mohammad
# Date: September 20 2019
# File Name: digit_breaker.py
# Description: A program that splits the digits in a number
# Ask a number from the user
number = input("Enter a Three Digit Number: ")
# Iterate over the provided string
for i in number:
print(i)
| true |
2494877cda4f8f5ebc6f88de5bd26cc0726d695e | Isaac3N/python-for-absolute-beginners-projects | /reading files.py | 1,110 | 4.53125 | 5 | # read it
# demonstrates reading from a text file
print("opening and a closing file.")
text_file= open("readit.txt", "r")
text_file.close()
print("\nReading characters from a file.")
text_file= open ("readit.txt", "r")
print(text_file.read(1))
print(text_file.read(5))
text_file.close()
print("\nReading the entire file at once.")
text_file = open("readit.txt","r")
whole_thing= text_file.read()
print(whole_thing)
text_file.close()
print("\nReading characters from a line.")
text_file= open("readit.txt", "r")
print(text_file.readline(1))
print(text_file.readline(5))
text_file.close()
print("\nReading one line at a time.")
text_file= open("readit.txt", "r")
print(text_file.readline())
print(text_file.readline())
print(text_file.readline())
text_file.close()
print("\nReading the entire file into a list.")
text_file= open("readit.txt", "r")
lines = text_file.readlines()
print(lines)
print(len(lines))
for line in lines:
print (line)
text_file.close()
print("\nlooping through a file line by line")
text_file= open("readit.txt", "r")
for line in text_file:
print (line)
text_file.close()
| true |
f75b734c0b6c1848e23253466a2a637dd5220983 | Isaac3N/python-for-absolute-beginners-projects | /limited tries guess my number game.py | 608 | 4.21875 | 4 | # welcome to the guess my number game
# your to guess a number from 1-5
# your limited to 3 tries
import random
print (" welcome to the guess my number game \n your limited to a number tries before the game ends \n GOOD LUCK !")
the_number = random.randint(1,5)
guess = input (" take a guess: ")
tries = 1
while guess != the_number and tries <= 3:
if guess > str(the_number) :
print ("lower....")
else :
print ("higher....")
guess = input (" take a guess: ")
tries += 1
print ( " congratulations! you guessed it ")
print (" and you did it in only",tries, " tries" )
| true |
988207876d95d5de27ef0fb9e14600343a9afe56 | macheenlurning/python-classwork | /Chap3Exam.py | 2,478 | 4.3125 | 4 | # Ryan Hutchinson
# Chapter 3 Exam
# Programming Projects 1 & 3
#1 - Car Loan
loan = int(input("Enter the amount of the loan: "))
if int(loan) >= 100000 or int(loan) < 0:
print("Total loan value {} might be incorrect...".format(loan))
response1 = input("Would you like to correct this? Type Yes or No: ").lower()
if response1 == 'yes':
loan = int(input("Enter the amount of the loan: "))
elif response1 == 'no':
pass
annual_rate = float(input("Enter the interest rate: "))
if float(annual_rate) >= 30 or float(annual_rate) < 0:
print("Annual rate {} might be incorrect?".format(annual_rate))
response2 = input("Would you like to correct this? Type Yes or No: ").lower()
if response2 == 'yes':
annual_rate = float(input("Enter the interest rate: "))
elif response2 == 'no':
pass
duration = int(input("Enter the duration in months: "))
if int(duration) > 72 or int(duration) < 12:
print("Duration of {} months might be incorrect?".format(duration))
response3 = input("Would you like to correct this? Type Yes or No: ").lower()
if response3 == 'yes':
duration = int(input("Enter the duration in months: "))
elif response3 == 'no':
pass
monthly_rate = round(((annual_rate/100) / 12), 8)
part1 = round((loan * monthly_rate), 8)
part2 = round(((1 / ((1 + monthly_rate) ** duration))), 8)
part3 = round((1 - part2), 8)
monthly_payment = round(float(part1 / part3), 2)
tot_int = (duration * monthly_payment) - loan
formatted_mp = "{:.2f}".format(monthly_payment)
formatted_ti = "{:.2f}".format(tot_int)
print("Monthly payment: ${}".format(formatted_mp))
print("Total interest paid: ${}".format(formatted_ti))
print()
#3 - Caffeine Absorption
print("CAFFEINE VALUES")
total_caf = 130
hours = 0
while total_caf >= 65:
total_caf = total_caf * 0.87
hours += 1
if total_caf < 65:
print("One cup: less than 65mg. will remain after {} hours.".format(hours))
total_caf = 130
hours = 0
while hours <25:
hours += 1
total_caf = (total_caf * 0.87)
if hours == 24:
print("One cup: {:.2f} mg. will remain after 24 hours.".format(total_caf))
total_caf = 130
hours = 0
while hours < 25:
hours += 1
total_caf = total_caf * 0.87
total_caf = total_caf + 130
if hours == 24:
print("Hourly cups: {:.2f} mg. will remain after 24 hours.".format(total_caf))
| true |
a5405798c83b1ecc5b8095b4a8251ea3d6aa8fea | bapadman/PythonToddlers | /pythonTutorialPointCodes/IfElse.py | 277 | 4.1875 | 4 | #!/usr/bin/python
# classic if else loop example
flag = True
if not flag:
print("flag is true")
print("Printing from if loop")
else:
print("flag is false")
print("Printing from else part")
#while loop sample
i = 0
while i < 10:
print("i = ",i)
i = i +1
| true |
55306a5cb494265ccaec0969650a6f311fe7270f | finolex/Python_F18_Abhiroop | /Lab 3 - Booleans/q3.py | 485 | 4.125 | 4 | import math
firstLeg = int(input("Please enter the length of the first leg: "))
secondLeg = int(input("Please enter the length of the second leg: "))
hyp = float(input("Please enter the length of the hypothenuse: "))
hypCalc = math.sqrt(firstLeg**2 + secondLeg**2)
if hyp == hypCalc:
print("This forms a right angled triangle!")
elif abs(hyp - hypCalc) < 0.00001:
print("This forms a right angled triangle!")
else:
print("This does not form a right angled triangle.")
| true |
5c624b55e026aa8c9c506162767176dd19e4fd7c | finolex/Python_F18_Abhiroop | /Lab 3 - Booleans/q4.py | 382 | 4.15625 | 4 | num1 = int(input("Please enter your first integer: "))
num2 = int(input("Please enter your second integer: "))
if num2 == 0:
print("This has no solutions.")
elif (-num1/num2) > 0 or (-num1/num2) < 0:
print("This has a single solution and x = .", (-num1/num2))
elif (-num1/num2) == 0:
print("This has a single solution.")
else:
print("This has infinite solutions.")
| true |
172720a347baa8828443ba979fb4fe01b2e7f6f5 | gabrielchase/MIT-6.00.1x- | /Week2/prob3.py | 1,116 | 4.5 | 4 | # Write a program that calculates the minimum fixed monthly payment needed
# in order pay off a credit card balance within 12 months. By a fixed monthly
# payment, we mean a single number which does not change each month, but
# instead is a constant amount that will be paid each month.
MONTHS_IN_A_YEAR = 12
# Given by the problem
balance = 999999
annualInterestRate = 0.18
def get_monthly_interest_rate():
return annualInterestRate/MONTHS_IN_A_YEAR
def monthly_mimimal_payment(balance, annual_interest_rate):
monthly_interest_rate = 1 + get_monthly_interest_rate()
coefficient = 0
for _ in range(MONTHS_IN_A_YEAR):
coefficient = (coefficient + 1) * monthly_interest_rate
balance = balance * monthly_interest_rate
return balance/coefficient
minimal_payment = monthly_mimimal_payment(balance, annualInterestRate)
print('Lowest Payment:', round(minimal_payment, 2))
assert minimal_payment == 90325.03
# Answer researched on
# 'https://codereview.stackexchange.com/questions/142676/for-a-given-balance-and-an-annual-interest-rate-calculate-the-minimum-fixed-mon' | true |
b785ed5bff4e17cb22b7ee84e0144ab222dedd45 | green-fox-academy/FulmenMinis | /week-04/day-03/fibonacci.py | 386 | 4.25 | 4 | # Fibonacci
# Write a function that computes a member of the fibonacci sequence by a given index
# Create tests that covers all types of input (like in the previous workshop exercise)
def fibonacci(n=0):
if n < 0:
return False
elif n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return (fibonacci(n-1) + fibonacci(n-2))
| true |
a0aacffaecbcb78b56a2f2beecb7d2bf0b143f68 | green-fox-academy/FulmenMinis | /week-03/day-04/number_adder.py | 264 | 4.25 | 4 | # Write a recursive function that takes one parameter: n and adds numbers from 1 to n.
def recursive_function(n):
if n == 0 or n == 1:
return n
else:
return (recursive_function(n-1) + recursive_function(n-2))
print(recursive_function(10)) | true |
19684231d4bc2fa7ee4e71da4563451022e7c826 | green-fox-academy/FulmenMinis | /week-04/day-03/sum.py | 790 | 4.1875 | 4 | # Sum
# Create a sum method in your class which has a list of integers as parameter
# It should return the sum of the elements in the list
# Follow these steps:
# Add a new test case
# Instantiate your class
# create a list of integers
# use the assertEquals to test the result of the created sum method
# Run it
# Create different tests where you
# test your method with an empyt list
# with a list with one element in it
# with multiple elements in it
# with a null
# Run them
# Fix your code if needed
class Sum(object):
def sum(self, numbers):
sum_of_all_numbers = 0
for number in numbers:
sum_of_all_numbers += number
return sum_of_all_numbers | true |
3c7361f73a5fdee8d31f86f9961ba5f5239060cb | green-fox-academy/FulmenMinis | /week-02/day-05/armstrong_number.py | 1,108 | 4.4375 | 4 | #Exercise
#
#Write a simple program to check if a given number is an armstrong number.
# The program should ask for a number. E.g. if we type 371, the program should print out:
# The 371 is an Armstrong number.
# What is Armstrong number?
# An Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits.
# Let's demonstrate this for a 4-digit number: 1634 is a 4-digit number,
# raise each digit to the fourth power, and add: 1^4 + 6^4 + 3^4 + 4^4 = 1634, so it is an Armstrong number.
#Solution1
number = input("Please enter a number: ")
numberlist = []
for i in range(len(number)):
numberlist.insert(len(numberlist), int(number[i]))
sum = 0
for i in numberlist:
sum += i ** len(numberlist)
print("The " + str(number) + " is an Armstrong number." if int(number) == sum
else "The " + str(number) + " isn't an Armstrong number.")
#Solution2
x = input("Please enter a number: ")
exponent = len(x)
sum = 0
for c in x:
sum += int(c)**exponent
if sum == int(x):
print( x + " is an Armstrong number!")
else:
print( x + " isn't an Armstrong number!") | true |
8164ea4320540ca503dc3493c629c74666eeec1f | ShivaVkm/PythonPractice | /playWithTrueFalse.py | 769 | 4.25 | 4 | # True means 1 and False in 0
print(True) # you will get True
print(False) # you will get False
print(True+False) # you will get 1 because True = 1 and False = 0
print(True == 1) # verification for trueness' value as equal to 1
print(False == 0) # verification for falseness' value as equal to 0
print(True+True)
print(True-True)
print(True*True)
print(True/True)
print(True%True)
print(False+False)
print(False-False)
print(False*False)
# print(False/False) # ZeroDivisionError: division by zero
# print(False%False) # ZeroDivisionError: integer division or modulo by zero
print(True+False)
print(True-False)
print(True*False)
# print(True/False) # ZeroDivisionError: division by zero
# print(True%False) # ZeroDivisionError: integer division or modulo by zero | true |
fa1ead85ec576a9d9f3f7595e855b0afcc5c2abc | rpt/project_euler | /src/problem001.py | 597 | 4.1875 | 4 | #!/usr/bin/env python3
# Problem 1:
# If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
# Answer:
# 233168
def problem1(n):
def sumd(x, n):
k = (n - 1) // x
return x * k * (k + 1) // 2
return sumd(3, n) + sumd(5, n) - sumd(15, n)
# print(problem1(1000))
def problem1n(n):
'''Naive, slow version.'''
c = 0
for i in range(1, n):
if (i % 3 == 0) or (i % 5 == 0):
c += i
return c
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.