blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
37e88ac370855bb19f949e1ef543d523004c6996 | yogeshrnaik/python | /linkedin/Ex_Files_Python_EssT/Exercise Files/Chap02/blocks.py | 400 | 4.1875 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
x = 42
y = 73
if x < y:
z = 112
print('x < y: x is {} and y is {}'.format(x, y))
print(f'x < y: x is {x} and y is {y}')
print(f'z is accessible here: {z} because z is defined inside a block and\n' +
'block do not define scope of variables in Python.\n' +
'Only Functions, objects and modules define the scope in Python.') | true |
850317ac0e03b4233ad3314c92b13de2c7bfef9f | yogeshrnaik/python | /linkedin/Ex_Files_Python_EssT/Exercise Files/Chap09/string.py | 396 | 4.125 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# str is built in Python class for String representation
class RevStr(str):
def __str__(self):
# this returns slice of string where the step goes backwards
# so it reverses the string
return self[::-1]
def main():
hello = RevStr('Hello, World.')
print(hello)
if __name__ == '__main__': main()
| true |
d3c891815ebda788c6c57c7f50d2f5c9c61adf8d | yogeshrnaik/python | /linkedin/Ex_Files_Python_EssT/Exercise Files/Chap04/ternary.py | 235 | 4.125 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# Ternary operator available since Python 2.5
hungry = True
x = 'Feed the bear now!' if hungry else 'Do not feed the bear.'
print(x)
x = 'Feed' if False else 1
print(x) | true |
9eb4c9650d7910a14d496cccec6fed714c707431 | aliahmadcse/Programming-Foundation_Algorithms | /hashTable.py | 399 | 4.21875 | 4 | # create a hash table all at once
item1 = dict({"key1": 1, "key2": 2, "key3": "three"})
# create a hash table progressively
item2 = {}
item2["key1"] = 1
item2["key2"] = 2
item2["key3"] = 3
print(item2)
# get an invalid key
print(item2.get("key6", 6))
# replace an item
item2["key2"] = "two"
print(item2)
# iterate over the hash table
for key, value in item2.items():
print(f"{key},{value}")
| true |
f8f05e4f21aeb822f592b48900b160eb9a715f09 | prakash959946/basic_python | /Python_Basics/2_Factorial.py | 756 | 4.15625 | 4 |
# Factorial of a number through conditional statements
"""
Example 1:
4! = 4* 3* 2* 1 = 24
"""
num = int(input("Enter a non-negative number: "))
factorial = 1
if num < 0:
print("Sorry, you can't find factorial here for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, num+1):
factorial = factorial * i
print("The factorial of", num, "is", factorial)
# Factorial of a number through functions
num = input("Enter a number: ")
def factorial(n):
if n == 1:
return n
elif n < 1:
return ("Sorry, you can't find factorial here for negative numbers")
else:
return n * factorial(n-1)
print(factorial(int(num))) | true |
47f58ce032f6fa0ba1a40dfa9397f1a3aa67d381 | prakash959946/basic_python | /Programiz_problems/7_celsius_to_fahrenheit.py | 276 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Convert Celsius to Fahrenheit
"""
celsius = float(input("Enter temperature in celsius: "))
#conversion factor
fahrenheit = celsius * 1.8 + 32
print("{} degree celsius is equal to {} degree fahrenheit".format(celsius, fahrenheit))
| false |
7418715eab3f89dcfbc67cc64cccaafdc458c4ef | prakash959946/basic_python | /Python_Basics/3_Simple_Interest.py | 292 | 4.125 | 4 |
# Simple Interest
"""
Example 1:
Input : P = 10000
R = 5
T = 5
Output :2500
"""
P = float(input("Enter Principle amount: "))
T = float(input("Enter rate Time period: "))
R = float(input("Rate of Interest per annuam: "))
si = P * T * R / 100
print(si) | false |
106dfe3bb623c0eb47082b19ea3001fe46c14e4f | DanDorado/CV_Projects | /credit/credit.py | 1,081 | 4.15625 | 4 | # Get the get_int function
from cs50 import get_string
# Get a number from the user.
cn = get_string("Number: ")
total = 0
place = 0
# Run a check on the number format, for each number from the right side(we use i to count, it doesn't matter from left or right):
# If it is even then add it to the total
# If it is odd then double it and add the total digits to the total.
for i in range(len(cn)):
place = len(cn) - i - 1
if (i + 1) % 2 is 1:
total += (int(cn[place]))
else:
total += (int(cn[place]) * 2 // 10) + (int(cn[place]) * 2 % 10)
# If total is a multiple of 10 then the card can be valid.
if total % 10 is not 0:
print("INVALID")
# Check for the correct card number length and starting digits of the main credit card companies.
elif (len(cn) is 15) and (int(cn[0]) is 3) and (int(cn[1]) in (4, 7)):
print("AMEX")
elif (len(cn) is 16) and (int(cn[0]) is 5) and (0 < int(cn[1]) < 6):
print("MASTERCARD")
elif (len(cn) in (13, 16)) and (int(cn[0]) is 4):
print("VISA")
# Otherwise print invalid anyway.
else:
print("INVALID") | true |
2abb4580f4cd4823ac69ec04939f469f9afdfd8f | solinwolf/Python | /think python/recursion.py | 236 | 4.1875 | 4 | # recursion
# functionality: recursively display numbers 0-n
def countdown(n):
if n<0:
print '%d is not positive'%n
return
if n==0:
print 'Blastoff'
else:
print n
countdown(n-1)
return
countdown('pw')
| false |
3665f1abfbe68986b0d95000761833f55c4c0e72 | solinwolf/Python | /think python/break.py | 491 | 4.28125 | 4 | # break statement
# Take input from the user until they type done
while True:
line = raw_input('>')
if line == 'done':
break
print line
print 'Done'
# Flow of execution for a break statement
# 1.take input from the user and store in the variable named line
# 2.Evaluate the condition statement (if) ,yielding True or False
# 3.If 2. yields True (line == 'done') jump out of the while statement and then print 'Done'. If 2. returns False (line != 'done') print lline
| true |
8f1167687c79cf5d19029895dc222a7ce10a339d | CosminEugenDinu/udacity_DSA_Problems_vs_Algorithms | /problem_4.py | 1,350 | 4.25 | 4 | #!/usr/bin/env python3.8
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
mid_val = 1
low_i = 0
scan_i = 0
high_i = len(input_list)
while (scan_i < high_i):
if input_list[scan_i] < mid_val:
input_list[low_i], input_list[scan_i] = input_list[scan_i], input_list[low_i]
low_i += 1
scan_i += 1
elif input_list[scan_i] > mid_val:
high_i -= 1
input_list[scan_i], input_list[high_i] = input_list[high_i], input_list[scan_i]
else: # input_list[scan_i] == mid_val
scan_i += 1
return input_list
def test_function(test_case):
sorted_array = sort_012(test_case)
# print(sorted_array)
if sorted_array == sorted(test_case):
print("Pass")
else:
print("Fail")
test_function([])
test_function([0, 1, 2])
test_function([2, 0, 1])
test_function([2, 1, 0])
test_function([0, 0, 0, 1, 2, 2, 2, 2])
test_function([0, 0, 0, 0, 2, 2, 2, 2])
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])
| true |
bb06156e51ca1f3b03dac639f37ba9aefefbf565 | dimishpatriot/way_on_the_highway | /5_kyu/product_of_consecutive_fib_numbers.py | 2,527 | 4.34375 | 4 | """The Fibonacci numbers are the numbers in the following integer sequence (Fn):
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...
such as
F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.
Given a number, say prod (for product), we search two Fibonacci numbers F(n)
and F(n+1) verifying
F(n) * F(n+1) = prod.
Your function productFib takes an integer (prod) and returns an array:
[F(n), F(n+1), true] or {F(n), F(n+1), 1} or (F(n), F(n+1), True)
if F(n) * F(n+1) = prod.
If you don't find two consecutive F(m) verifying F(m) * F(m+1) = prodyou
will return
[F(m), F(m+1), false] or {F(n), F(n+1), 0} or (F(n), F(n+1), False)
F(m) being the smallest one such as F(m) * F(m+1) > prod.
Some Examples of Return:
productFib(714) # should return (21, 34, true),
# since F(8) = 21, F(9) = 34 and 714 = 21 * 34
productFib(800) # should return (34, 55, false),
# since F(8) = 21, F(9) = 34, F(10) = 55 and 21 * 34 < 800 < 34 * 55
"""
import pytest
@pytest.mark.parametrize("number, result", [
(0, [0, 1, True]),
(1, [1, 1, True]),
(2, [1, 2, True]),
(6, [2, 3, True]),
(15, [3, 5, True]),
(40, [5, 8, True]),
(104, [8, 13, True]),
(714, [21, 34, True]),
])
def test_production_fib_pozitive(number, result):
assert productFib(number) == result
@pytest.mark.parametrize("number, result", [
(3, [2, 3, False]),
(5, [2, 3, False]),
(14, [3, 5, False]),
(39, [5, 8, False]),
(103, [8, 13, False]),
(713, [21, 34, False]),
(800, [34, 55, False]),
])
def test_production_fib_negative(number, result):
assert productFib(number) == result
def fib_gen(max):
s1 = 0
s2 = 1
yield s1
yield s2
current = 1
while current < max:
yield current
s1 = s2
s2 = current
current = s1 + s2
def productFib(prod):
if prod == 0:
return [0, 1, True]
else:
f = fib_gen(prod + 2) # +2 for 1 and 2
try:
first = next(f)
second = next(f)
while True:
first = second
second = next(f)
if first * second == prod:
return [first, second, True]
elif first * second > prod:
return [first, second, False]
except StopIteration:
pass
"""The best practice for Python is:
def productFib(prod):
a, b = 0, 1
while prod > a * b:
a, b = b, a + b
return [a, b, prod == a * b]
FUN :)
"""
| true |
5b4b8befa78b9383861483c5b82e8ec3e168c88c | badordos/Doliner-labs-Python-2018 | /1) Введение/Task9.py | 504 | 4.375 | 4 | #9. Составьте программу, которая вычисляет площадь равностороннего треугольника
h = float(input('Введите длину высоты равностороннего треугольника '))
a = float(input('Введите длину стороны равностороннего треугольника '))
s = 0.5*a*h
print('Площадь треугольника =',s)
input("\n\nНажмите Enter чтобы выйти")
| false |
2634142a9a139d87a4d5c9ea528e6af8f0c4ece8 | badordos/Doliner-labs-Python-2018 | /4) Цикл For/Task4.py | 658 | 4.125 | 4 | #Напишите программу вычисления совершенных чисел, не превосходящих
#заданного числа N. Совершенным называется такое число,
#сумма делителей которого совпадает с самим числом
#(например, 6=1+2+3)
n = int(input("Введите число N: "))
k = 0
def soversh(n):
s = 0
j = 1
while j <= n/2:
if n % j == 0 :
s += j
j += 1
if s == n:
return 1
else:
return 0
for i in range(1, n + 1):
if soversh(i) != 0 :
print(i)
| false |
f54f1dcae56f083e320c8e28d70011e4c82b7397 | badordos/Doliner-labs-Python-2018 | /1) Введение/Task10.py | 1,111 | 4.1875 | 4 | #Напишите программу вычисления стоимости покупки, состоящей из
#нескольких карандашей, линеек и тетрадей. Их количество и цену задать
#вводом. Ответ вывести в виде:
#Сумма к оплате: … руб … коп.
pencil = int(input('Сколько карандашей вы купили? '))
pencilPrice = float(input('Сколько стоит карандаш, 1шт? '))
ruler = int(input('Сколько линеек вы купили? '))
rulerPrice = float(input('Сколько стоит одна линейка? '))
notebook = int(input('Сколько тетрадей вы купили? '))
notebookPrice = float(input('Сколько стоит одна тетрадь? '))
sum = (pencil*pencilPrice)+(ruler*rulerPrice)+(notebook*notebookPrice)
sum = "%.2f" % sum
sumResult = str(sum)
sumResult = sumResult.split(".")
print ("Сумма к оплате:", sumResult[0],"руб",sumResult[1], "коп.")
input("\n\nНажмите Enter чтобы выйти")
| false |
ca93590acafd4fe2998867e3d48d2cbbc7c07bb6 | badordos/Doliner-labs-Python-2018 | /3) Ветвление/task9.py | 537 | 4.15625 | 4 | #Дано трехзначное число.
#Cоставьте программу, которая определяет, есть ли среди его цифр одинаковые.
x = int(input('Введите трехзначное число'))
xn = str(x)
res = list(xn)
res[0] = int(res[0])
res[1] = int(res[1])
res[2] = int(res[2])
if (res[0]==res[1] or res[0]==res[2] or res[1]==res[2]):
print ('В числе есть одинаковые цифры')
else: print ('В числе нет одинаковых цифр')
| false |
216811b00d29392a016ea8f746fc2b6527d8576d | EshaMayuri/Python-Programming | /Lab1/Source/EvenOdd.py | 645 | 4.3125 | 4 | #var to check if the user wants to continue check for another number
i = 1
while(i != 0):
# take input from user
number = input("Please enter a number: ")
#type casting input from user into integer
n = int(number)
#calculating the remainder when the number is divided by 2
r = n%2
#displaying if the number is even or odd based on the remainder
if (r == 0):
print("The number", n, "entered by user is even")
else:
print("The number", n, "entered by user is odd")
data = input("Do you want to continues(yes/no): ")
if (data.upper() == "YES" ):
i = 1
else:
i = 0 | true |
964e99ea261e62d88ac82005385845f77d59d1c8 | sergiotrivino/Palindromo | /es_palindromo.py | 916 | 4.25 | 4 | '''
Verificar si un texto que termina en punto es un palíndromo (capicúa). Un texto es
palíndromo si se lee lo mismo de izquierda a derecha o de derecha a izquierda.
Ej: “Amor a roma”.
'''
def es_palindromo (texto: str) -> str:
texto = texto.lower() #pasar a minuscula
if (texto[-1] == "."): # condición: si el último caracter es un punto
texto = texto[:-1] # reasignar variable sin el punto
print(texto[::-1]) # mostrar el string de der a izq para comprobar
return "Es un palindromoo"
elif (texto == texto[::-1]): # condicion: si la cadena es un palindromo
print(texto[::-1]) # mmostra el string de der a izq
return "Es un palindromo"
else: # si no concuerda entonces no es palindromo
print(texto[::-1])
return "No es un palindromo"
#pruebas
print(es_palindromo('Amor a roma.'))
print(es_palindromo('HanNaH'))
| false |
aa960c1d9e6574ca86d4cad54694793ce3fed8ec | lakshaysharma12/Hacktoberfest2k21 | /Leap_Year.py | 288 | 4.28125 | 4 | #Python code for leap year
def Leapyr(Yr):
if((Yr % 400 == 0) or
(Yr % 100 != 0) and
(Yr % 4 == 0)):
print("Given Year is a leap Year !");
else:
print ("Given Year is not a leap Year !")
Yr = int(input("Enter your year: "))
Leapyr(Yr) | false |
15dccd7c4a59f4f16a12a3761d1bbe4f8c8d6724 | petitepirate/interviewQuestions | /q0053.py | 1,660 | 4.375 | 4 | # This problem was asked by Apple.
# Implement a queue using two stacks. Recall that a queue is a FIFO
# (first-in, first-out) data structure with the following methods: enqueue,
# which inserts an element into the queue, and dequeue, which removes it.
# _________________________________________________________________________
# Solution
# We can implement this by noticing that while a stack is LIFO (last in first
# out), if we empty a stack one-by-one into another stack, and then pop from the
# other stack we can simulate a FIFO (first in first out) list.
# Consider enqueuing three elements: 1, 2, and then 3:
# stack1: [1, 2, 3]
# stack2: []
# Then emptying stack1 into stack2:
# stack1: []
# stack2: [3, 2, 1]
# Then dequeuing three times:
# 1
# 2
# 3
# Which retains the original order. So when enqueuing, we can simply push to our
# first stack. When dequeuing, we'll first check our second stack to see if any
# residual elements are there from a previous emptying, and if not, we'll empty
# all of stack one into stack two immediately so that the order of elements is
# correct (we shouldn't empty some elements into stack two, pop only some of them,
# and then empty some more, for example).
class Queue:
def __init__(self):
self.s1 = []
self.s2 = []
def enqueue(self, val):
self.s1.append(val)
def dequeue(self):
if self.s2:
return self.s2.pop()
if self.s1:
# empty all of s1 into s2
while self.s1:
self.s2.append(self.s1.pop())
return self.s2.pop()
return None
| true |
c8900b3e30493765478a4e34f5e21c76a990c358 | shams33/Python | /Basics/Decimal_Conversion.py | 237 | 4.40625 | 4 | # Program to convert Decimal number into Binary, Octal and Hexadecimal
dec=int(input("Enter a number:"))
print("The Decimal Value of ",dec,"is:")
print(bin(dec),"in Binary")
print(oct(dec),"in Octal")
print(hex(dec),"in Hexadeciamal")
| true |
563bfd4c1aa6bac9e01c2d22a4a162f2f456e5ff | shams33/Python | /Game/Rock_Paper_Scissor.py | 1,025 | 4.375 | 4 | # Rock Paper Scissor Game
# Program to play Rock Paper Scissor Game with Computer
from random import randint
player = input('Rock (r) , Paper (p) , Scissorr (s) : ')
if(player == 'r'):
print('Rock', end=' ')
elif(player == 'p'):
print('Paper', end=' ')
elif(player == 's'):
print('Scissor', end=' ')
else:
print('???')
print('vs', end=' ')
chosen = randint(1,3)
if(chosen == 1):
computer = 'r'
print('Rock')
elif(chosen == 2):
computer = 'p'
print('Paper')
else:
computer = 's'
print('Scissor')
if(player == computer):
print('DRAW!')
elif(player == 'r' and computer == 's'):
print('Player Wins!')
elif(player == 'r' and computer == 'p'):
print('Computer Wins!')
elif(player == 'p' and computer == 'r'):
print('Player Wins!')
elif(player == 'p' and computer == 's'):
print('Computer Wins!')
elif(player == 's' and computer == 'p'):
print('Player Wins!')
elif(player == "s" and computer == 'r'):
print('Computer Wins!')
else:
print('Try Again!!!')
| false |
8f85990e6548c2c520aae2c24be958cee5907a46 | Sam-G-23/Python-class2020 | /string_functions.py | 650 | 4.25 | 4 | """
program: string_functions.py
Sam Goode
sgoode1@dmacc.edu
6/13/2020
The purpose of this program to to calculate a users input so that they can determine their hourly wage
"""
def multiply_string():
"""
:param string_multiplier: represents the string used to multiply as 'message'
:param n: represents the number 3
:return: the mathematical operation as multi
"""
n = int(input("Please input an integer: "))
string_multiplier = 'message'
multi = n * string_multiplier
return multi
if __name__ == '__main__':
print(multiply_string())
# Everything seems to be working perfectly with no issues
| true |
f3890fe5afb7be6c645da5d542ead7ca0dfb19ea | Sam-G-23/Python-class2020 | /input_validation_with_try.py | 2,107 | 4.34375 | 4 | """
Sam Goode sgoode1@dmacc.edu 6/4/2020
This supposed to take 3 inputs convert to an int and spit out an average score
and on top of that it is supposed to spit out an error if a good input
is given and that input is also an integer and not a str.
I went with the If-else statement per your recommendation I did try doing elif but
I did not know really where to go with it and I felt I was over complicating the code.
Inputs for the user and total to simplify the function below
After opting for your suggestion the code works perfectly
"""
def average():
try:
test1 = int(input("Now your first test grade. "))
if (test1 >= 0) and (test1 <= 100):
print("Thank you.")
else:
print('input not between 0 and 100')
raise ValueError
except:
print('could not convert to int')
raise ValueError
try:
test2 = int(input("Now your second test grade. "))
if (test2 >= 0) and (test2 <= 100):
print("Thank you.")
else:
print('input not between 0 and 100')
raise ValueError
except:
print('could not convert to int')
raise ValueError
try:
test3 = int(input("Now your third test grade. "))
if (test3 >= 0) and (test3 <= 100):
print("Thank you.")
else:
print('input not between 0 and 100')
raise ValueError
except:
print('could not convert to int')
raise ValueError
final_avg_test = ((test1 + test2 + test3) / 3)
return final_avg_test
# Calculating average
# I am not really sure what to make of the PEP8 error except throws up.
# All the code seems to be working for the most part I have not noticed anything wrong with it at least.
if __name__ == "__main__":
name = input("Please input your full name. ")
print("Congrats,", name, "your average test score is:", average())
# Print out the test score
# Assuming good prompts are given, I know a stretch of the imagination this code should work as intended.
| true |
40c670ea291f0ad3b23ae25fca5cef9e23ba750a | sandeshgupta/learning-python | /StringLists.py | 1,378 | 4.40625 | 4 | '''
Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.)
'''
def isPalindrome(stringToCheck):
#A simple way to do it would be to reverse the string using reverse()
#There will be two variable i and j keeping track of start and end of the string
# Variable 'i' will move ahead and 'j' will move backward with each iteration
#In each iteration char at 'i' will be compared to 'j'.
#This will carry on until the middle of string is reached. If middle of string is reached by both 'i' and 'j', string is Palindrome. Middle of the string for any string will be when i==j (odd no of characters in string) or i== j-1 (even no of characters in string)
#j is given assigned to last position of the string
j = len(stringToCheck)-1
#the loop will run from 0th position to mid of the string
for i in range(0,j//2+1):
if i<=j and stringToCheck[i] == stringToCheck[j]:
if i==j or i==j-1:
return True
j -= 1
continue
else:
return False
if __name__ =='__main__':
#User input String
stringToCheck = str(input('Enter a string\n'))
isPalindromeResult = isPalindrome(stringToCheck)
if isPalindromeResult == True:
print('The string \''+stringToCheck+'\' is Palindrome')
else:
print('The string \''+stringToCheck+'\' is NOT Palindrome')
| true |
f14a057046c07967d1d047104d8728d2440cb143 | Roseoketch/Python-Task-5 | /temp_converter.py | 1,384 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 6 06:43:25 2021
@author: USER
"""
def fahrenheit_celsius_converter():
try:
temperature_value = int(input('Input your temperature value (integers only): '))
expected_unit = ['c', 'C', 'f', 'F']
unit_input = input('Input the unit to be converted from, C if Celsius, or F if Fahrenheit: ')
while unit_input not in expected_unit:
print("\n")
print ("The inputted unit is not appropriate, it should be 'C' or 'F'.")
unit_input = input('Input the unit to be converted from, C if Celsius, or F if Fahrenheit: ')
if unit_input == 'F' or unit_input == 'f':
celsius_equivalent = round((5/9) * (temperature_value - 32), 2)
print (str(temperature_value) + ' Fahrenheit equates to ' + str(celsius_equivalent) + ' Celsius')
elif unit_input == 'C' or unit_input == 'c':
fahrenheit_equivalent = round(((1.8 * temperature_value) + 32), 2)
print (str(temperature_value) + ' Celsius equates to ' + str(fahrenheit_equivalent) + ' Fahrenheit')
else:
print ('Your unit input is neither C nor F, input the appropriate unit.')
except ValueError:
print ('The inputted value is not an integer, enter an integer.')
fahrenheit_celsius_converter()
fahrenheit_celsius_converter()
| true |
343a01e65e4697d1c31fb961ffc7dbbbd79946f2 | givewgun/python_misc_year1_CU | /Increasing-digit num.py | 1,080 | 4.28125 | 4 | #Is this an increasing-digit number? --->
''' Code แบบเลข ขวามาซ้าย
n = int(input('Number = '))
while n**2 ==0:
print('It is zero you dumbass')
n = int(input('Number = '))
is_increasing = True
right_of_d = 99
while n>0 :
d = n % 10 #รอบแรก d คือหลักหน่วยของ n รอบสองคือหลักสิบ เทียบจากขวาไปซ้าย
n //= 10
if d >= right_of_d : #ตัวทางซ้ายไม่น้อยกว่าตัวทางขวา
is_increasing =False
break
right_of_d = d
'''
#code แบบstring ชวาไปซ้าย
n = input('Enter digits : ')
is_increasing = True
while int(n)**2 ==0:
print('It is zero you dumbass')
n = input('Enter digits :')
prev_d = ''
for d in n:
if d <= prev_d:
is_increasing = False
break
prev_d = d
if is_increasing :
print('Yes, this is an increasing-digit number')
else:
print('No, this is not an increasing-digit number')
| false |
a7b43c341eb7e0c2a76a41b477a9f0aa96c4ddbc | DMorrisonASC/Mini-Python-Projects | /sphere.py | 501 | 4.59375 | 5 | # sphere.py - Lab 2
#
# Name: Daeshaun Morrison
# Date: 9/1/2020
#
# Given the radius of a sphere, this program computes its
# diameter, surface area, and volume.
# A useful value:
PI = 3.14159265359
# Initialize the radius:r
radius = 4.0
# Calculate the properties of the sphere:
diameter = radius * 2
surfaceArea = 4 * PI * radius**2
volume = (4/3) * PI * radius**3
# Print the results:
print(f" sphere radius = {radius}\n \n diameter = {diameter} \n area = {surfaceArea} \n volume = {volume}")
| true |
bb5c9c08a82386122a9d0cba4d57314ec3a01dbe | DMorrisonASC/Mini-Python-Projects | /speedTrap.py | 1,135 | 4.4375 | 4 | # speedTrap.py - Lab 4
# Author: Daeshaun Morrison
# Date: 9/16/2020
# purpose: To check if the user is driving at legal speed limit
# set a speed limit
legalSpeed = int(input(f"What's the local speed limit?: "))
# Input speed limit
speedTraveling = int(input(f"What speed are you going at?: "))
excessiveSpeeding = legalSpeed + 31
# Conditional that checks to see if legalSpeed vs. speedTraveling
# if legalSpeed is equal to or less than 25, inidicate that the speed is legal
# if speedTraveling is 31 or more than the legalSpeed, then they will be charged with excessive speeding
# Otherwise, print a message indicating that the driver will receive a speeding ticket.
if speedTraveling <= legalSpeed :
print(f"You were going at {speedTraveling} mpg, this is legal")
elif speedTraveling >= excessiveSpeeding:
print(f"You were going at {speedTraveling} mpg, this is 31+ mpg above the speed limit. \nThis is a serious infraction. Your driver’s license suspensed for 15-days")
else:
print(f"You were going at {speedTraveling}, this is above the speed limit. \nYou will be getting a speed ticket!")
| true |
6ac9553a56357b25a09065e341467e16d25f8204 | RamanandPatil/An-Introduction-to-Interactive-Programming-in-Python-Part1 | /Assignments/Week 0a - Expressions/04_AreaofRectangle.py | 840 | 4.21875 | 4 | # http://www.codeskulptor.org/iipp-practice-experimental/#user43_nFMgQQoQwn_2.py
# Compute the area of a rectangle, given its width and height.
# The area of a rectangle is wh, where w and h are the lengths of its sides.
# Note that the multiplication operation is not shown explicitly in this formula.
# This is standard practice in mathematics, but not in programming.
# Write a Python statement that calculates and prints the area
# in square inches of a rectangle with sides of length 4 and 7 inches
###################################################
# Rectangle area formula: width * height
# Student should enter statement on the next line.
print 4 * 7
###################################################
# Expected output
# Student should look at the following comments and compare to printed output.
#28 | true |
49ae971f145db8043ffb303fcc35d7d31d4760a8 | RamanandPatil/An-Introduction-to-Interactive-Programming-in-Python-Part1 | /Assignments/Week 1a - Functions/04_AreaOfRectangle.py | 1,246 | 4.25 | 4 | # http://www.codeskulptor.org/#user43_BHyfDAkGFN_0.py
# Compute the area of a rectangle, given its width and height.
# Write a Python function rectangle_area that takes two parameters width and height
# corresponding to the lengths of the sides of a rectangle and returns the area
# of the rectangle in square inches.
###################################################
# Rectangle area formula
# Student should enter function on the next lines.
def rectangle_area(width, height):
return width * height
###################################################
# Tests
# Student should not change this code.
def test(width, height):
print "A rectangle " + str(width) + " inches wide and " + str(height),
print "inches high has an area of",
print str(rectangle_area(width, height)) + " square inches."
test(4, 7)
test(7, 4)
test(10, 10)
###################################################
# Expected output
# Student should look at the following comments and compare to printed output.
#A rectangle 4 inches wide and 7 inches high has an area of 28 square inches.
#A rectangle 7 inches wide and 4 inches high has an area of 28 square inches.
#A rectangle 10 inches wide and 10 inches high has an area of 100 square inches.
| true |
abf30ce7a352795f7fd30e575ca7bf993b7acdd3 | pushpakjalan02/GeeksForGeeks-Solutions | /Reversal_Right_Rotation.py | 963 | 4.1875 | 4 | # Reversal algorithm for right rotation of an array
# Given an array, right rotate it by k elements.
# URL: https://www.geeksforgeeks.org/reversal-algorithm-right-rotation-array/
import sys
def reverse(list_of_nos, start, end):
while(start < end):
temp = list_of_nos[start]
list_of_nos[start] = list_of_nos[end]
list_of_nos[end] = temp
start = start + 1
end = end - 1
return
def rotate(list_of_nos, nos, rotations):
reverse(list_of_nos, 0, nos - 1)
reverse(list_of_nos, 0, rotations - 1)
reverse(list_of_nos, rotations, nos - 1)
return
def main():
nos = int(input("Enter No. of Nos.: "))
list_of_nos = list(map(int, input("Enter List of Nos.: ").strip().split()))
if(len(list_of_nos) != nos):
sys.exit(0)
rotations = int(input("Enter No. of Rotations.: "))
rotate(list_of_nos, nos, rotations)
print(list_of_nos)
return
if __name__ == "__main__":
main()
| true |
80d9eb733482e882fe29c56d3927cfddd103562a | pushpakjalan02/GeeksForGeeks-Solutions | /Possible_to_Sort_after_Rotation.py | 997 | 4.25 | 4 | # Check if it is possible to sort the array after rotating it
# URL: https://www.geeksforgeeks.org/check-if-it-is-possible-to-sort-the-array-after-rotating-it/
def find_answer(list_of_nos, nos):
i = 0
while(i < nos - 1):
if(list_of_nos[i] > list_of_nos[i+1]):
break
i += 1
if(i == nos - 1):
return "Already Sorted... Hence Possible"
i += 1
while(i < nos - 1):
if(list_of_nos[i] > list_of_nos[i+1]):
break
i += 1
if(i == nos - 1):
if(list_of_nos[0] < list_of_nos[nos - 1]):
return "Not Possible"
else:
return "Possible"
else:
return "Not Possible"
return
def main():
nos = int(input("Enter No. of Nos."))
list_of_nos = list(map(int, input("Enter the list of Nos.").strip().split()))
if(len(list_of_nos) != nos):
return
answer = find_answer(list_of_nos, nos)
print(answer)
return
if __name__ == "__main__":
main()
| true |
40dce94b231ef29f93bb5a7c88c3b919e02e5453 | DanielsOfficial0102/ExerciciosPython | /[Concluído] Logica De Programação l Atividade 2 l Questão 2.py | 551 | 4.1875 | 4 | #Atividade 02 - Lógica de Programação
#3. Faça um programa de computador em que se permita a entrada de uma temperatura em Fahrenheit e converta para graus Célsius, mostrando em seguida o resultado da conversão. Faça uma pesquisa na Internet para descobrir a fórmula de conversão.
'''Permita que o usuário entre com os valores'''
b = float(input('Qual é o valor da base? '))
a = float(input('Qual é o valor da altura? '))
t = (b*a)/2
print('O valor da area entre {} e {} é {}'.format(b,a,t))
input('Aperete ENTER pra sair')
| false |
07c6e153ab11e7093c11946e0dd008efffdbc697 | dgavieira/teste-binamik | /scripts/src/q3.py | 739 | 4.1875 | 4 | """
Given an A array, return the most frequent numbers and its respective frequencies.
Tiebreaker: it is allowed to return any of the tie cases, if occurs.
Example:
Input: [1,5,7,3,2,1, 4, 7, 8, 15, 0, 9, 1, 1, 7, 4]
Output:
1 -> (4 occurrences)
7 -> (3 occurrences)
4 -> (2 occurrences)
"""
import pandas as pd
def top_three(A):
# converts array to a pandas series
A_series = pd.Series(A)
# counts occurrences for all elements
ranking = A_series.value_counts()
# returns the first three elements from the head of the series
return print(ranking.head(3))
if __name__ == '__main__':
A = [1, 5, 7, 3, 2, 1, 4, 7, 8, 15, 0, 9, 1, 1, 7, 4]
top_three(A)
| true |
3cdcc6a945512281c8173f78594280678dd3c9f0 | AviramHan/Phyton_Learn | /targilNum6-Condition.py | 737 | 4.15625 | 4 | ##Condition
'''
NAME=input("Enter a neme: ") # בדיקת תנאים
if(NAME == "aviram"):
print("Hello Aviram\n")
AGE = int(input("Enter a Age: "))
if (AGE == 28):
print("WoW you are 28 years old")
else:
print("you are too young")
else:
print("Where is Aviram?\n") '''
'''
number=int(input("Enter a number: \n")) #בדיקת תנאים גדול שווה וקטן שווה
if(number <= 6):
print(number*2)
else:
print(number-1) '''
'''
name=input("Enter your name: ") # בדיקת תנאים של or And
age=int(input("Enter your age: "))
if((name=="aviram" or name=="Aviram") and (age >= 18)):
print("You can enter to the club!")
else:
print("You are not allowed to enter...") ''' | false |
f93bd098bc69ffdfde1e73a4525c0f1d2a65befd | Try-Try-Again/lpthw | /ex1-22/ex20.py | 1,472 | 4.375 | 4 | #import the argv function from the 'sys' library
from sys import argv
#define the arguments that are being passed into argv
script, input_file = argv
def print_all(f):
print(">>> f=", f)
print(f.read())
print("<<< f=", f)
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print(line_count, f.readline())
#define the 'current_file' variable and assign a value from opening a file
current_file = open(input_file)
#print a string
print("First let's print the whole file:\n")
#call the 'print_all' function with 'current_file' as the argument
print_all(current_file)
#print a string
print("Now let's rewind, kind of like a tape.")
#call the 'rewind' function with 'current_file' as the arguement
rewind(current_file)
#print some text
print("Let's print three lines:")
#define the 'current_line' variable and assign it the value 1
#current line =1
current_line = 1
#call the 'print_a_line' function with 'current_line' and 'current_file'
#as arguments
print_a_line(current_line, current_file)
#increment the value of the 'current_line' variable by 1
#current line = 2
current_line += 1
#call the 'print_a_line' function with 'current_line' and 'current_file'
#as arguments
print_a_line(current_line, current_file)
#increment the value of the 'current_line' variable by 1
#current line = 3
current_line += 1
#call the 'print_a_line' function with 'current_line' and 'current_file'
#as arguments
print_a_line(current_line, current_file)
| true |
90ab03f1b1c23f13ca27effd0f612bedb5d74f4c | Try-Try-Again/lpthw | /ex25/ex25.py | 1,340 | 4.3125 | 4 | #define break_words
def break_words(stuff):
"""This function will break up words for us."""
#use the split fucntion on 'stuff' and return resulting list to 'words'
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
#return the result of running the sorted function on 'words'
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
#pop off the first value in the list 'words', and assign it to 'word'
word = words.pop(0)
#print word
print(word)
def print_last_word(words):
"""Prints the last word after popping it off."""
#pop off the last word in the list 'words' and assign it to 'word'
word = words.pop(-1)
print(word)
def sort_sentence (sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
#research sorted, split, pop,
| true |
baada1b9395aeb1b255e13b89e785c1d212422c1 | Try-Try-Again/lpthw | /ex1-22/ex15.py | 775 | 4.4375 | 4 | #import argv from the sys module
from sys import argv
#unpacks arguments from arg-v and assign those values to two variable
#script, filename = argv
#opens text file and assigns it to a variable
#txt = open(filename)
#prints an fstring including the filename
#print(f"Here's your file {filename}:")
#print the file inside the txt using the read method
#print(txt.read())
#print a basic string
print("Type the filename again:")
#assign value from input to file_again with a custom prompt
file_again = input("> ")
#open whatever file was assigned to file_again using input and assign it's
#contents to txt_again
txt_again = open(file_again)
#print out the file instide text_again using the read method
print(txt_again.read())
#on excercise 5
#here we go!
#wheeeeee!!!!
| true |
81f65cc80df40115bbfd33dc97f8efd6ae9de4a5 | Try-Try-Again/lpthw | /ex33/ex33_drill.py | 797 | 4.25 | 4 | # assign nil to "i"
#create empty list called "numbers"
#while i is less than six, do the following:
def counter(count, stepsize):
numbers = []
for i in range(0, count * stepsize, stepsize):
#print a formatted string 'i'
print(f"At the top i is {i}")
#append current 'i' to the list
numbers.append(i)
#print a string with the value of 'numbers'
print("Numbers now: ", numbers)
#print a formatted string with 'i'
print(f"At the bottom i is {i}")
#print string
print("The numbers: ")
#while theres stuff in 'numbers', pop off an item from 'numbers' and
#put it in num, and then do the following
for num in numbers:
#print 'num'
print(num)
counter(11, 10)
counter(7, 4)
counter(9, 9)
| true |
a530f91fa0bb07ed1e6b4381a44ae02d3984a138 | Parrot023/NeuralNetwork | /XOR_problem.py | 1,358 | 4.21875 | 4 | """
The XOR, or “exclusive or”, problem is a classic
problem in ANN research. It is the problem of using a neural network
to predict the outputs of XOR logic gates given two binary inputs.
An XOR function should return a true value if the two inputs are not equal
and a false value if they are equal
"""
import nn
import matrix_math as mm
import random
from mnist import MNIST
n = nn.NeuralNetwork([2,4,1])
# XOR PROBLEM DATA
inputs = [
mm.Matrix.list_2_matrix([0,1]),
mm.Matrix.list_2_matrix([1,0]),
mm.Matrix.list_2_matrix([1,1]),
mm.Matrix.list_2_matrix([0,0])
]
labels = [
mm.Matrix.list_2_matrix([1]),
mm.Matrix.list_2_matrix([1]),
mm.Matrix.list_2_matrix([0]),
mm.Matrix.list_2_matrix([0]),
]
t_inputs = []
t_labels = []
# Creates training data with a given number of randomized inputs and labels
for i in range(20000):
index = random.randint(0,3)
t_inputs.append(inputs[index])
t_labels.append(labels[index])
# Telling the network to train with the given data
n.train(t_inputs, t_labels)
# Trying all inputs to verify the result
for i in inputs:
result, data = n.feed_forward(i)
print("INPUT:")
i.pretty_print()
print("OUPUT:")
result.pretty_print()
# Saving the network as XOR_model (Dont write a filetype - the filetype is handled by the library)
n.save("XOR_model")
| true |
037079ab1edddc116a131364e7ab1a913ab2229f | sidtrip/hello_world | /CS106A/week2/ass2helpsess/countColours.py | 502 | 4.40625 | 4 | """
Ask user for as many colours as they can think of, in case they
enter'white', they are done.
Print out how many the user input
"""
def main():
#get input from user
colour = input("Enter a colour: ")
colour_count = 1
#keep getting until white
while (colour != "white" ):
colour = input("Enter a colour: ")
colour_count += 1
#track how many so far
print("Total number of colours entered " + str(colour_count))
if __name__ == '__main__':
main() | true |
b60a63d7d851096c7c6dfd0b59228bd2bc62fde9 | sidtrip/hello_world | /6001/week3/lec5/oddtuples.py | 377 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 28 06:29:18 2020
@author: sidtrip
"""
def oddTuples(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
oTup = ()
for element in range(0,len(aTup),2):
oTup += (aTup[element],)
return oTup
r = oddTuples((19, 20, 8, 3, 18, 7, 6, 19))
print(r) | false |
20e837af2c3f3c3f2f2b1cbeac400b8c4a90e6d0 | sidtrip/hello_world | /CS106A/week5/lec14/count_words.py | 925 | 4.5625 | 5 | """
File: count_words.py
--------------------
This program counts the number of words in a text file.
"""
import sys
def count_words(filename):
"""
Counts the total number of words in the given file and
print it out.
"""
count = 0
with open(filename, 'r') as file: # Open file to read
for line in file:
line = line.strip() # Remove newline
word_list = line.split() # Create list of words
for word in word_list: # Print words
print("#" + str(count) + ": " + word)
count += 1
print(filename + " contains " + str(count) + " words")
def main():
"""
The name of the file to count words in should be the first
(and only) command line argument.
"""
args = sys.argv[1:]
if len(args) == 1:
count_words(args[0])
# Python boilerplate.
if __name__ == '__main__':
main()
| true |
299f4b01e62ca5b9f4cc993679f61ec21f7aa4a4 | Rashi1997/Python_Exercises | /38.AverageWordLength.py | 627 | 4.25 | 4 | """Write a program that will calculate the average word length of a text stored in a file (i.e the sum of all the lengths of the word
tokens in the text, divided by the number of word tokens)."""
import re
p=open("C:/Users/rasdhar/Desktop/Python Training/38/punctuations.txt")
punct=list(p.read())
#print(punct)
file=open("C:/Users/rasdhar/Desktop/Python Training/38/text.txt")
text=file.read()
words=re.split("\n| ",text)
frequency=list()
c=0
for word in words:
for w in word:
if w not in punct:
c+=1
frequency.append(c)
c=0
avg=sum(frequency)/len(frequency)
print(avg)
| true |
c2d979dccd8c769b676250b91b16eebca624f236 | GauravAhlawat/Algorithms-and-Data-Structures | /Stack/infixToPostfix.py | 1,189 | 4.1875 | 4 | def infixToPostfix(infixExpr):
"""function to convert infix expression into an Postfix expression"""
# creating a dictionary for precedence of different operators
prec = {}
prec['/'] = 3
prec['*'] = 3
prec['+'] = 2
prec['-'] = 2
prec['('] = 1
operatorStack = Stack() # stack for storing operators
postfixList = [] # list for storing the final postfix expression
tokenList = infixExpr.split() # tokenising the input expression
for token in tokenList:
if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
postfixList.append(token)
elif token == "(":
operatorStack.push(token)
elif token == ")":
topToken = operatorStack.pop()
while topToken != ")":
postfixList.append(topToken)
topToken = operatorStack.pop()
else:
while (not operatorStack.isEmpty()) and (prec[operatorStack.peek()] >= operatorStack.pop()):
postfixList.append(operatorStack.append())
operatorStack.push(token)
while not operatorStack.isEmpty():
postfixList.append(opStakc.pop())
return " ".join(postfixList)
| true |
53d87574d5a738112ac8fd4e6a7c9ac086759fc5 | rysa03/part2_all_task | /part2_task10.py | 769 | 4.4375 | 4 | strings=input('Write something: ')
print('The third character of this string is: ',strings[0:3])
print('Last character of this string is: ',strings[-1])
print('The first five characters of this string are: ',strings[0:5])
print('The last two characters of this string are: ',strings[-2::])
print('The characters of this string with even indices are: ',strings[1::2])
print('The characters of this string with odd indices are: ',strings[0::2])
print('Starting with the second character in the string: ',strings[1])
print('All the characters of the string in reverse order: ',strings[::-1])
print('Every second character of the string in reverse order: ',strings[-1::-2])
#print('Start from last: ',strings[-1:-5:])
print('The length of the given string: ',len(strings)) | true |
ab224e794d912d68d1635d71c8a405fc9c61b14f | wangdongliang1/Algorithm | /LeetCode/Problems/4. Median of Two Sorted Arrays.py | 954 | 4.25 | 4 | '''
There are two sorted arrays nums1 and nums2 of size m and n respectively.
有两个大小分别为m和n的已排序数组nums1和nums2。
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
找到两个排序数组的中值。总的运行时间复杂度应该是O(log(m+n))。
You may assume nums1 and nums2 cannot be both empty.
您可以假设nums1和nums2不能都为空。
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
'''
from typing import List
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
nums3 = sorted(nums1 + nums2)
return nums3[int(len(nums3) / 2)] if len(nums3) % 2 else (nums3[int(len(nums3) / 2)] + nums3[int(len(nums3) / 2 - 1)]) / 2
a = Solution()
print(a.findMedianSortedArrays([1, 2], [3, 4])) | false |
853c9f61e466046f66a8d350a0477cc22d951954 | KhaylaDawson/Python- | /6-20-2018.py | 2,061 | 4.15625 | 4 | ###Building a List Comprehension
##
###The result will be a list
###Add in brackets
##result_list = []
##
###Put in iteration and a base output
###The iteration is the for loop
###The output is x
##result_list = [x for x in range(10)]
##
###Add in the logic
###Which is to square the value of every number met
###While looping through the "orginal list"
##result_list = [x**2 for x in range(10)]
##
###Can add conditions
##set_b = []
##for i in range(1,20):
## if i % 2 == 0:
## set_b.append(i)
##
###To simplify the code to a single line
###The condition could be we written as
##set_b = [i for i in range(1,20) if i % 2 == 0]
##
##
##
###Call for a function
##def squares(num):
## squares = [num**num for num in range(num+1)]
## return squares
##
##
###main
##print(squares(10))
##doubles = [x * 2 for x in range(10)]
##upper_bound = eval(input("Please enter a lower bound(int): ")
##
##lower_bound = eval(input("Please enter an upper bound(int): ")
##
##evens = [print("All of the even numbers between") for i in range(lower_bound,upper_bound)]
##
##evens_div
##
##
##file_name = input("Please enter a file name: ")
##print("All words in the file: ")
##words_contents = [line.strip() for line in open("words.txt", "r")]
##print (words_contents)
##
##
####
####def vowel_count(word):
## count = 0
## for letter in word:
## if letter in "aeiou":
## count += 1
##
##
## if count >= 2:
## return True
## else:
## return False
##
##vowels = [word for word in words_contents if vowel_count(word)]
##
##print("The words in the file that contain 2 or more vowels: ", vowels)
##
##words = ["apple", "ball", "candle", "dog", "Egg", "frog"]
##words = [word.upper() if words[i].upper(words) <= 4 for word in words(len(words))]
##words = result
secret = input("Please enter the secret: ")
secret_message = ["-" if letter.isalpha() else letter for letter in secret]
print("".join(secret_message))
| true |
e78468576c64ce1be4da4c1e5af1720346db1c59 | AbreuHD/FundamentosProgramacion | /Tarea 2/py/11.Programa que acepte un numero y mostrar la mitad, el cuadrado, el doble.py | 517 | 4.3125 | 4 | print("""
____ ___ ____ _ ___ _____ ___ ___
|___ \ / _ \ |___ \ / | / _ \ |___ / / _ \ ( _ )
__) || | | | __) || | _____ | | | | |_ \ | | | | / _ \
/ __/ | |_| | / __/ | ||_____|| |_| | ___) || |_| || (_) |
|_____| \___/ |_____||_| \___/ |____/ \___/ \___/
""")
numero = int(input("Ingresa tu numero: "))
print("La mitad de tu numero es ", numero/2)
print("El cuadrado de tu numero es ", numero**0.5)
print("El doble de tu numero es ", numero+numero) | false |
16f7d2b4e603f0f9d23c32efbc0952c956ec80fd | PBhandari99/Poke_around | /comm_in_arrays.py | 376 | 4.125 | 4 | # Find the common elements of 2 int arrays.
def find_common(array1, array2):
array1_dict = {}
common_elem = []
for i in array1:
if i not in array1_dict:
array1_dict[i] = 1
for j in array2:
if j in array1_dict:
common_elem.append(j)
return common_elem
print(find_common([1, 2, 5, 3, 7, 4, 3], [5, 3, 7, 2, 8, 6]))
| true |
c1183dfc9e5cf3e09b54cb76b2339e57e65ce32c | aukrasnov/dev_dao | /tech_sessions/20190418_SearchTree/linked_list.py | 2,856 | 4.125 | 4 | #
# class LinkedList:
#
# def __init__(self, current):
# self.current = current
# print(self.current)
#
# def add(self, current):
#
# 'LinkedList_2'.format(current) = current
#
# #
# # def delete:
# #
# #
# # def find:
#
#
#
# LinkedList(1)
# LinkedList(2)
# LinkedList(3)
#
#
#
# LinkedList_2 = {'current':2, 'next':3}
# LinkedList_3 = {'current':3, 'next':4}
#
class Node:
link = None
def __init__(self, key, value):
self.key = key
self.value = value
def __str__(self):
return 'key:{0} value:{1}'.format(self.key, self.value)
node1 = Node(1, 1)
node2 = Node(2, 2)
node3 = Node(3, 3)
node4 = Node(4, 4)
node5 = Node(5, 5)
# print(node1.value)
class LinkedList:
first_node = None
last_node = None
def add(self, node):
if self.last_node:
self.last_node.link = node
self.last_node = node
if not self.first_node:
self.first_node = node
def find(self, node_key_to_find):
if not self.first_node:
print('No nodes')
return None
current_node = self.first_node
# проверяю, что нода в списке
while current_node:
if current_node.key == node_key_to_find:
return current_node
current_node = current_node.link
def travers(self):
if self.first_node:
link = self.first_node
while link:
node = link
link = node.link
print(node, node.link)
else:
print('No nodes')
return
def delete(self, node_to_delete):
# проверяю, что список не пустой
if not self.first_node:
print('No nodes')
return
current_node = self.first_node
prev_node = None
# проверяю, что нода в списке
while current_node != node_to_delete:
prev_node = current_node
current_node = current_node.link
prev_node.link = node_to_delete.link
def update(self, node_to_update, new_value):
# проверяю, что список не пустой
if not self.first_node:
print('No nodes')
return
L_List.find(node_key_to_find=node_to_update).value = new_value
L_List = LinkedList()
L_List.add(node=node1)
L_List.add(node=node2)
L_List.add(node=node3)
L_List.add(node=node4)
L_List.add(node=node5)
# print(L_List.first_node.link)
# print(L_List.last_node)
#
# L_List.travers()
#
# L_List.travers()
# print('\n DELETE!!!!! \n')
#
# L_List.delete(node_to_delete=node3)
# L_List.travers()
print(L_List.find(1))
L_List.update(1, 15)
print(L_List.find(1))
# node2.link.value = 15
# print(node3)
| false |
a4930de2b4824dba72b2b7b69db332309450d3b3 | JeanAfonso/CursoUdemyPython | /Aula1/somandoduaslistas.py | 734 | 4.28125 | 4 | """
Considerando duas listas de inteiros ou floats (lista A e lista B)
Some os valores nas listas retornando uma nova lista com os valores somados:
Se uma lista for maior que a outra, a soma só vai considerar o tamanho da
menor.
Exemplo:
lista_a = [1, 2, 3, 4, 5, 6, 7]
lista_b = [1, 2, 3, 4]
=================== resultado
lista_soma = [2, 4, 6, 8]
"""
lista_a = [10, 2, 3, 40, 5, 6, 7]
lista_b = [1, 2, 3, 4]
lista_soma = [x + y for x, y in zip(lista_a, lista_b)]
print(lista_soma)
# lista_soma = []
# for i in range(len(lista_b)):
# lista_soma.append(lista_a[i] + lista_b[i])
# print(lista_soma)
# lista_soma = []
# for i, _ in enumerate(lista_b):
# lista_soma.append(lista_a[i] + lista_b[i])
# print(lista_soma) | false |
2b7e7b394a86b1434d7ce8a5f11847e5a34a76ad | aryanz-co-in/python-comments-variables-type-casting-operators | /variables/assign_none_variable.py | 308 | 4.1875 | 4 | # Assigning None to a variable
# None keyword is used for assigning none value
# (i.e Null in other programming languages, in Python it is None)
name = "David"
print(name)
name = None
print(name)
def has_some_value():
return
print(f"Return from method has_some_value() is {has_some_value()}")
| true |
a7814d25acc57df1cba14b8d3802db89b21b68bb | cavmp/200DaysofCode | /Day5-AdditionPractice.py | 2,536 | 4.34375 | 4 | import random
"""
These constants were implemented as they will be used throughout the code. Furthermore, it will be easier for me to
change these if I want to try different numbers.
"""
NUM_MIN = 10 # The assignment requires a minimum number of 99 which will be used in the code below
NUM_MAX = 99 # The assignment requires a maximum number of 99 which will be used in the code below
MAXIMUM_CORRECT = 3 # The assignment requires the user to get 3 problems correct in a row
def main():
"""
I did this code after learning Python's control flows and I applied a lot of my code here from that.
First, I started coding as a whole. I decomposed the code to 2 main functions: addition_question and
ending_statement. Then, I moved on to define each functions to make an addition game.
"""
addition_questions() # Randomly generates addition problems for the user and checks the answer from the user
ending_statement() # Closing statement for when the user gets 3 questions in a row
def addition_questions():
correct_answers = 0 # To start, user has 0 correct answers
while correct_answers < 3: # To guarantee that the user has 3 correct answers in a row
num1 = random.randint(NUM_MIN, NUM_MAX) # Will generate a random number from num_min to num_max
num2 = random.randint(NUM_MIN, NUM_MAX) # Will generate another random number from num_min to num_max
real_answer = num1 + num2 # Real answer of the addition question will go here
print("What is " + str(num1) + " + " + str(num2) + "? ")
user_answer = int(input("Your answer: ")) # User's answer in the terminal
if real_answer != user_answer: # A condition for when the real answer does not equal to the user's answer
print("Incorrect, the answer is " + str(real_answer) + ".") # Will tell the user the correct answer
correct_answers = 0 # Restarts answers correct to 0 so the while loop also restarts
else: # A condition for when the real answer is equal to the user's answer
correct_answers += 1 # Adds 1 to answers correct
print("Correct! " + "You've gotten " + str(correct_answers) + " correct in a row.")
# Informs the user his/her numbers of correct answers in a row
def ending_statement():
print("Congratulations! You mastered addition.") # The ending statement will be printed in the terminal
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
main()
| true |
32766526b96eb49bba1871517423ea15c3d55cbe | Reynald205/Python-Projects | /Tut11.py | 663 | 4.25 | 4 | answer = lambda x: x*7 # Sub for function.
print(answer(5))
date, item, price = ['December 23, 1956', 'Boxing Gloves', 8.51] # Called unpacking a list.
first = ['Tom', 'Bob', 'Dave']
second = ['Hanks', 'Sagat', 'Chapelle']
names = zip(first, second) # zip takes two list to combine into a new list
for a, b in names:
print(a, b)
def Drop_first_and_last(grades):
first, *middle, last = grades # With the star the middle combines all the things except first and last
avg = sum(middle) / len(middle)
print(avg)
Drop_first_and_last([55, 76, 88, 96, 86, 76])
Drop_first_and_last([55, 76, 88, 96, 86, 76, 78, 89, 90, 99, 100, 56]) | true |
c919b5d66f199cd0e6e50ebc96e6bd60582a530a | Bulgakoff/PyAlg | /Lesson03/task_2.py | 877 | 4.15625 | 4 | """
Задание_2. Во втором массиве сохранить индексы четных элементов первого массива.
Например, если дан массив со значениями 8, 3, 15, 6, 4, 2, то во второй массив
надо заполнить значениями 1, 4, 5, 6 (или 0, 3, 4, 5 - если индексация начинается с нуля),
т.к. именно в этих позициях первого массива стоят четные числа.
"""
import random
SIZE = 5 # 1_000_000
MIN_ITEM = 0
MAX_ITEM = 1000 # 10_000_000
array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
print(array)
odd_ind = []
for i in range(len(array)):
if array[i] % 2 == 0:
odd_ind.append(i)
print(f'Исходный массив: {array}, результат: {odd_ind}') | false |
1f5e4b9c8b8ac578cda1956e71d4bd0d6742fa69 | RMedeirosCosta/tex | /bancos_dados_para_biologia/t3/python/ex5.py | 1,330 | 4.15625 | 4 | # Autor: Ricardo Medeiros da Costa Junior
# Titulo: Exercicio 5
# Data: 22/03/2016
# Objetivo: Dado um numero natural de base binaria, transformalo para base decimal
# Entrada: numero (inteiro)
# Saida: O numero em base decimal
# Obs.: Verificar se o numero e natural e se e de base binaria e depois imprimir o numero convertido em base decimal
def is_binario(numero):
for i in numero:
if (i not in ['0','1']):
return False
return True
def converter_decimal(numero_binario):
somatorio = 0
expoentes = range((len(numero_binario)-1), -1, -1)
for indice, unidade in enumerate(numero_binario):
somatorio += (int(unidade) * (2**expoentes[indice]))
return str(somatorio)
def main():
try:
numero = int(input("Digite um numero natural em base binaria: "))
if (numero < 0):
raise ValueError
# Faco o casting para string para facilitar nas verificacoes
numero_str = str(numero)
if (not is_binario(numero_str)):
raise ValueError
print("O numero "+numero_str+" na base decimal e: "+converter_decimal(numero_str))
except ValueError:
print("Numero invalido. Programa sera reiniciado. POR FAVOR! \n"
"Informe um numero natural de base binaria. Exp: 10110, 01, 10001110")
main()
main()
| false |
031090671687413e62aba6af7aaf1c81e53a7976 | shahbazakon/HackerRank-Problems | /HR_Running_Time_and_Complexity_Prime_no.py | 1,450 | 4.125 | 4 | # ==================================================================================
"""
Task
A prime is a natural number greater than that has no positive divisors
other than and itself. Given a number, , determine and print whether it
is Prime or Not Prime.
Note: If possible, try to come up with a 0(sqrt(n)) primality algorithm, or see what
sort of optimizations you come up with for an 0(n) algorithm. Be sure to check
out the Editorial after submitting your code.
"""
# ===================================================================================
"""
#Not work on very large value.
def isPrime(n):
if n is 1:
return print("Not prime")
elif n < 0:
-n
flag = 0
for i in range(2, n):
if n % i == 0:
flag = 1
if flag is 1:
print("Not prime")
else:
print("Prime")
T = int(input())
Lst = []
for j in range(T):
Lst.append(int(input()))
for k in range(T):
isPrime(Lst[k])
"""
for _ in range(int(input())):
num = int(input())
if num == 1:
print("Not prime")
else:
if num % 2 == 0 and num > 2:
print("Not prime")
else:
for i in range(3, int(num**(1/2))+1, 2):
if num % i == 0:
print("Not prime")
break
else:
print("Prime")
# ===================================================================================
| true |
8d3b5552489d6cfe717b25fa7f11119cdbf19a1f | shahbazakon/HackerRank-Problems | /HR_Symmetric_Difference.py | 1,008 | 4.21875 | 4 | # ==================================================================#
"""
Task
Given 2 sets of integers, M and N, print their symmetric difference
in ascending order. The term symmetric difference indicates
those values that exist in either M or N but do not exist in both.
Input Format
The first line of input contains an integer, M.
The second line contains M space-separated integers.
The third line contains an integer, N.
The fourth line contains N space-separated integers.
Output Format
Output the symmetric difference integers in ascending order,
one per line.
"""
# ==================================================================#
s1 = int(input())
a = map(int, input().split())
set1 = set(a)
s2 = int(input())
b = map(int, input().split())
set2 = set(b)
diff1 = list(set2.difference(set1))
diff2 = list(set1.difference(set2))
MyList = diff1 + diff2
MyList.sort()
for i in range(0, len(MyList)):
print(MyList[i])
# ==================================================================#
| true |
befdc83c414b61f6a0b32cb06cf1e18592ef47f1 | avvRobertoAlma/esercizi-introduzione-algoritmi | /algoritmi_ordinamento/insertion_sort.py | 754 | 4.15625 | 4 | """
insertion sort è un algoritmo in cui si scorre una lista dalla posizione i+1 (con i che parte da 0)
e si spostano tutti gli elementi da j=i-1 a destra se maggiori di lista[i]
"""
def insertion_sort(lista):
for i in range(1, len(lista)):
# estrazione elemento corrente:
current = lista[i]
# sposto tutti gli elementi del vettore precedente [1...i-1] a dx di una unità se current
# è minore
j = i-1
while j>=0 and lista[j] > current:
lista[j+1] = lista[j]
j -= 1
# a questo punto so che current è minore di lista[j]
lista[j+1] = current
return lista
if __name__ == "__main__":
l = [4, 2, 6, 1, 9, 12, 5]
print(insertion_sort(l))
| false |
193e3bb6a3e51672a6899f0392d17216667edb65 | TomJamesGray/data_types | /queue.py | 851 | 4.25 | 4 | """
Basic implementation of a queue in python
"""
class Queue(object):
def __init__(self,initial):
self.head = QueueVal(initial)
self.tail = None
def enqueue(self,data):
if self.tail == None:
self.tail = QueueVal(data)
self.tail.before = self.head
self.head.after = self.tail
else:
tmp = QueueVal(data)
self.tail.after = tmp
self.tail = tmp
def get(self):
tmp = self.head
val = tmp.data
self.head = tmp.after
return val
class QueueVal(object):
def __init__(self,data):
self.data = data
self.before = None
self.after = None
if __name__ == "__main__":
q = Queue("1st")
q.enqueue("2nd")
q.enqueue("3rd")
print(q.get())
print(q.get())
print(q.get())
| false |
4ed83646906356909587e618eb8a7f540d7f197c | rahulrishi01/Data-Structure | /python/BinaryTree/height_binary_tree.py | 1,825 | 4.125 | 4 | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
class Traverse:
def __init__(self, root):
self.head = root
def inorder(self):
if self.head:
self._inorder(self.head)
else:
print("Tree is Empty")
def _inorder(self, root: Node):
if not root:
return
self._inorder(root.left)
print(str(root.data) + ' -> ')
self._inorder(root.right)
class HeightTree:
def __init__(self, root: Node):
self.head = root
def height(self):
if self.head:
return self._height(self.head)
else:
return 0
def _height(self, root: Node):
if not root:
return 0
else:
return 1 + max(self._height(root.left), self._height(root.right))
class SizeTree:
def __init__(self, root: Node):
self.head = root
def size(self):
if self.head:
return self._size(self.head)
else:
return 0
def _size(self, root: Node):
if not root:
return 0
else:
return 1 + self._size(root.left) + self._size(root.right)
if __name__ == '__main__':
binary_tree = Node(5)
binary_tree.left = Node(3)
binary_tree.right = Node(7)
binary_tree.left.left = Node(2)
binary_tree.left.right = Node(4)
binary_tree.left.left.left = Node(1)
binary_tree.right.left = Node(6)
binary_tree.right.right = Node(8)
b_traverse = Traverse(binary_tree)
b_traverse.inorder()
bt_height = HeightTree(binary_tree)
print("Height of the Binary tree is: {}".format(bt_height.height()))
bt_size = SizeTree(binary_tree)
print("Size of the Binary tree is: {}".format(bt_size.size()))
| false |
04226f1f0bb4b440a98199a790e5f7327d5c43b3 | rahulrishi01/Data-Structure | /python/String/add_space_in_front_of_string.py | 820 | 4.375 | 4 | """
Given a string that has set of words and spaces, write a program to move all spaces to front of string, by traversing the string only once.
Examples:
Input : str = "geeks for geeks"
Output : ste = " geeksforgeeks"
Input : str = "move these spaces to beginning"
Output : str = " movethesespacestobeginning"
There were four space characters in input,
all of them should be shifted in front.
"""
def move_space_front(text):
text_lngth = len(text)
new_text = ''
for ch in text:
if ch != ' ':
new_text += ch
spaces = ' '*(len(text) - len(new_text))
print(len(spaces))
modified_text = spaces + new_text
return modified_text
if __name__ == '__main__':
text ='move these spaces to beginning'
modified_text = move_space_front(text)
print(modified_text)
| true |
6484f5b226022f4a847be952059cca70f2f35b19 | rahulrishi01/Data-Structure | /python/String/longest_word_in_string.py | 598 | 4.34375 | 4 | """
Longest Word
Have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string.
If there are two or more words that are the same length, return the first word from the string with that length.
Ignore punctuation and assume sen will not be empty.
Examples
Input: "fun&!! time"
Output: time
Input: "I love dogs"
Output: love
"""
import re
def LongestWord(sen):
# code goes here
return max((re.sub('[^\sA-Za-z0-9]+', '', sen)).split(' '), key=len)
# keep this function call here
print(LongestWord(input()))
| true |
75cfa7b1cdcdb3926ce0c71f6d9249ec61b76560 | desh-woes/Algorithms-and-Data-structures | /Sorting Algorithms/Quick_Sort.py | 1,440 | 4.1875 | 4 | # Basic quick sort interface
def quick_sort(arr):
quick_sort2(arr, 0, len(arr)-1)
return arr
# Recursive quick sort function
def quick_sort2(arr, first, last):
# While this list does not contain only one element:
if first < last:
# Call the partition function which sorts both sides of the pivot
p = partition(arr, first, last)
# Call the quick sort function on the other halves of the array recursively
quick_sort2(arr, first, p-1)
quick_sort2(arr, p+1, last)
# Function to generate our pivot index using the median of three values approach
def get_pivot(arr, first, last):
middle = (first+last)//2
pivot = last
if arr[last] < arr[middle]:
if arr[middle] < arr[last]:
pivot = middle
elif arr[last] < arr[first]:
pivot = last
return pivot
# Partition function to sort our pivot value
def partition(arr, first, last):
pivot_index = get_pivot(arr, first, last)
pivot_value = arr[pivot_index]
arr[pivot_index], arr[first] = arr[first], arr[pivot_index]
border = first
for i in range(first, last+1):
if arr[i] < pivot_value:
border += 1
arr[i], arr[border] = arr[border], arr[i]
arr[first], arr[border] = arr[border], arr[first]
return border
# Test parameters
arr_test = [106, 56549, 86547, 5477, 7667, -56756, 6467, 367, 782, -451, 0]
print(quick_sort(arr_test))
| true |
c478551717950f629d68156573eb80ad604d8b69 | desh-woes/Algorithms-and-Data-structures | /Implementing abstract data types/Linked List - python/Singly_Linked List.py | 2,789 | 4.25 | 4 | # Implementing the node class
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Create the node wrapper
class LinkedList:
def __init__(self, data=None):
if data is None:
self.head = data
else:
self.head = Node(data)
self.tail = self.head
# Implement append function
def append(self, data):
new_node = Node(data)
cur = self.head
if cur is not None:
while cur.next is not None:
cur = cur.next
cur.next = new_node
self.tail = cur.next
else:
self.head = new_node
# Implement count/len function
def length(self):
cur = self.head
count = 0
if cur is not None:
count = 1
while cur.next is not None:
count += 1
cur = cur.next
return count
# Implement Index get function
def get(self, index):
if index >= self.length():
print('You have given an index that is out of range')
return None
else:
cur_index = 0
cur = self.head
while True:
if cur_index == index:
return cur.data
else:
cur = cur.next
cur_index += 1
# Function to display the contents of the linked list
def display(self):
cur = self.head
while cur.next is not None:
print(cur.data)
cur = cur.next
print(cur.data)
# Function to reverse the contents of the linked list
def reverse(self):
# Current is a pointer to head
cur = self.head
# If out pointer is null, then our list is empty so return it
if cur is None:
return cur
# Else if our list is not empty
else:
# While we are not on our last element
while cur.next is not None:
# Store our next value as temp
temp = cur.next
# Switching variable in position 1
if cur == self.head:
cur.next = None
temp_2 = temp.next
temp.next = cur
self.head = temp
cur = temp_2
# Switching variables in other positions
else:
cur.next = self.head
self.head = cur
cur = temp
# Switching the last variable
cur.next = self.head
self.head = cur
# Test params
test = LinkedList(1)
test.append(2)
test.append(3)
test.display()
# print(test.get(0))
test.reverse()
test.display() | true |
da9394360b7bc24d11360d5a77f13795117f0900 | desh-woes/Algorithms-and-Data-structures | /Iteration and selection control/Lists.py | 512 | 4.1875 | 4 | # 1. Modify the given code so that the final list only contains a single copy of each letter.
word_list = ['cat','dog','rabbit']
letter_list = [ ]
for a_word in word_list:
for a_letter in a_word:
if a_letter not in letter_list:
letter_list.append(a_letter)
print(letter_list)
# 2. Redo the given code using list comprehensions. For an extra challenge, see if you can
# figure out how to remove the duplicates.
letter_list2 = [set(x for x in y) for y in word_list]
print(letter_list2)
| true |
0e69368740d53bdae4f49863e2e7c50dd37b6725 | desh-woes/Algorithms-and-Data-structures | /Recursion/Converting an Integer to a String in Any Base.py | 384 | 4.21875 | 4 | # Recursive algorithm to keep reducing the integer to it's base case and return a string in the new base
def convert_tostr(number, base):
conversion_string = "0123456789ABCDEF"
if number < base:
return conversion_string[number]
else:
return convert_tostr(number//base, base) + conversion_string[number%base]
# Test parameters
print(convert_tostr(7, 8))
| true |
4c316bfc27e42c28b20a7d04f03b62b0993981cc | tabletenniser/leetcode | /9_palindrome_number.py | 886 | 4.28125 | 4 | """
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
"""
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
reverse = 0
original_x = x
while True:
reverse += x % 10
x /= 10
if x == 0:
break
reverse *= 10
return reverse == original_x
| true |
b911e4c707b7b975b3e61896e10d0aeeb7b741d0 | tabletenniser/leetcode | /694_number_of_distinct_island.py | 1,186 | 4.15625 | 4 | '''
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Count the number of distinct islands. An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other.
Example 1:
11000
11000
00011
00011
Given the above grid map, return 1.
Example 2:
11011
10000
00001
11011
Given the above grid map, return 3.
Notice that:
11
1
and
1
11
are considered different island shapes, because we do not consider reflection / rotation.
Note: The length of each dimension in the given grid does not exceed 50.
'''
class Solution(object):
def numDistinctIslands(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
s = Solution()
print s.numDistinctIslands([[]])
print s.numDistinctIslands([[0,0,0,0,0,0,0,0]])
print s.numDistinctIslands(
[[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 1, 1],
[0, 0, 0, 1, 1]])
print s.numDistinctIslands(
[[1, 1, 0, 1, 1],
[1, 0, 0, 0, 0],
[0, 0, 0, 0, 1],
[1, 1, 0, 1, 1]])
| true |
785c06f1281ec0c6d7b75554d96b536b7c247ad8 | tabletenniser/leetcode | /394_decode_string.py | 1,637 | 4.15625 | 4 | '''
Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
'''
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
count_stack = []
str_stack = []
i = 0
cur_num, cur_str = [], []
while i < len(s):
if '0' <= s[i] <= '9':
cur_num.append(s[i])
elif s[i] == '[':
count_stack.append(int(''.join(cur_num)))
str_stack.append(''.join(cur_str))
cur_num = []
cur_str = []
elif s[i] == ']':
num = count_stack.pop()
old_str = str_stack.pop()
cur_str = list(old_str+(''.join(cur_str))*num)
else:
cur_str.append(s[i])
i += 1
return ''.join(cur_str)
s = Solution()
assert s.decodeString("3[a]2[bc]") == "aaabcbc"
assert s.decodeString("3[a2[c]]") == "accaccacc"
assert s.decodeString("2[abc]3[cd]ef") == "abcabccdcdcdef"
| true |
d17068122eb33631b56d64619534f321e0a5fa9f | tabletenniser/leetcode | /92_reverse_linked_list_2.py | 1,153 | 4.21875 | 4 | '''
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 <= m <= n <= length of list.
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x, n):
self.val = x
self.next = n
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
root = ListNode(None, None)
root.next = head
prev, cur = root, head
i = 1
while i < n:
if i >= m:
next_node = cur.next
assert(next_node)
cur.next = next_node.next
next_node.next = prev.next
prev.next = next_node
else:
prev = prev.next
cur = cur.next
i += 1
return root.next
n1 = ListNode(1, None)
n2 = ListNode(2, n1)
n3 = ListNode(3, n2)
s = Solution()
s.reverseBetween(n3, 1, 3)
| true |
357c5bef133a5d8331ebcb097f4e727dd35936fa | mayankdubey1996/Data-Structure-Algorithm | /Hashing/hashing.py | 486 | 4.21875 | 4 | """ Time Complexity
To create hashTable O(n)
To get value from hashTable O(1)"""
""" Space complexity O(n) """
def hashing(array):
h = {}
for i in range(len(array)):
value = array[i]
idx = i
h[value] = idx
return h
def search(hash_map, target):
if target in hash_map:
idx = hash_map[target]
return idx
return -1
array = [5,7,4,1,3,8]
hash_map = hashing(array)
z = search(hash_map, 1)
print(z) | false |
e541074da93bade2ee562a5525a06217cb14f405 | inki-hong/python-fast | /numbers.py | 712 | 4.15625 | 4 | my_number_1 = 100 # Python int data type
my_number_2 = 3.14 # Python float data type
print(my_number_1)
print(my_number_2)
print(type(100))
print(type(my_number_2))
print(type('Hello, World!'))
print()
a = 5
b = 2
# Addition, subtraction, multiplication, and division
print(a + b)
print(a - b)
print(a * b) # asterisk
print(a / b)
print()
# Exponentiation, integer division, and modulo
print(a ** b)
print(a // b) # integer division (floor division)
print(a % b)
print('----------------------------------------')
#
a = 1.414
b = 3.14
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print()
print(a ** b)
print(a // b)
print(a % b)
print('----------------------------------------')
#
| false |
2797509793071f6ae8999ab5f6c6ddf7a9f363b9 | bishboria/learn_python_the_hard_way | /ex16.py | 964 | 4.40625 | 4 | from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w+')
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
new_line = "\n"
output = "%s%s%s%s%s%s" % (
line1,
new_line,
line2,
new_line,
line3,
new_line
)
target.write(output)
print "And finally, we close it."
target.close()
print "Oh, open the file back up! Let's see what you wrote:"
target = open(filename)
print target.read()
target.close()
# Extra Credit 4: 'w' was passed as an extra parameter as this signifies
# that you want to file to be written to.
# Extra Credit 5: if a file is opened up with 'w' or 'w+' then no truncate is necessary.
| true |
6d79f0324f2579343d7fa8789f5a210ef46f58ab | primatera/py4e | /py4e/data_structures/assignment6_5.py | 380 | 4.15625 | 4 | # Assignment 6.5
# Write code using find() and string slicing (see section 6.10) to extract the number at the end of the line below.
# Convert the extracted value to a floating point number and print it out.
text = "X-DSPAM-Confidence: 0.8475";
# parse out number
colon_position = text.find(':')
number = text[colon_position+1: ].strip()
number = float(number)
print(number) | true |
6197e89c77ec337d6ed74126c7deb2f5cc065b4d | Oleksijt/my_python_learning | /t3_2715.py | 794 | 4.40625 | 4 | """ This Script is Task#3 in Programming_education course.
The task is to calculate squares of numbers in range from
0 to 100000000000.
The code should be able to execute on very simple computer
(without huge amount of virtual memory, CPU, etc.).
Code should works under both versions of Python (2.X, 3.X).
In result script runs in Python 3.6 an also Python 2.7.15.
Python 2.7.15 runs with max_range up to 1000000.
"""
import sys
def square_large_list(list_range): # creates generator with max_range
for num in range(0, list_range):
yield num * num # returns squared iterator
max_range = 100000000000
if sys.version_info < (3, 0, 0):
max_range = 1000000 # for Python 2.X max_range limited to 1000000
for number in square_large_list(max_range):
print(number)
| true |
3a87dc6ad821f7e8c62d8f29885de60da3d5c580 | zongzake/MyScript_019 | /Input.py | 361 | 4.1875 | 4 | #Initialize a variable with a user-specified value.
user=input("I am Python. What is your name? :")
#Output a string and a variable value.
print("Welcome",user)
#Initialize another variable with a user-specified value.
lang=input("Favorite programming language?:")
#Output a string and a variable value.
print(lang,"Is" ,"Fun",sep="*",end="!\n")
| true |
1da93060295a6523441c38a46e8b5f0183e49b6d | lena-prokopenko/codecool-bp-2016-1 | /calc.py | 532 | 4.15625 | 4 |
operation = input("Enter operation: ")
x = int(input("Enter your first number or LETTER to EXIT: "))
y = (input("Enter your second number: "))
if operation == "*":
result = x * y
print(result)
elif operation == "/":
result = x / y
print(result)
try:
exec(result)
except ZeroDivisionError:
print("Can't divide by zero")
elif operation == "+":
result = x + y
print(result)
elif operation == "-":
result = x - y
print(result)
else:
exit()
print("Result: ", result)
| true |
87bb9131d8b8cd17825fb0993d407564c0bae3aa | guihlr/PythonExercicios | /ex060-Cáculo do Fatorial.py | 1,046 | 4.1875 | 4 | # Exercício Python 060: Faça um programa que leia um número qualquer e mostre o seu fatorial.
# Ex: 5! = 5 x 4 x 3 x 2 x 1 = 120
# from math import factorial
# n = int(input('Digite um número para calcular seu Fatorial: '))
# f = factorial(n)
# print('O fatorial de {} é {}.'.format(n, f))
n = int(input('Digite um número para calcular seu Fatorial: '))
c = n
f = 1
print('Calculando {}! = '.format(n), end='')
while c > 0:
print('{}'.format(c), end='')
print(' x ' if c > 1 else ' = ', end='')
f *= c
c -= 1
print('O fatorial de {} é {}.'.format(n, f))
n = int(input('Digite um número para calcular seu fatorial: '))
print('Calculando o fatorial com o < for >')
f = 1
print('Calculando {}! = '.format(n), end='')
for x in range(n, 0, -1):
print('{}'.format(x), end='')
print(' x ' if x > 1 else ' = ', end='')
f *= x
print('{}'.format(f))
""" Meu Programa """
n = int(input('Digite número para calular seu Fatorial: '))
f = 1
c = n
while c > 0:
f *= c
c -= 1
print(f'O fatorial de {n} é {f}')
| false |
f3655982f71352a2c2935268a655f5d1068debce | manobendro/Modern-Computer-Architecture-and-Organization | /Chapter01/Answers to Exercises/src/Ex__3_single_digit_subtractor.py | 861 | 4.15625 | 4 | #!/usr/bin/env python
"""Ex__3_single_digit_subtractor.py: Answer to Ch 1 Ex 3
(single digit subtractor)."""
import sys
# Perform one step of the Analytical Engine subtraction
# operation. a and b are the digits being subtracted (a - b),
# c is the carry: 0 = borrow, 1 = not borrow
def decrement_subtractor(a, b, c):
a = (a - 1) % 10 # Decrement left operand, to 9 if wrapped
b = b - 1 # Decrement accumulator
if a == 9: # If accum reached 9, decrement carry
c = c - 1
return a, b, c;
# Subtract two decimal digits. The difference is returned as
# digit1 and the carry output is 0 (borrow) or 1 (not borrow).
def subtract_digits(digit1, digit2):
carry = 1
while digit2 > 0:
[digit1, digit2, carry] = decrement_subtractor(
digit1, digit2, carry)
return digit1, carry
| true |
3e843cb42ea3242471f33c304ebc75cc3b1bfb9f | panok90/lesson-4 | /task-7.py | 855 | 4.125 | 4 | """Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение.
При вызове функции должен создаваться объект-генератор. Функция должна вызываться следующим образом: for el in fact(n).
Функция отвечает за получение факториала числа, а в цикле необходимо выводить только первые n чисел,
начиная с 1! и до n!."""
def fact():
number = 1
fact_number = 8
for item in range(1, fact_number + 1):
number *= item
yield item
print(f'Факториал числа {fact_number}! равен: {number}')
for el in fact():
print(f'{el}!')
| false |
8e9c0c9ee233aef4bc2b7cbf6bcc922a6a344795 | hjkim88/EPI | /codes/Arrays/5_8_p48.py | 2,760 | 4.125 | 4 | ###
# File name : 5_8_p48.py
# Author : Hyunjin Kim
# Date : Jun 11, 2019
# Email : firadazer@gmail.com
# Purpose : Write a program that takes an array A of n numbers, and rearranges A's elements to get a new array
# B having the property that B[0] <= B[1] >= B[2] <= B[3] >= B[4] <= B[5] >= ...
#
# Example : input: [3, 4, 1, 54, 32, 42, 7, 5, 43] -> output: [3, 4, 1, 54, 32, 42, 5, 43, 7]
# input: [34, 2, 54, 64, 23, 43, 25, 5] -> output: [2, 54, 32, 64, 23, 43, 5, 25]
# input: [100, 43, 2, 53, 64, 54, 34, 6] -> output: [34, 100, 6, 53, 2, 64, 43, 54]
# input: [53, 6, 34, 23, 64, 34, 64, 34] -> output: [6, 53, 34, 64, 23, 34, 34, 63]
# input: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] -> output: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
#
# Instruction
# 1. import 5_8_p48.py
# 2. Run the function 5_8_p48.start()
# 3. The results will be generated in the console
###
### import modules
import timeit
### a function starting this script
def start():
print("5_8_p48.py")
start_time = timeit.default_timer()
print("fluctuation([3, 4, 1, 54, 32, 42, 7, 5, 43]) = ", fluctuation([3, 4, 1, 54, 32, 42, 7, 5, 43]))
print("fluctuation([34, 2, 54, 64, 23, 43, 25, 5]) = ", fluctuation([34, 2, 54, 64, 23, 43, 25, 5]))
print("fluctuation([100, 43, 2, 53, 64, 54, 34, 6]) = ", fluctuation([100, 43, 2, 53, 64, 54, 34, 6]))
print("fluctuation([53, 6, 34, 23, 64, 34, 64, 34]) = ", fluctuation([53, 6, 34, 23, 64, 34, 64, 34]))
print("fluctuation([5, 5, 5, 5, 5, 5, 5, 5, 5, 5]) = ", fluctuation([5, 5, 5, 5, 5, 5, 5, 5, 5, 5]))
print("Execution Time: ", timeit.default_timer() - start_time)
### a bruce-force approach would be iteratively find bigger/smaller number than the previous one
### time complexity: O(n^2), space complexity: O(1)
### a more efficient one is to swap consecutive values sequentially
### time complexity: O(n), space complexity: O(1)
### only two for loops are needed
### for example, [5, 3, 6, 8], we do it with indicies of 0 and 2
### [5, 3, 6, 8] -> [3, 5, 6, 8]
### then we check indicies of 1 and 3,
### [3, 5, 6, 8] -> [3, 6, 5, 8]
### here, only two for loops are OK because we already know 3 < 5 and 6 < 8
### and if 5 < 6, then 6 is already bigger than 3, since "3 < 5" is already ordered in the first step loop
### likewise, 5 < 8 because we already know 5 < 6 < 8 and the "6 < 8" is already ordrered in the first step loop
def fluctuation(A):
for i in range(0, len(A)-1, 2):
if A[i] > A[i+1]:
A[i], A[i+1] = A[i+1], A[i]
for i in range(1, len(A)-1, 2):
if A[i] < A[i+1]:
A[i], A[i + 1] = A[i + 1], A[i]
return A
start()
| true |
d1887de14b4c1609167b3a6538c12887c294fd56 | Metheus97/Meus_Exerccicios_de_Python | /ex93.py | 823 | 4.1875 | 4 | '''Programa de calculo de aproveitamento de um jogador de futebol no campeonato'''
jogador = {'nome': str(input('Qual o nome do jogador? '))}
partidas = int(input('Numero de partidas jogadas: '))
gol = []
tot = 0
for c in range(0, partidas):
gols = (int(input(f'Quantos gols ele fez na {c + 1}º partida: ')))
gol.append(gols)
tot += gols
jogador['gols'] = gol[:]
jogador['total'] = tot
# primeira apresentação
print('♦-' * 30)
print(jogador)
print('♦-' * 30)
# segunda apresentação
for v, k in jogador.items():
print(f'O campo {v} tem o valor {k}')
print('♦-' * 30)
# Terceira apresentação
print(f'O jogador {jogador["nome"]} jogou {partidas} partidas')
for u in range(0, partidas):
print(f' --->Na partida {u + 1} ele fez {gol[u]} gols ')
print(f'Total de gols feitos é de {tot}')
| false |
e4dc5953de648e35eab4452529585487da561f42 | Metheus97/Meus_Exerccicios_de_Python | /ex100.py | 765 | 4.21875 | 4 | '''um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar(). A primeira função vai
sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar a soma entre todos os valores pares
sorteados pela função anterior.'''
from random import randint
from time import sleep
núm = []
def sort(list):
print('os numeros sorteados são: ', end='')
for c in range(0, 5):
num = randint(0, 10)
list.append(num)
print(f'{num} ', end='', flush=True)
sleep(0.5)
print(' PRONTO!')
def soma(lis):
res = 0
for numer in lis:
if numer % 2 == 0:
res += numer
print(f'A soma dos numeros pares é igual a: {res} ')
sort(núm)
soma(núm)
| false |
0d1cc043ab6314044e4c341b4362eb1a2c33e5eb | minotaur423/Python3 | /Python-Scripts/prob16.py | 1,846 | 4.1875 | 4 | # Average of an array
# Average (or mean) value of some numbers could be calculated as their sum divided by
# their amount. For example:
# avg(2, 3, 7) = (2 + 3 + 7) / 3 = 4
# avg(20, 10) = (20 + 10) / 2 = 15
# You will be given several arrays, for each of which you are to find an average value.
# Input data will give the number of test-cases in the first line. Then test-cases
# themselves will follow, one case per line. Each test-case describes an array of
# positive integers with value of 0 marking end. (this zero should not be included
# into calculations!!!).
# Answer should contain average values for each array, rounded to nearest integer
# (see task on rounding), separated by spaces.
# Example:
# input data:
# 3
# 2 3 7 0
# 20 10 0
# 1 0
# Answer: 4 15 1
def avg_nums(nums):
count = 0
sum_num = 0
count = 0
for arg in nums:
if arg != 0:
sum_num += arg
count += 1
result = round(sum_num / count)
return result
numbers = ['6445 5437 6396 14805 7404 4662 16232 15918 0', '5252 14707 3760 5533 13765 1377 6422 0', '1676 394 1579 1438 1903 1580 1454 1766 1035 1356 0', '57 480 774 982 942 41 0', '3674 13302 3470 1996 677 9003 15761 2054 15425 7543 9337 12446 10690 5580 7561 0', '44 114 158 214 149 252 228 13 189 217 248 0', '7034 2 4981 576 1000 5320 5078 689 6347 4598 4460 2823 2628 0', '3205 3188 3265 3906 910 1695 3222 0', '691 870 135 534 836 930 325 692 930 948 764 31 589 0', '90 238 169 178 64 219 98 8 163 0', '14010 9659 12601 10759 16131 7267 0', '247 83 6 73 256 239 54 191 246 201 0', '34 9 188 212 72 151 0', '226 390 300 78 994 64 750 0']
values: list = []
final_result = 0
for i in numbers:
num = i.split()
del values[::]
for j in num:
values.append(int(j))
final_result = avg_nums(values)
print(final_result, end=' ') | true |
36492a4c4d4a3abe2d89e752243a8fe22334f0da | minotaur423/Python3 | /Python-Scripts/slice_demo.py | 2,000 | 4.125 | 4 | # Slicing allows access one or more elements of a sequence
# Immutable sequences include tuples, strings, and bytes
a_tuple = ('a', 1, 2, (3, 4))
a_string = 'immutable'
a_bytes = b'testing'
# Mutable sequences include lists and bytearrays
a_list = [5, 6, 7, 8, (4, 5)]
a_byte_array = bytearray(b'Jose Santos')
# Accessing is allowed in all sequences
print('a_tuple[0] ->', a_tuple[0])
print('a_string[1] ->', a_string[1])
print('a_bytes[2] ->', a_bytes[2])
print('a_list[3] ->', a_list[3])
print('a_byte_array[4] ->', a_byte_array[4])
# Negative indexes are from the end
print('a_tuple[-1] ->', a_tuple[-1])
print('a_string[-2] ->', a_string[-2])
print('a_bytes[-3] ->', a_bytes[-3])
print('a_list[-4] ->', a_list[-4])
print('a_byte_array[-5] ->', a_byte_array[-5])
# Subslices can be accessed with two indexes
print('a_list[0:2] ->', a_list[0:2])
print('a_list[:2] ->', a_list[:2])
print('a_list[2:5] ->', a_list[2:5])
print('a_list[2:] ->', a_list[2:])
print('a_list[:] ->', a_list[:])
list_ref = a_list
print('a_list is list_ref ->', a_list is list_ref)
list_copy = a_list[:]
print('a_list is list_copy ->', a_list is list_copy)
# Steps can be taken with a third parameter:
print('a_list[::2] ->', a_list[::2])
print('a_list[1:4:2] ->', a_list[1:4:2])
print('a_string[::-1] ->', a_string[::-1])
# Use additional slices to access elements with sequences
print('a_list ->', a_list)
print('a_list[4] ->', a_list[4])
print('a_list[4][0] ->', a_list[4][0])
print('a_list[4][1] ->', a_list[4][1])
# Mutable sequences can be updated with slices
print('a_list ->', a_list)
a_list[0] = 'five'
print('a_list ->', a_list)
a_list[1:4] = [10, 11, 12]
print('a_list ->', a_list)
# A slice object can be used in the [ ] for slicing
a_slice = slice(4)
print('a_slice ->', a_slice)
print('a_list[a_slice] ->', a_list[a_slice])
a_slice = slice(1,5)
print('a_slice ->', a_slice)
print('a_list[a_slice] ->', a_list[a_slice])
a_slice = slice(1,5,2)
print('a_slice ->', a_slice)
print('a_list[a_slice] ->', a_list[a_slice])
| true |
26b9ccac3092f8752c1ec13d1d5908b8f1f4e171 | minotaur423/Python3 | /Python-Scripts/int_demo.py | 1,314 | 4.1875 | 4 | x = 5
y = 10
y = 0xA # Hex
y = 0o12 # Octal
y = 0b1010 # binary
print('x =', x, ',', 'y =', y)
# Typical comparisons can be made
print('x == y =', x == y)
print('x != y =', x != y)
print('x >= y =', x >= y)
print('x > y =', x > y)
print('x <= y =', x <= y)
print('x < y =', x < y)
# The usual operators can be used:
print('x + y =', x + y)
print('x - y =', x - y)
print('x * y =', x * y)
print('x / y =', x / y)
# In Python 2, x / y users floor division like:
print('x // y =', x // y)
print('x % y =', x % y)
print('x ** y =', x ** y)
# There are several useful builtin functions:
print('divmod(x, y) =', divmod(x, y))
print('pow(x, y) =', pow(x, y))
print('abs(-x) =', abs(-x))
print('int(5.2) =', int(5.2))
print('int("0xff",16) =', int("0xff", 16))
print('float(x) =', float(x))
# Inline notation can also be used:
print('x = x + y =', end = ' ')
x += y
print(x)
print('x = x - y =', end = ' ')
x -= y
print(x)
print('x = x * y =', end = ' ')
x *= y
print(x)
print('x = x / y =', end = ' ')
x /= y
print(x)
# Multiple assignments can be done:
x, y = 4, 2
print('x =', x, ',' 'y =', y)
# Bitwise operators can be used:
print('Or: x | y =', x | y)
print('Xor: x ^ y =', x ^ y)
print('And: x & y =', x & y)
print('Left Shift: x << y =', x << y)
print('Right Shift: x >> y =', x >> y)
print('Inversion: ~x =', ~x)
| false |
32063197afd4dad61596cc8ed4213f5a7aeb6cf9 | minotaur423/Python3 | /Python-Scripts/prob9.py | 1,132 | 4.15625 | 4 | # Triangles
# You are given several triplets of values representing lengths of the
# sides of triangles. You should tell from which triplets it is possible
# to build triangle and for which it is not.
# Input data: A number of triplets.
# Other lines will contain triplets themselves (each in separate line).
# Answer: You should output 1 or 0 for each triplet (1 if triangle
# could be built and 0 otherwise).
def check_triangle(a,b,c):
if a + b > c and a + c > b and b + c > a:
return 1
return 0
int_list = []
side_lengths = '616 1553 805 766 1492 1456 181 203 305 1915 926 1380 493 852 1974 510 197 223 1800 840 890 592 1108 700 384 1513 636 1386 1523 882 1713 751 480 615 1759 866 155 194 473 500 645 1497 709 1439 815 407 261 178 550 1072 867 2038 740 1427 383 737 262 606 1057 383 780 416 1440 838 430 2014 575 714 1441 599 837 1496 1272 897 916 940 517 1984 312 238 727 537 455 420 301 548 605 1020 2404 700'
side_list = side_lengths.split(' ')
for side in side_list:
int_list += [int(side)]
for i in range(0,len(side_list),3):
print(check_triangle(int_list[i],int_list[i+1],int_list[i+2]), end=' ') | true |
4114af5b93e00ca55ae4cc1679364f9103994cb3 | StRobertCHSCS/oop-practice-assignment-mrfabroa | /Coin.py | 1,297 | 4.25 | 4 | """
-------------------------------------------------------------------------------
Name: Coin.py
Purpose:
Simulates a coin flip
Author: Fabroa.E
Created: 22/03/2019
------------------------------------------------------------------------------
"""
import random
class Coin(object):
"""
Models a coin as an object
"""
def __init__(self):
"""
Initializes the face of the coin to either heads or tails
:return: None
"""
self.face = random.choice(["heads", "tails"])
def get_face(self):
"""
Retrieves the current face of the coin facing up
:return: string The value of the face attribute
"""
return self.face
def flip(self):
"""
Sets the face attribute to heads or tails
:return: None
"""
self.face = random.choice(["heads", "tails"])
# Simulates 1000 coin flips and saves the data to accumulator variables
if __name__ == '__main__':
# initialize the counters
heads = 0
tails = 0
for i in range(1000):
myCoin = Coin()
myCoin.flip()
if myCoin.get_face() == "heads":
heads += 1
else:
tails += 1
print("Total Heads: " + str(heads) + "\nTotal Tails: " + str(tails)) | true |
2c44ca6dba2e1cf8b95b2a00211cd7852c6f9bd5 | Haein1/Exercises-for-Programmers-57-Challenges-to-Develop-Your-Coding-Skills | /password_validation.py | 760 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 4 08:39:57 2021
@author: Administrator
"""
'''Create a simple program that validates userlogin credentials.
The program must prompt the user for a username and
password. The program should compare the password given
by the user to a known password. If the password matches,
the program should display “Welcome!” If it doesn’t match,
the program should display “I don’t know you.”
Example Output
What is the password? 12345
I don't know you.
Or
What is the password? abc$123
Welcome!
'''
true_password = 'abc$123'
user_input_p = input("What is the password? ")
if user_input_p == true_password:
print('Welcome!')
else:
print("I don't know you.") | true |
641a3055777d211025e34f1f2716036bb1327f0f | YuduDu/cracking-the-coding-interview | /3.4.py | 1,296 | 4.1875 | 4 | #!/usr/bin/python
class tower(object):
def __init__(self):
self.stack = []
def push(self, data):
if len(self.stack)==0:
self.stack.append(data)
elif data < self.peek():
self.stack.append(data)
return True
else:
return False
def peek(self):
return self.stack[-1]
def pop(self):
return self.stack.pop()
def get_tower(self):
return self.stack
def get_size(self):
return len(self.stack)
class towersOfHanol(object):
def __init__(self,N):
tower1 = tower()
tower2 = tower()
tower3 = tower()
for i in range(N,0,-1):
tower1.push(i)
self.Hanol = [tower1,tower2,tower3]
def move(self,source,target):
if (source not in range(3)) or (target not in range(3)):
return False
elif self.Hanol[source].get_size() == 0:
return False
else:
data = self.Hanol[source].pop()
if self.Hanol[target].push(data):
return True
else:
return False
def getHanol(self):
for i in self.Hanol:
print i.get_tower()
def moveHanol(hanol,N,source,target,buffer):
if N == 1:
hanol.move(source,target)
else:
moveHanol(hanol,N-1,source,buffer,target)
hanol.move(source,target)
moveHanol(hanol,N-1,buffer,target,source)
hanol = towersOfHanol(20)
hanol.getHanol()
moveHanol(hanol,20,0,2,1)
print "result:"
hanol.getHanol()
| false |
cb217436a493861dbb306d2bf900ab20ffc087d6 | sichkar-valentyn/Roman_number_to_decimal_number | /Roman_to_decimal_number_system.py | 2,031 | 4.1875 | 4 | # File: Roman_to_decimal_number_system.py
# Description: Conversion Roman number to decimal number system
# Environment: PyCharm and Anaconda environment
#
# MIT License
# Copyright (c) 2018 Valentyn N Sichkar
# github.com/sichkar-valentyn
#
# Reference to:
# [1] Valentyn N Sichkar. Conversion Roman number to decimal number system // GitHub platform [Electronic resource]. URL: https://github.com/sichkar-valentyn/Roman_number_to_decimal_number (date of access: XX.XX.XXXX)
# Implementing the task
# Converting Roman number system to decimal number system
# By using regular expressions
# Importing library 're'
import re
# Creating a pattern for finding following numbers in the string: 4, 9, 40, 90, 400, 900
# By using '|' we say which groups of symbols to look for
pattern_1 = r'IV|IX|XL|XC|CD|CM'
# Inputting string in Roman number system
string = input() # 'MCMLXXXIV'
# Finding all inclusions according to the pattern_1 and put them into the list
all_inclusions = re.findall(pattern_1, string) # ['CM', 'IV']
# Deleting found inclusions in the string
for i in range(len(all_inclusions)):
string = re.sub(all_inclusions[i], r'', string) # At the end we'll receive 'MLXXX'
# Creating a pattern for finding following numbers in the string: 1, 5, 10, 50, 100, 500, 1000
# By using '|' we say which groups of symbols to look for
pattern_2 = r'I|V|X|L|C|D|M'
# Finding all inclusions according to the pattern_2 and adding them to the list
all_inclusions += re.findall(pattern_2, string) # We'll receive ['CM', 'IV', 'M', 'L', 'X', 'X', 'X']
# Creating a dictionary for conversion
d = {'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
'IV': 4,
'IX': 9,
'XL': 40,
'XC': 90,
'CD': 400,
'CM': 900}
# Converting to decimal number system
# Going through all elements of the list and finding the values in the dictionary
# After the appropriate values were found it is needed just to add them all together
n = 0
for x in all_inclusions:
n += d[x]
print(n)
| true |
a5efa06fdb63f791a834971e03c7c0e81c0dffd3 | mbsabath/Hangman | /ps2_hangman.py | 2,710 | 4.15625 | 4 | # 6.00 Problem Set 3
#
# Hangman
#
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = string.split(line)
print " ", len(wordlist), "words loaded."
return wordlist
def choose_word(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
# end of helper code
# -----------------------------------
# actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program
def hangman():
wordlist = load_words()
word = choose_word(wordlist)
length = len(word)
import string
alphabet = string.lowercase
alphabetlist = list(alphabet)
print 'The word I am thinking of is', length, 'letters long'
chance = 8
blankwordlist = []
for blanks in range(0, length):
blankwordlist = blankwordlist + ['_ ']
blankword = ''.join(blankwordlist)
print blankword
while chance > 0:
print 'You have', chance, 'guesses left'
print 'Available letters:', alphabet
guess = raw_input('Please guess a letter: ').lower()
if len(guess) ==1:
letterremoval = alphabet.find(guess)
del alphabetlist[letterremoval]
alphabet = ''.join(alphabetlist)
lettercount = word.count(guess)
check = word.find(guess)
if check == -1:
chance -=1
print blankword
else:
for occurance in range(0, lettercount):
if occurance > 0:
checknew = word.find(guess, (check + 1))
check = checknew
blankwordlist[check] = guess
else:
blankwordlist[check] = guess
blankword = ''.join(blankwordlist)
print blankword
else:
print 'Please guess only a single letter'
if blankword == word:
break
if blankword == word:
print 'You win!'
if chance == 0:
print 'you lose'
print 'The word was:', word
hangman()
| true |
f12af87fc46d13f4ac6c122c9389eac3a67b231d | Chris-M-Wagner/Number_Guess_Game | /Number_Guess_Game.py | 1,811 | 4.3125 | 4 | """
Creator: Chris Wagner
Created Date: 12/03/2015
Last Updated: 12/03/2015
Summary:
Number_Guess_Game generates a random integer and asks the user to guess it.
"""
import random
def Number_Guess_Game():
LL = 1 #Lower limit
UL = 10 #Upper limit
guessUL = 3 #Guess upper limit
guess = 0
tries = 0
ans = random.randrange(LL,UL+1) #This will be the mystery number
print "\n\n\nWelcome to the Guessing Game! I will think of a mystery number between %s and %s, and you will have %s guesses to find the number!" %(LL, UL, guessUL)
while tries<guessUL and guess!=ans:
guessguesses = "guesses"
if (guessUL - tries) == 1:
guessguesses = "guess"
print "\nYou have %s %s left" %((guessUL - tries), guessguesses)
try:
guess = int(raw_input("Enter a number: "))
print ""
except ValueError:
print "You have entered an incorrect value. Please input a positive integer."
if guess>UL or guess<LL:
print "The mystery number is between %s and %s, try guessing between those numbers!" %(LL, UL)
if guess!=ans and guess<=UL and guess>=LL:
tries+=1
if (guessUL-tries)>0:
hilow = ""
if guess > ans:
hilow = "lower"
elif guess < ans:
hilow = "higher"
print "The mystery number is %s than %s" %(hilow, guess)
if guess==ans:
print "You win! The mystery number is %s" %(ans)
elif guess!=ans and tries==guessUL:
print "Sorry, the mystery number was %s" %(ans)
replay = raw_input("Play again? \n(Y/N): ")
if replay == "Y":
Number_Guess_Game()
else:
print "Exiting Game."
return None
Number_Guess_Game()
'''
Testing Methodology:
- Guess a string
- Guess an integer outside of the LL/UL range
- Guess number that is false to review guess iteration
- Guess the mystery number, make sure that the win message comes up
- Test the replay Y/N
''' | true |
26988e1f80fc621b2e2b1fedbff3e87239efc533 | IsroilovDavron/HW-Texnikum | /HW#7/DzDp_Razdelitel.py | 768 | 4.3125 | 4 | # Написать функцию, которая принимает от пользователя двухзначное число
# и возвращает кол-во десятков и единиц.
# Например, пользователь вводит 45, функция возвращает 4 десятка и 5 единиц
# ( в разных переменных ), не строкой.
while True:
x=int(input('Введите двухзначное число: '))
y = x // 10
z = x - y * 10
if x<10:
print('В этом числе нет десятки, но есть единицы равные', z, 'единицам')
else:
print('В числе', x, 'есть',y,'десятка и', z,'единиц') | false |
5e973f14f177befd126613339f4285ff834895eb | devisri15ec007/python-ds | /largest among 3 numbers.py | 329 | 4.21875 | 4 | m=int(input("Enter the number:"))
d=int(input("Enter the number:"))
s=int(input("Enter the number:"))
if(m >= s) and (m >= s):
print ("The largest number among given number is: m")
elif(d >= m) and (d >= s ):
print ("The largest number among given number is: d")
else:
print ("The largest number among given number is: s")
| false |
0653295501e98002fd2b487e66498abb754de345 | chaitanya-j/python-learning | /Intermidiate concepts/logic based prgms/map-func-demo.py | 861 | 4.65625 | 5 | # Lets say, we have some list as below
# It could be a list of just anything - strings, numbers or other class objects
children = ['Chaitanya','Tanmay','Raghav','Mrunmayee','Anvay','Adwait']
# Now we want to do something with each member of the list - say we want to greet each child with a 'Hello'
# Lets define a say_hello function that takes in a child's name and then returns a greeting for that child
def say_hello(name):
return f'Hi {name}!'
# Traditional way of doing this - using a for loop
for child in children:
greeting = say_hello(child)
print(greeting)
# New way of doing it - using the python map function
greets = map(say_hello,children)
print(list(greets))
# Lets define another function - say which converts the name to UPPERCASE
def to_upper(name):
return name.upper()
uppers = list(map(to_upper,children))
print(uppers) | true |
487511d08eb00cbce3c639e5aed6f3c43e402718 | CesarPalomeque/Investigacion.py | /calculadora.py | 2,457 | 4.15625 | 4 | class Calculadora:
def __init__(self, numero1, numero2):
self.num1=numero1
self.num2=numero2
def suma(self):
result_Suma= self.num1 + self.num2
print("La suma del los numeros: {} y {} es: {}".format(self.num1,self.num2,result_Suma))
def resta(self):
result_Resta= self.num1 - self.num2
print("La resta del los numeros {} y {} es: {}".format(self.num1, self.num2, result_Resta))
def multiplicacion(self):
result_Multiplicacion= self.num1 * self.num2
print("La multiplicación de los numeros {} y {} es de: {}".format(self.num1,self.num2,result_Multiplicacion))
def division(self):
total_Division=self.num1 / self.num2
print("La division de los numeros es de: {}".format(total_Division))
class CalEstandar(Calculadora):
def __init__(self, numero1, numero2):
super().__init__(numero1,numero2)
def multiplicacion(self):
Resultado= self.num2 * self.num1
return Resultado
def exponente(self,base,exponente1):
resultado=1
for i in range(exponente1):
resultado*=base
return resultado
def valorAbsoluto(sefl,numero):
if numero >= 0:
return numero
else:
numero = -numero
return numero
class calCientifica(Calculadora):
def __init__(self, numero1, numero2):
super().__init__(numero1, numero2)
def circunferencia(self):
PI = 3.1416
Perimetro = 2 * PI * self.num1
return Perimetro
def areaCirculo(self):
PI = 3.1416
area = PI * (self.num1**2)
return area
def areaCuadrado(self):
return self.num2 ** 2
#cal=Calculadora(12,2)
#cal.suma()
# print('\n')
# cal.resta()
# print('\n')
# cal.multiplicacion()
# print('\n')
# cal.division()
# print('\n')
# cal1=CalEstandar(8,1)
# print('la multiplicacio es: ',cal1.multiplicacion())
# print('\n')
# print('el resultado del metodo_exponente es: ',cal1.exponente(2,5))
# print('\n')
# print('el valor absoluto es: ',cal1.valorAbsoluto(-4))
# print('\n')
# cal2 = calCientifica(2,2)
# print('La circuferencia es: ',cal2.circunferencia())
# print('\n')
# print('El area del circulo es: ',cal2.areaCirculo())
# print('\n')
# print('area del cuadrado: ',cal2.areaCuadrado())
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.