blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
706f7af5c7a3c732df5923577dd0321e87630f87 | maherme/python-deep-dive | /Numeric_Types/FloatCoercingToIntegers.py | 751 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 25 12:01:19 2021
@author: maherme
"""
#%%
# Let's see trunc function:
from math import trunc
print(trunc(10.3), trunc(10.5), trunc(10.9))
# Trunc is used by default for the int constructor:
print(int(10.4), int(10.5), int(10.9))
#%%
# Let's see floor function:
from math import floor
print(floor(10.3), floor(10.5), floor(10.9))
# Notice the difference between floor and trunc is in negative numbers:
print(trunc(10.4), trunc(10.5), trunc(10.9))
print(floor(-10.4), floor(-10.5), floor(-10.9))
#%%
# Let's see ceil function:
from math import ceil
print(ceil(10.4), ceil(10.5), ceil(10.9))
print(ceil(-10.4), ceil(-10.5), ceil(-10.9)) # Notice -10 is greater than -11
#%% | true |
9a89d50b6d86604378507e92964ab812c49e8fcf | maherme/python-deep-dive | /Numeric_Types/FloatInternalRepresentation.py | 782 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 25 11:18:51 2021
@author: maherme
"""
#%%
# Let's see the float constructor:
print(float(10))
print(float(10.4))
print(float('12.5'))
print(float('22/7')) # This will fail, you need to create a fraction first
#%%
from fractions import Fraction
a = Fraction('22/7')
print(float(a))
#%%
# Let's see the problem of the infinite number and the internal representation:
print(0.1)
print(format(0.1, '.15f'))
print(format(0.1, '.25f')) # So 0.1 is not 0.1 in the machine!
print(0.125)
print(format(0.125, '.25f')) # In this case 0.125 is stored as it is in the machine
a = 0.1 + 0.1 + 0.1
b = 0.3
print(a == b)
# Notice a is different to b in the machine!
print(format(a, '.25f'))
print(format(b, '.25f'))
#%% | true |
6311e80dfa4995203437be22f5bc1c0343fac53b | Kseniya159/home_work | /задание 1.py | 467 | 4.1875 | 4 | #Поработайте с переменными, создайте несколько,
# выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные,
# выведите на экран..
number = int ( input ("Введите число"))
print( number)
age = 28
print ( age)
name = input( "Введите имя")
from1 = input( (" Я из "))
| false |
793453499738c02f538f5a5e7585426e3c89de37 | AlvaroSanchezBC/-lvaro-S-nchez-Beato | /practica24.py | 548 | 4.15625 | 4 | # -º- coding: utf-8 -º-
'''
Pr�ctica 28
FechaL�mite:2/11/2020
FechaCorreci�n:5/11/2020
author@: alvaro.sanchez
'''
#Escribir un programa que solicite del usuario una lista de edades y muestre en pantalla la lista de edades de menor a mayor y de menor a mayor.
#Primero voy a crear una lista de edades.
#Ahora con el método sort voy a ordenar la lista de forma ascendente.
#Printamos la lista.
thislist= [91,10,7,45,22,4,38,66,18,15]
thislist.sort(key=None, reverse=False)
print (thislist)
nombre= input()
print(nombre) | false |
9e222085ac82d074594e896dd8f9ecec93b071f2 | MatsK/python-for-grade-8 | /example01_print_and_variables.py | 255 | 4.34375 | 4 | # My first program
print "Hello, world!"
name = "Your name"
#name = "Someone elses name"
print "Hello %s" % name
# x is a integer variable name
x = 5
print "x=%s" % x
# We can change the value of x with a mathematical operation
x = x + 2
print "x=%s" % x
| true |
c135c6a9d36b791f5c3222d012acfc0911e81b63 | ColdMacaroni/sort-by-ord | /no_sort_by_ord.py | 1,976 | 4.28125 | 4 | ##
# no_sort_by_ord.py
# Sorts input string by the value given by ord(char)
# 2021-03-31
def str_to_ord(string):
"""
Returns a list with the ord of each character.
"""
return [ord(x) for x in string]
def corresp_ord(string):
"""
Returns a dictionary of the equivalent ascii order for each
character. Including spaces. {82: 'S'}
"""
dict_ord = {}
for char in string:
dict_ord[ord(char)] = char
return dict_ord
def manual_sort(int_iterable):
"""
Takes an iterable(only accepts integers) and sorts it manually.
Not using the built-in sort function.
"""
sorted_list = []
# Will run until the original list is empty
while len(int_iterable):
# Get a starting value
smallest = int_iterable[0]
# Replace smallest with the actual smallest item
for item in int_iterable:
if smallest > item:
smallest = item
sorted_list.append(int_iterable.pop(int_iterable.index(smallest)))
return sorted_list
def sort_by_ord(string):
"""
Sorts a string by the value given by ord(char
"""
# Set up
list_ord = str_to_ord(string)
dict_ord = corresp_ord(string)
sorted_ord = manual_sort(list_ord)
new_string = []
# Convert each number to their corresponding character
for item in sorted_ord:
new_string.append(dict_ord[item])
return ''.join(new_string)
def sort_each_word_by_ord(string):
"""
Returns each word of a sentence sorted by result of ord(char)
"""
# Setup
sentence = string.split()
new_sentence = []
# Go through each word
for word in sentence:
new_sentence.append(sort_by_ord(word))
return ' '.join(new_sentence)
if __name__ == "__main__":
print(sort_by_ord(input('Sort all: ')))
print(sort_each_word_by_ord(input('Sort by word: ')))
| true |
b110b7e2469298143333a46a0bb226873852dd57 | magedu-pythons/python-19 | /6-kwei/week13/homework.py | 2,036 | 4.21875 | 4 | # 1、实现数据结构stack(栈),并实现它的append,pop方法【动手查询相关资料理解stack特点以及与queue区别】
# 用数组实现
class Stack:
def __init__(self, length: int):
self.length = length
self.stack = [None] * length
self.index = -1
def append(self, item):
if self.index + 1 >= self.length:
print('overflow!')
return
self.index += 1
self.stack[self.index] = item
def pop(self):
if self.index == -1:
print("stack is empty, can't pop")
return
self.stack[self.index], temp = None, self.stack[self.index]
self.index -= 1
return temp
def __repr__(self):
return 'STACK:{}, length:{}'.format(self.stack, self.index + 1)
# test
s = Stack(3)
s.pop()
print(s)
s.append(1)
print(s)
s.append(1)
s.append(1)
print(s)
s.append(1)
s.pop()
print(s)
# 2、打印出N对合理的括号组合。
# 例如: 当N=3,输出:()()(),()(()),(())(),((()))
# 这题有意思
def prinar(char, pos, left, right):
if left < 0 or right < 0:
return
if left == 0 and right == 0:
print(''.join(char))
return
if left > 0:
char[pos] = '('
prinar(char, pos + 1, left - 1, right)
if right > left:
char[pos] = ')'
prinar(char, pos + 1, left, right - 1)
def res(n):
char = [0] * (2 * n)
prinar(char, 0, n, n)
# test
res(3)
# 3、根据字典,从一个抹去空格的字符串里面提取出全部单词组合,并且拼接成正常的句子:
# 例如: 输入一个字符串:"thisisanexample", 程序输出: "this is an example"
dictionary = {
'b', 'example', 'c', 'an', 'am', 'this', 'is', 'are'
}
string = "thisisanexample"
res = []
offset = 0
for i,_ in enumerate(string):
if string[offset:i+1] in dictionary:
res.append(string[offset:i+1])
offset = i+1
print(string[offset:i+1])
print(' '.join(res))
"""
(0 + 0)
最后2题参考答案
""" | false |
5eae836273a74302642730313923d3bf8732c0b9 | magedu-pythons/python-19 | /0-Answers/week11/2-parenthesis.py | 591 | 4.125 | 4 | # 2、打印出N对合理的括号组合。
# 例如: 当N=3,输出:()()(),()(()),(())(),((())),(()())
def print_parenthesis(output, opend, close, pairs):
"""
左右括号数量匹配
:param output:
:param opend:
:param close:
:param pairs:
:return:
"""
if opend == pairs and close == pairs:
print(output)
else:
if opend < pairs:
print_parenthesis(output + '(', opend + 1, close, pairs)
if close < opend:
print_parenthesis(output + ')', opend, close + 1, pairs)
print_parenthesis('', 0, 0, 3)
| false |
dd7a85fa55680805cf4fe5f83993dce00ba8420b | magedu-pythons/python-19 | /P19035-艾合麦提/week2/1.py | 442 | 4.15625 | 4 | def fibonacci_generator():
"""
:return:the generator produces number
"""
i = 0
j = 1
yield 1
while True:
yield j+i
n = i
i = j
j = n + i
def main(n):
for k in fibonacci_generator():
if k < n:
print(f"the number is {k}")
#test
if __name__ == '__main__':
main(200)
"""
(0 + 0)
参考答案的实现,作业格式 按照week-demo来
"""
| false |
b8322e0df48c549087167b2a887be03f659e587a | jeffwright13/codewars | /is_prime.py | 946 | 4.1875 | 4 | def main():
print is_prime.__doc__
def is_prime(n):
"""
Checks for primality via trial division on (1, sqrt(n)]
"""
from math import sqrt
if type(n) != int or n <= 1:
return False
#print 'checking for n =', n
for i in range(2, int(round(sqrt(n)))+1):
if n % i == 0:
return False
return True
def test_is_prime():
assert is_prime(-1) == False
assert is_prime(0) == False
assert is_prime(0.5) == False
assert is_prime('l') == False
assert is_prime(1) == False
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(6) == False
assert is_prime(99) == False
assert is_prime(100) == False
assert is_prime(101) == True
assert is_prime(918) == False
assert is_prime(919) == True
assert is_prime(15485863) == True
if __name__ == "__main__":
main()
| false |
00194cd3682ef8a32845aa3b52ac7b9f03c582ba | jeffwright13/codewars | /mixed_fraction.py | 2,189 | 4.5625 | 5 | def main():
print mixed_fraction.__doc__
def mixed_fraction(s):
"""
https://www.codewars.com/kata/simple-fraction-to-mixed-number-converter
Task:
Given a string representing a simple fraction x/y, your function must return a string representing the corresponding mixed fraction in the following format:
a b/c
where a is integer part and b/c is irreducible proper fraction. There must be exactly one space between a and b/c.
If the x/y equals the integer part, return integer part only. If integer part is zero, return the irreducible proper fraction only. In both of these cases, the resulting string must not contain any spaces.
Division by zero should raise an error (preferably, the standard zero division error of your language).
Examples
Input: 42/9, expected result: 4 2/3.
Input: 6/3, expedted result: 2.
Input: 4/6, expected result: 2/3.
Input: 0/18891, expected result: 0.
Input: -10/7, expected result: -1 3/7.
Inputs 0/0 or 3/0 must raise a zero division error.
Note:
Make sure not to modify the input of your function in-place, it is a bad practice.
"""
negative = (s[0] == '-')
numerator, denominator = s.split('/')
print "negative, num, den:", negative, numerator, denominator
if denominator == '0':
raise ZeroDivisionError
base = int(numerator) / int(denominator)
remainder = int(numerator) % int(denominator)
print "base, remainder:", base, remainder
if not negative:
return str(base) + ' ' + str(remainder) + '/' + str(denominator)
else:
return '-' + str(base) + ' ' + str(remainder) + '/' + str(denominator)
def test_mixed_fraction():
# assert mixed_fraction('44/0') == ZeroDivisionError
assert mixed_fraction('42/9') == '4 2/3'
assert mixed_fraction('-42/9') == '-4 2/3'
assert mixed_fraction('6/3') == 2
assert mixed_fraction('4/6') == '2/3'
assert mixed_fraction('5/100') == '1/20'
assert mixed_fraction('0/18991') == 0
assert mixed_fraction('-10/7') == '-1 3/7'
assert mixed_fraction('-22/7') == '-3 1/7'
if __name__ == "__main__":
main()
| true |
341d3ca705d51e831f9bd0aed54b27dc4931da42 | jeffwright13/codewars | /permutation_average.py | 1,623 | 4.25 | 4 | def main():
print permutation_average.__doc__
def permutation_average(n):
"""
A number is simply made up of digits.
The number 1256 is made up of the digits 1, 2, 5, and 6.
For 1256 there are 24 distinct permuations of the digits:
1256, 1265, 1625, 1652, 1562, 1526, 2156, 2165, 2615, 2651, 2561, 2516,
5126, 5162, 5216, 5261, 5621, 5612, 6125, 6152, 6251, 6215, 6521, 6512.
Your goal is to write a program that takes a number, n, and returns the average value of all distinct permutations of the digits in n. Your answer should be rounded to the nearest integer. For the example above the return value would be 3889.
n will never be negative
A few examples:
permutation_average(2)
return 2
permutation_average(25)
>>> 25 + 52 = 77
>>> 77 / 2 = 38.5
return 39
permutation_average(20)
>>> 20 + 02 = 22
>>> 22 / 2 = 11
return 11
permutation_average(737)
>>> 737 + 377 + 773 = 1887
>>> 1887 / 3 = 629
return 629
Note: Your program should be able to handle numbers up to 6 digits long
"""
if len(str(n)) > 6:
return 'Input too long'
from itertools import permutations
perms = [float(''.join(e)) for e in permutations(str(n))]
return int(round(sum(perms) / len(perms)))
def test_permutation_average():
assert permutation_average(1234567) == 'Input too long'
assert permutation_average(25) == 39
assert permutation_average(737) == 629
assert permutation_average(2) == 2
assert permutation_average(20) == 11
if __name__ == "__main__":
main()
| true |
d59f595e547df9dff7ecef38724b1729dabc2b23 | jeffwright13/codewars | /sumDig_nthTerm.py | 2,345 | 4.4375 | 4 | def main():
print sumDig_nthTerm.__doc__
def sumDig_nthTerm(initVal, patternL, nthTerm):
"""
We have the first value of a certain sequence, we will name it initVal. We define pattern list, patternL, an array that has the differences between contiguous terms of the sequence. E.g: patternL = [k1, k2, k3, k4]
The terms of the sequence will be such values that:
term1 = initVal
term2 - term1 = k1
term3 - term2 = k2
term4 - term3 = k3
term5 - term4 = k4
term6 - term5 = k1
term7 - term6 = k2
term8 - term7 = k3
term9 - term8 = k4
.... - ..... = ...
.... - ..... = ...
So the values of the differences between contiguous terms are cyclical and are repeated as the differences values of the pattern list stablishes.
Let's see an example with numbers:
initVal = 10
patternL = [2, 1, 3]
term1 = 10
term2 = 12
term3 = 13
term4 = 16
term5 = 18
term6 = 19
term7 = 20 # and so on...
We can easily obtain the next terms of the sequence following the values in the pattern list. We see that the sixth term of the sequence, 19, has the sum of its digits 10.
Make a function sumDig_nthTerm(), that receives three arguments in this order
sumDig_nthTerm(initVal, patternL, nthTerm(ordinal number of the term in the sequence))
This function will output the sum of the digits of the n-th term of the sequence.
Let's see some cases for this function:
sumDig_nthTerm(10, [2, 1, 3], 6) -----> 10 # because the sixth term is 19 and the sum of Dig = 1 + 9 = 10. The sequence up to the sixth-Term is: 10, 12, 13, 16, 18, 19
sumDig_nthTerm(10, [1, 2, 3], 15) ----> 10 # 37 is the 15-th term, and 3 + 7 = 10
Enjoy it and happy coding!!
"""
index = 0
s = initVal
for i in range(1, nthTerm):
if index % len(patternL) == 0:
index = 0
s += patternL[index]
index += 1
print "sum:", s, type(s)
return sum([int(digit) for digit in str(s)])
def test_sumDig_nthTerm():
assert sumDig_nthTerm(1, [1, 3, 5], 4) == 1
assert sumDig_nthTerm(10, [2, 1, 3], 6) == 10
assert sumDig_nthTerm(10, [2, 1, 3], 15) == 10
assert sumDig_nthTerm(100, [2, 2, 5, 8], 6) == 11
assert sumDig_nthTerm(100, [2, 2, 5, 8], 157) == 16
if __name__ == "__main__":
main()
| true |
a626678ccefac238fdc86942ad04c0f5c6ebfd91 | jeffwright13/codewars | /find_next_square.py | 1,524 | 4.34375 | 4 | def main():
print find_next_square(None)
def find_next_square(sq):
"""
You might know some pretty large perfect squares. But what about the NEXT one?
Complete the findNextSquare method that finds the next integer perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.
If the parameter is itself not a perfect square, than -1 should be returned. You may assume the parameter is positive.
Examples:
findNextSquare(121) --> returns 144
findNextSquare(625) --> returns 676
findNextSquare(114) --> returns -1 since 114 is not a perfect
"""
if sq < 0:
return -1
if sq == 0:
return 1
if sq == 1:
return 4
def is_square(apositiveint):
x = apositiveint // 2
seen = set([x])
while x * x != apositiveint:
x = (x + (apositiveint // x)) // 2
if x in seen: return False
seen.add(x)
return True
if not is_square(sq):
return -1
import math
return (math.sqrt(sq) + 1) ** 2
def test_find_next_square():
assert find_next_square(-1) == -1
assert find_next_square(0) == 1
assert find_next_square(47) == -1
assert find_next_square(1) == 4
assert find_next_square(121) == 144
assert find_next_square(625) == 676
assert find_next_square(319225) == 320356
assert find_next_square(15241383936) == 15241630849
if __name__ == "__main__":
main()
| true |
a7d20941cdeb717e3e519c286c059ccdd5cb6e4e | jeffwright13/codewars | /remainder.py | 1,106 | 4.4375 | 4 | def main():
print remainder(None)
def remainder(dividend, divisor):
"""
Task
----
Write a method 'remainder' which takes two integer arguments, dividend and divisor, and returns the remainder when dividend is divided by divisor. Do NOT use the modulus operator (%) to calculate the remainder!
Assumption
----------
Dividend will always be greater than or equal to divisor.
Notes
-----
Make sure that the implemented remainder function works exactly the same as the Modulus Operator (%). For example n % 0 = NaN, your method should return null.
"""
if dividend < divisor:
return 'Input error'
div = float(dividend)/float(divisor)
if div == dividend/divisor:
return 0
else:
return dividend - int(div) * divisor
def test_remainder():
assert remainder(2, 3) == 'Input error'
assert remainder(2, 2) == 0
assert remainder(3, 2) == 1
assert remainder(19, 2) == 1
assert remainder(10, 2) == 0
assert remainder(34, 7) == 6
assert remainder(27, 5) == 2
if __name__ == "__main__":
main()
| true |
55abc4c575a0c0f15f21f69ca6b7e4ecc8ff64bc | JuanAngel1/PrimerRepo | /prog3.py | 960 | 4.15625 | 4 | #Menu
#Operaciones
#S. Suma
#R. Resta
#M. Multiplicacion
#D. Division
#A. Salir
#Que opcion elige? :
#Ingrese numero uno
#Ingrese numero dos
print("Programa para resolver operaciones aritmeticas")
while True:
print('''Operaciones: 1.- S. Suma 2.- R. Resta 3.- M. Multiplicacion 4.- D. Division 5.- A. Salir
¿Que opcion elige? : ''')
resp = input("Ingrese una opcion: ").upper()
if resp == "S" or resp == "R" or resp == "M" or resp == "D":
num1 = int(input("Ingresa el primer numero: "))
num2 = int(input("Ingresa el segundo numero: "))
if resp == "S":
print(f"La suma es: {num1 + num2}")
elif resp == "R":
print(f"La resta es: {num1 - num2}")
elif resp == "M":
print(f"La multiplicacion es: {num1 * num2}")
elif resp == "D":
print(f"La division es: {num1 / num2}")
elif resp == "A":
print("SALIR")
break
| false |
a4af751a08ba85b2009e042f0c31d6eaac5cb57c | wfSeg/py3dahardway | /py16.py | 1,103 | 4.4375 | 4 | # what can you do with files?
# close: close the file
# read: reads the file
# readline: reads just one line of text
# truncate: Empties the file.. so it's not truncate, it's like Erase
# write('stuff'): Writes into the file
# seek(0): Moves the r/w location to beginning of file.. this is like for HDDs
from sys import argv
script, filename = argv
print(f"We're going to erase {filename}.")
print("Press CTRL-C to cancel.")
print("Hit RETURN to continue with the script.")
input("?") #waiting for any button I guess
print("Opening the file...")
target = open(filename, 'w')
print("Truncating the file. Goodbye!") #yeah it's coming back, I definitely did this years ago
target.truncate()
print("Now I'm going to ask you for three lines.")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, close the file.")
target.close()
#coolio, this works. Use exercise 15 script to check it. | true |
00fcc169bc667b5d259b76bb31e7a6ed1f0d04e0 | wfSeg/py3dahardway | /py31.py | 2,074 | 4.125 | 4 | # I go out for boba everyday, sometimes even twice. :|
print("""You enter a dark room with two doors.
Do you go through the door on the LEFT or the door on the RIGHT?""")
choice = input("> ")
#if choice == "L" or "Left": #hmm capitalization matters. Need a better way to sanitize the input
# doesn't work.
if choice == "L" or choice == "Left" or choice == "l" or choice == "LEFT":
print("There is a giant Hillary sitting there.")
print("What do you do?")
print("1. Check your emails.")
print("2. Check her emails.")
hillary = input("> ")
if hillary == "1":
print("She ignores you.")
elif hillary == "2":
print("She eats your face off.")
else:
print(f"Well, doing {hillary} isn't one of the options...")
print("sicko")
#elif choice == "R" or "Right": # I was going to put in cases for "RIGHT" and "r" too, but it's unecessary
# doesn't work.
elif choice == "R" or choice == "Right" or choice == "r" or choice == "RIGHT":
print("There is a giant Trump yelling there.")
print("1. Blueberries.")
print("2. Yellow jacket clothespins.")
print("3. Understanding revolvers yelling melodies.")
# hahaha, I didn't even read this part when I first coded it. I just replaced door 1 and 2 with L and R
# then I replaced bear with Hillary, and assumed the other one was another bear.
# but Trump and Cthullu are kinda interchangeable here, both induce insanity.
insanity = input("> ")
#if insanity == "1" or "2": # don't need to specify insanity == "2" again, redundant right?
# nope. doesn't work.
if insanity == "1" or insanity == "2":
print("Your body survives powered by a mind of jello.")
print("Goo job. Yes, 'Goo' job.")
else:
print("The insanity rots your eyes into a pool of muck.")
print("Good job!")
else:
print("You stumble around and fall on a banana, and pass out. Check your spelling! Capitalizaton matters.") #the text from the exercise was too morbid.
# ok so it didn't work first time around, turns out, you NEED to specify variable for both the booleans
# listening to Meek Mill - Dreams and Nightmares. Intense. | true |
e3829c37aeb3c9cf05a090ed36625b6da355a9f5 | komerela/dataStructAlgosPython | /mergelinkedlists.py | 1,528 | 4.3125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
"""
1 -> 2 -> 4 1 -> 3 -> 4 -> 5 ->6
l1 l2
new_List 0 -> 1 ->
(start new merged list)
1. set variables
"""
class ListNode:
# constructor
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# A linked list class with a single head node
class LinkedList:
def __init__(self):
self.head = None
# insertion method for linked list
# Merge function for Linked list
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# set variables
new_list = ListNode() # used to manipulate the new merged list
ans = new_list # head of new merged list
# create loop
while l1 and l2:
if l1.val <= l2.val:
new_list.next = l1 # store the node in the new_list
l1 = l1.next
elif l2.val < l1.val:
new_list.next = l2
l2 = l2.next
new_list = new_list.next
if l1:
new_list.next = l1
elif l2:
new_list.next = l2
return ans.next
if __name__ == "__main__":
l = ListNode(10)
l2 = ListNode(8, l)
o = ListNode(-1)
n = ListNode(-3, o)
s = LinkedList()
res = s.mergeTwoLists(l2, n)
while res:
print(res.val)
res = res.next
| true |
d6c336ad50bb88fc70f86641b8cbbe40b89a0d63 | airakesh/interviewbits | /arrays/anti_diagonals.py | 722 | 4.375 | 4 | '''
Give a N*N square matrix, return an array of its anti-diagonals. Look at the example for more details.
Example:
Input:
1 2 3
4 5 6
7 8 9
Return the following :
[
[1],
[2, 4],
[3, 5, 7],
[6, 8],
[9]
]
Input :
1 2
3 4
Return the following :
[
[1],
[2, 3],
[4]
]
'''
class Solution:
# @param A : list of list of integers
# @return a list of list of integers
def diagonal(self, A):
res = [list() for i in range(2 * len(A) - 1)]
for i in range(len(A)):
for j in range(len(A)):
res[i + j].append(A[i][j])
return res
# Ans/test code
s = Solution()
A = [
[1, 2, 3],
[3, 5, 6],
[6, 8, 9]
]
s.diagonal(A)
| true |
51c636d72134537e16a284191ddb828a637dd6d4 | HardyBubbles/TikTakToe | /player_input.py | 857 | 4.28125 | 4 | '''
Функция спрашивает у 1го игрока, каким маркером он хочет отмечать свои квадратики на доске
The function asks the 1st player with which marker he wants to mark his squares on the board
'''
def player_input():
p1_m = "" # стартовое знач-е для запуска цикла while
while not (p1_m == "X" or p1_m == "O"):
p1_m = input("Player 1 please choose X or O: ").upper()
if p1_m == "X": # присвоение маркеров игрокам, исходя из выбора первого игрока
p2_m = "O"
elif p1_m == "O":
p2_m = "X"
else:
print("Wrong input\n")
return (p1_m, p2_m) # возвращаем маркеры, присвоенные игрокам
| false |
c715c821737e4f25dc84d73ed29f9840d1cb7674 | olgaBovyka/BasicLanguagePython | /Урок 3/Task3_3.py | 1,172 | 4.5625 | 5 | """
3. Реализовать функцию my_func(),
которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.
"""
def my_func(argument1, argument2, argument3):
argument_list = [argument1, argument2, argument3]
argument_list.sort()
return argument_list[1] + argument_list[2]
input_var = input("Введите аргумент 1 ")
if input_var.isdigit():
arg1_int = int(input_var)
input_var = input("Введите аргумент 2 ")
if input_var.isdigit():
arg2_int = int(input_var)
input_var = input("Введите аргумент 3 ")
if input_var.isdigit():
arg3_int = int(input_var)
result_var = my_func(arg1_int, arg2_int, arg3_int)
print(result_var)
else:
print("Ошибка ввода. Нужно вводить целое число.")
else:
print("Ошибка ввода. Нужно вводить целое число.")
else:
print("Ошибка ввода. Нужно вводить целое число.")
| false |
27c3871b192c088d6c2a2bcf1af6471a05f9ed78 | ScienceStacks/common_python | /common_python/util/dataframe.py | 1,508 | 4.15625 | 4 | """Utilities for DataFrames"""
import pandas as pd
import numpy as np
def isLessEqual(df1, df2):
"""
Tests if each value in df1 is less than or equal the
corresponding value in df2.
"""
indices = list(set(df1.index).intersection(df2.index))
dff1 = df1.loc[indices, :]
dff2 = df2.loc[indices, :]
df = dff1 - dff2
df_tot = df.applymap(lambda v: v <= 0)
result = df_tot.sum().sum() == df.size
return result
def mean(dfs):
"""
Calculates the mean of values in a list of dataframes
for the same index, column.
:param list-pd.DataFrame dfs:
:return pd.DataFrame:
"""
df_mean = sum(dfs)
return df_mean/len(dfs)
def std(dfs):
"""
Calculates the standard deviation of values in a
list of dataframes for the same index, column.
:param list-pd.DataFrame dfs:
:return pd.DataFrame:
"""
df_mean = mean(dfs)
df_sq = sum([(df - df_mean)*(df - df_mean) for df in dfs])
return df_sq / len(dfs)
def subset(df, items, axis=1):
"""
Constructs a dataframe is a subset to the items, by row or column.
Parameters
----------
df: pd.DataFrame
items: list
columns if axis = 1
indices if axis = 0
axis: int
0 - rows
1 - columns
Returns
-------
pd.DataFrame
"""
if axis == 1:
columns = list(set(items).intersection(df.columns))
return df[columns]
elif axis == 0:
indices = list(set(items).intersection(df.index))
return df.loc[indices, :]
else:
raise ValueError("Invalid axis: %d" % axis)
| true |
d31914ca5bf9ec1e3b03e53b5b957216fcde80fd | erikayoon/Automate-The-Boring-Stuff-With-Python | /Chapter 4/commaCode.py | 868 | 4.1875 | 4 | # TASK:
# Take a list value as an argument
# Return a string with all the items separated by a comma and space
# With 'and' inserted before the last item
# Ex: apples, bananas, tofu, and cats
# PERSONAL TWIST:
# If the first value of the list is a string
# Capitalize it
### MY CODE BELOW: ###
# Define function
def str_list(list_value):
string = ''
for i in range(len(list_value)):
if i == 0 and type(list_value[i]) == str:
string = list_value[i].capitalize() + ', '
elif i == len(list_value) -1:
string = string + 'and ' + str(list_value[i])
else: string = string + str(list_value[i]) + ', '
return string
# Test function with different values
list1 = ['apples', 'bananas', 'tofu', 'cats']
list2 = [1, 2, 3, 4, 5]
list3 = [0, 'pi', 3.14, 'circles']
my_string = str_list(list1)
print(my_string)
| true |
69e69ff253c15e514a62aed56a5792ac6ce175c9 | Elvandro/Password-locker | /user.py | 748 | 4.15625 | 4 | class User:
"""
Class that generates new instances of users
"""
user_list = []
def __init__(self, user_name, password):
"""
__init__ method helps us define our object
Args:
user_name: New user name.
password: New user password.
"""
self.user_name = user_name
self.password = password
def save_user(self):
"""
save_user method saves the users object into our user_list
"""
User.user_list.append(self)
@classmethod
def user_exists(cls, user_name):
"""
method to check is a user exists
"""
for user in cls.user_list:
if user_name == user_name:
return user
| true |
e33f993b6a2a63db6c94b998a3d7aed4d48804b4 | yanyanxumian/Stats507_F21 | /nb/string_df.py | 1,659 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Create a small pandas DataFrame for examples.
@author: James Henderson
@date: August 31, 2021
"""
# 79: ------------------------------------------------------------------------
# libraries: -----------------------------------------------------------------
import pandas as pd
# input strings: -------------------------------------------------------------
str1 = 'To err is human.'
str2 = 'Life is like a box of chocolates.'
# functions: -----------------------------------------------------------------
def n_vowels(s):
"""
Count the vowels in s.
Parameters
----------
s : str
The string in which to count vowels.
Returns
-------
An integer for the count of vowels (a, e, i, o, or u) in s.
"""
n = 0
for v in ['a', 'e', 'i', 'o', 'u']:
n += s.count(v)
return(n)
def pct_vowels(s, digits=1):
"""
Return the % of characters in s that are vowels.
Parameters
----------
s : str
The string in which to compute the % of vowels.
digits : int, optional
Roun the % to this many digits. The default is 1.
Returns
-------
The % of vowels among all characters (not just alpha characters) in s.
"""
n = n_vowels(s)
pct = round(100 * n / len(s), digits)
return(pct)
# data frame: ----------------------------------------------------------------
dat = pd.DataFrame(
{
"string": [str1, str2],
"length": [len(str1), len(str2)],
"% vowels": [pct_vowels(str1), pct_vowels(str2)]
}
)
# 79: ------------------------------------------------------------------------
| true |
4b8fca052411efb9514b2b31e434126cf326d376 | fangyeqing/hello-python | /_7_oop/_5_class_attribute.py | 699 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = '实例属性和类属性'
__author__ = 'fangyeqing'
__time__ = '2016/11/3'
"""
# 学生
class Student(object):
# 用于记录已经注册学生数
student_number = 0
def __init__(self, name):
self.name = name
# 注册一个学生:注册必填项名字,选填项利用关键字参数传递。注册完成,学生数+1
def register(name, **kw):
a = Student(name)
for k, v in kw.items():
setattr(a, k, v)
Student.student_number += 1
return a
bob = register('Bob', score=90)
ah = register('Ah', age=8)
print(getattr(bob, 'score'))
print(getattr(ah, 'age'))
print(Student.student_number)
| false |
40a2e739e6752b978deb83b7c04dd653aa541cbe | Maddallena/python | /day_2.py | 1,366 | 4.21875 | 4 | # DZIEŃ DRUGI____________________________________________________________________________________________________________________________________
# Data types
# print("Hello" [3]) SUBSCRIPTING A CHARACTER
# num_char = len(input("what is your name?: "))
# new_num_char = str(num_char)
# print("your name has " + new_num_char + " characters")
# two_digit_number = input("Type a two digit number: ")
# new_number = int(two_digit_number[0]) + int(two_digit_number[1])
# print(new_number)
# Matematical operations
# 1 + 3
# 3 - 2
# 2 * 5
# 6 / 3
# 2 ** 3 potega exponent operator
# height = input("enter your height in m: ")
# weight = input("enter your weight in kg: ")
# h = float(height)
# w = float(weight)
# bmi = w/h**2
# result = int(bmi)
# print(result)
# age = input("What is your current age? ")
# left = 90 - int(age)
# days = 365 * left
# weeks = 52 * left
# months = 12 * left
# print(f"You have {days} days, {weeks} weeks, and {months} months left.")
# print("Welcomme to the tip calculator.")
# bill = float(input("What was the total bill? $"))
# tip = int(input("What percentage tip would you like to give? 10, 12, or 15? "))
# ppl = int(input("How many people to split the bill? "))
# to_pay = round(bill/ppl * (1 + tip / 100), 2)
# #pay = round(to_pay, 2)
# print(f"Each person should pay: ${to_pay}.") | false |
fd70bcf214fe1afaa31eb8f1c70639d3cfdf18c7 | annecode21/Projects | /Random password generator.py | 446 | 4.1875 | 4 | import random
print ("Welcome to my random password generator!")
chars = "abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ123456789!@#$%&"
number = int(input("Number of password(s) to generate: "))
length = int(input("Enter length of password required: "))
print ("\nHere is/are your password(s): ")
for pwd in range (number):
password = " "
for char in range (length):
password += random.choice(chars)
print (password) | false |
8585491202fd2e83a07204c2bdccd91762a0f9a4 | jaumecosta/python | /tortuga.py | 787 | 4.15625 | 4 | import turtle
#funcion que se encarga de la activacion de la ventaan de dibujo y de llamar a la funcion haz rectangulo
def oceano():
window = turtle.Screen()
tortuguita = turtle.Turtle()
haz_rectangulo(tortuguita)
turtle.mainloop()
#funcion que nos hace las preguntas de largo y alto
def haz_rectangulo(tortuguita):
largo = float(input('Largo: '))
alto = float(input('Alto: '))
for i in range(2):
haz_linea(tortuguita, largo)
haz_alto(tortuguita, alto)
def haz_linea(tortuguita, largo):
tortuguita.forward(largo)
tortuguita.left(90)
def haz_alto(tortuguita, alto):
tortuguita.forward(alto)
tortuguita.left(90)
#Para definir donde comenzara nuestro codigo vamos a usar esta linia
if __name__ == '__main__':
oceano()
| false |
51d4e110fa914f72d9acbf1a0f2e45c8c726650f | mystor/ugrad-thesis | /figs/canasta.py | 750 | 4.125 | 4 | def value(num, suit):
if num <= 2:
return 20
elif 3 == num and suit in ['H', 'D']:
return 100 # red 3s are worth 100
elif 3 <= num < 8:
return 5
elif 8 <= num:
return 10
def main():
# Read in the type of card.
numbers := ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'J', 'Q', 'K']
num := input("Card Number (" + '/'.join(numbers) + "): ")
if num not in numbers:
print("Invalid card number!")
return
suits := ['H', 'D', 'C', 'S']
suit := input("Card Suit (" + '/'.join(suits) + "): ")
if suit not in suits:
print("Invalid card suit!")
return
# Get the value of the card
print("Value:", value(numbers.index(num) + 1, suit))
main()
| true |
2dce48e58b3a4682acb9787e9bf06f6b82a9f2ad | rosajong/population | /Population.py | 1,606 | 4.34375 | 4 | """
Define class Human which has the following : gender hair eyes AGE
For every baby a Human gets Population must be += 1
Only women can have babies
Human grows from baby > child > adolescent > adult
The attributes gender hair eyes are randomly given to Human
Give population a starting number and make that amount of humans
"""
import random
total_population = 4
genderoptions = ['M', 'F']
hairoptions = ["blond", "brown", "black", "ginger"]
eyesoptions = ["blue", "green", "brown"]
ageoptions = ['baby', 'child', 'adolescent', 'adult']
class Human:
kind = 'homo_sapiens'
def __init__(self, gender, hair, eyes, age):
self.gender = random.choice(genderoptions)
self.hair = random.choice(hairoptions)
self.eyes = random.choice(eyesoptions)
self.age = age
#def __set_characteristics(self, gender, hair, eyes):
# """
# the __ before function name makes it private - that means it can only be used within this class
# """
# self.gender =
# self.hair =
# self.eyes =
def make_baby(self, gender, hair, eyes, age):
if Human.gender == "F" and age == "adult":
total_population +=1
print("There are now %i people") %total_population
return Human(self, gender, hair, eyes, "baby")
else:
pass
Adam = Human('M', 'ginger', 'green')
Eva = Human('F', 'blond', 'brown')
Joseph = Human('M', 'brown', 'blue')
Mary = Human('F', 'black', 'brown')
print("Do you want to make babies?")
answer = str(raw_input("yes/no "))
if 'y' in answer:
pass # make babies
| true |
a4d8597b95e2597a4ba85080248dc67819d515a6 | mhiloca/PythonBootcamp | /challenges/valid_parentheses.py | 539 | 4.125 | 4 | def valid_parentheses(string):
# check = []
# for p in string:
# if p == '(':
# check.append('(')
# if p == ')':
# check.remove('(') if check else check.append('(')
# return not check
count = item = 0
while item < len(string):
if string[item] == '(':
count += 1
if string[item] == ')':
count -= 1
item += 1
if count < 0:
return False
return not count
para = '()()()()()()'
print(valid_parentheses(para))
| true |
56bdf527e4d9e212d136ed7ee92df0b3d5f21928 | Kiran-24/python-assignment | /python_partA_171041001/centroid.py | 640 | 4.1875 | 4 | ''' Implement a python code to find the centroid of a triangle'''
def centroid(p1,p2,p3):
''' To calculate the centroid of triangle'''
centroid = [(p1[0]+p2[0]+p3[0])/3 , (p1[1]+p2[1]+p3[1])/3]
return centroid
def main():
print('enter x y co-ordinates of first vertex :')
p1 = [float(d) for d in input().split()]
print('enter x y co-ordinates of second vertex :')
p2 = [float(d) for d in input().split()]
print('enter x y co-ordinates of third vertex :')
p3 = [float(d) for d in input().split()]
x_y = centroid(p1,p2,p3)
print('the centroid of triangle is (%.2f , %.2f)' %(x_y[0],x_y[1]))
if __name__ == '__main__':
main() | false |
b8115f4ebdea6c62c79d545587ff159b893f046d | melipefelgaco/project_madLibs | /project_madLibs.py | 1,397 | 4.3125 | 4 | # Reads text files and lets user add their own text anywhere the words ADJECTIVE, NOUN, VERB or NOUN appears in the text.
# Read the file panda.txt stored on this same folder.
# Path = yourpath
# The results should be printed to the screen and saved to a new text file. (newpanda.txt)
from pathlib import Path
import os, re
import pyinputplus as pyip
# Modify the file panda.txt
panda = open('C:\\yourpath\panda.txt')
pandaContent = panda.read()
# Transfers the content of panda to newPanda:
newPanda = open('newPanda.txt', 'w')
newPandaWrite = newPanda.write(pandaContent)
# The panda regex:
pandaRegex = re.compile(r'(ADJECTIVE|NOUN|VERB|ANOUN)')
# Getting user input to match in the regex:
while True:
mo = pandaRegex.search(pandaContent)
if mo == None:
break
elif mo.group() == 'ADJECTIVE':
print('Enter an adjective: ')
elif mo.group() == 'NOUN':
print('Enter a noun: ')
elif mo.group() == 'VERB':
print('Enter a verb: ')
elif mo.group() == 'ANOUN':
print('Enter another noun: ')
userInput = input()
pandaContent = pandaContent.replace(mo.group(), userInput, 1)
# Creating a new panda file and transfering the new content to it:
newPanda = open('newPanda.txt', 'w')
newPanda.write(pandaContent)
# Print the new file content from newpanda.txt:
print(pandaContent)
# Closing everything:
newPanda.close()
panda.close()
| true |
2b8d6283a183aa16f1d5d2a9ce113c0ba55b3d59 | xgabrielrf/igti-python | /modulo1/class.py | 1,189 | 4.28125 | 4 | print(''''Erro' ao absorver informação de uma variável que foi obtida por classe.
Nesse caso abaixo nós fazemos o carro_2 = carro_1, porém, ao modificar o carro_2,
o carro_1 é alterado indevidamente.
Isso ocorre por conta de quando colocamos carro_2 = carro_1, fazemos o apontamento
para o mesmo objeto na memória. Assim, ao alterarmos um deles, o outro acaba
enxergando o mesmo objeto, com o valor alterado.
Segue o exemplo:''')
class Carro:
def __init__(self, numero_portas, preco):
self.numero_portas = numero_portas
self.preco = preco
print('Objeto carro instanciado!')
def get_numero_portas(self):
return self.numero_portas
def set_numero_portas(self, novo_numero_portas):
self.numero_portas = novo_numero_portas
carro_1 = Carro(4,80000)
print(f'Numero de portas do carro_1 é {carro_1.get_numero_portas()}.')
carro_2 = carro_1
print(f'Numero de portas do carro_2 é {carro_2.get_numero_portas()}.')
carro_2.set_numero_portas(2)
print('erro:')
print(f'Numero de portas do carro_1 é {carro_1.get_numero_portas()}.')
print('alterado:')
print(f'Numero de portas do carro_2 é {carro_2.get_numero_portas()}.')
| false |
bd43128053f6a3e8e88e860cd103f09f8288d8e7 | marioabz/python-cheat-sheet | /data_types/collections/dictionaries.py | 1,423 | 4.375 | 4 |
# Dictionary is a collection that stores values in a key-value fashion
# Dictionaries are changeable and don't allow duplicates
person = {
"age": 67,
"name": "Jinpig",
"last_name": "Xi",
"ocupation": "President",
"country_of_origin": "China",
}
# Accesing the 'age' key of dict 'person'
print(person["age"])
# Updating the value of key 'country_of_origin'
person["country_of_origin"] = "Taiwan"
# Create a copy of person but they are no the same object
copycat = person.copy()
print(person == copycat, person is copycat) # -> True, False
keys = "age", "name", "last_name", "ocupation", "country_of_origin"
#Create a dict with iterable as keys
person_to_set = dict.fromkeys(keys, None)
print(person_to_set)
# Returns the keys and values in a list of tuples
print(person.items())
# -> dict_items([('age', 67), ('name', 'Jinpig'),
# ('last_name', 'Xi'), ('ocupation', 'President'),
# ('country_of_origin', 'China')])
# Returns a list of keys of a dict
print(person.keys()) # -> dict_keys(['age', 'name', 'last_name',
# 'ocupation', 'country_of_origin'])
# Returns a list of values of a dict
print(person.values()) # -> dict_values([67, 'Jinpig', 'Xi', 'President', 'China'])
# Returns the value asociated with the key
print(person.pop("ocupation")) # -> 'President'
# Returns a default value if key doesn't exist in dict
print(person.pop("countryyy", "-")) # -> '-'
| true |
83144e045f2852d5219c6d7c4b73b67d8fe53b29 | lee000000/leetcodePractice | /434.py | 1,015 | 4.125 | 4 | '''
434. Number of Segments in a String
Count the number of segments in a string, where a segment
is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-#printable characters.
Example:
Input: "Hello, my name is John"
Output: 5
'''
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return 0
if (len(s) == 1 and s != " "):
return 1
if (len(s) == 1 and s == " "):
return 0
count = 0
for i in range(len(s)):
#print("\'", s[i],"\'")
if s[i] == " " and s[i - 1] != " ":
#print("here")
count += 1
if s[0] != " " and s[-1] != " ":
count += 1
return count
if __name__ == "__main__":
a = "Of all the gin joints in all the towns in all the world, "
sol = Solution()
print(sol.countSegments(a))
| true |
b2cea68ccf191849f470f7263f73758199e7bc47 | Elephantxx/gs | /05_高级数据类型/x_15_字符串统计操作.py | 254 | 4.28125 | 4 | hello_str = "hello hello"
# 1. 统计字符串长度
print(len(hello_str))
# 2. 统计某一个小字符出现的次数
print(hello_str.count("llo"))
print(hello_str.count("abc"))
# 3. 某一个子字符串出现的位置
print(hello_str.index("llo")) | false |
d97c062c45e9e754a6f04f7ba683d2a1d0e73c92 | Elephantxx/gs | /05_高级数据类型/x_01_列表基本使用.py | 1,036 | 4.28125 | 4 | name_list = ["zhangsan", "lisi", "wangwu"]
# 1. 取值和取索引
# list index out of range - 列表索引超出范围
print(name_list[2])
# 已知数据内容,查找该数据在列表中的位置
print(name_list.index("lisi"))
# 2. 修改
name_list[1] = "李四"
# list assignment index out of range - 列表指定的索引超出范围
# name_list[3] = "小明"
# 3. 增加
# append 方法可以向列表末尾追加数据
name_list.append("小强")
# insert 方法可以在列表的指定索引位置增加数据
name_list.insert(1,"小红")
# extend 方法可以把其他列表中完整的内容 追加到当前列表的末尾
temp_list = ["孙悟空", "猪二哥", "沙师弟"]
name_list.extend(temp_list)
# 4. 删除
# remove 方法可以从列表中删除指定数据
name_list.remove("小强")
# pop 方法默认情况下可以删除当前列表中最后一个数据
name_list.pop()
# pop 方法可以删除指定索引位置的数据
name_list.pop(1)
# clear 方法可以清空列表
name_list.clear()
print(name_list)
| false |
3d5ace7db875341ae5e0f442f4752402b1fd7725 | NineMan/Project_Euler | /Euler_2.py | 732 | 4.125 | 4 | """
Задача 2 Четные числа Фибоначчи
Каждый следующий элемент ряда Фибоначчи получается при сложении двух предыдущих.
Начиная с 1 и 2, первые 10 элементов будут:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Найдите сумму всех четных элементов ряда Фибоначчи, которые не превышают четыре миллиона.
"""
lst = [1]
fib1 = 1
fib2 = 1
while fib2 <= 4000000:
fib1, fib2 = fib2, fib1 + fib2
lst.append(fib2)
# print(lst)
a = filter(lambda x: x % 2 == 0, lst)
# print(list(a))
b = sum(a)
print('summa =', b)
| false |
3c46650b3604ff754235564bf09e508320169a51 | strayberry/data_struct | /Chain.py | 2,359 | 4.21875 | 4 | # -*- coding: UTF-8
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class LinkedList(object):#链表
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
if self.head is None:
print('The linkedlist is empty')
else:
print('The linkedlist is not empty')
def append(self, data): #在末插入节点
node = Node(data)
if self.head is None:
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
def iter(self): #遍历
if self.head is None:
print('The linkedlist is empty')
else:
cur = self.head
while cur is not None:
print(cur.data)
cur = cur.next
def insert(self, index, value): #在第n的位置插入节点
cur = self.head
cur_index = 0
# 空链表时
if cur is None:
print('List is empty')
return
while cur_index < index-1:
cur = cur.next
# 插入位置超出链表节点的长度时
if cur is None:
print('list length less than index')
return
cur_index += 1
node = Node(value)
node.next = cur.next
cur.next = node
# 插入位置是链表的最后一个节点时,需要移动tail
if node.next is None:
self.tail = node
def remove(self, index): #移除第n个节点
cur = self.head
cur_index = 0
if cur is None: # 空链表时
print('List is empty')
return
while cur_index < index-1:
cur = cur.next
if cur is None:
print('list length less than index')
cur_index += 1
if index == 0: # 当删除第一个节点时
self.head = cur.next
cur = cur.next
return
if self.head is self.tail: # 当只有一个节点的链表时
self.head = None
self.tail = None
return
cur.next = cur.next.next
if cur.next is None: # 当删除的节点是链表最后一个节点时
self.tail = cur
def search(self,item): #查找节点位置
cur = self.head
cur_index = 0
if cur is None: # 空链表时
print('List is empty')
return
while cur.data != item:
cur = cur.next
cur_index += 1
print("iterm index :" + str(cur_index))
if __name__ == '__main__':
linkedList = LinkedList()
linkedList.is_empty()
linkedList.append(1)
linkedList.append(2)
linkedList.is_empty()
linkedList.iter()
linkedList.insert(2,3)
linkedList.iter()
linkedList.remove(2)
linkedList.iter()
linkedList.search(2)
| false |
25f8cf1be395e35ac62c3334e9b6264512a9abc6 | pramo31/LeetCode | /Completed/group_anagrams.py | 662 | 4.125 | 4 | from typing import List
"""
Given an array of strings, group anagrams together.
"""
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagram_dict = {}
for word in strs:
sorted_word = "".join(sorted(list(word)))
if (sorted_word in anagram_dict.keys()):
anagram_dict[sorted_word].append(word)
else:
anagram_dict[sorted_word] = [word]
return anagram_dict.values()
if (__name__ == "__main__"):
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
obj = Solution()
print("Grouped Anagrams : {}".format(obj.groupAnagrams(strs)))
| true |
9817dccf295e2f42f3548a9e1282e5ba71557f66 | IndranilRay/PythonRecipes | /GeeksForGeeks/Int2Bin.py | 247 | 4.1875 | 4 | """
Program displays binary equivalent of an integer > 0
"""
def display_bin(n):
if n == 0:
return
display_bin(n//2)
print(n % 2)
if __name__ == "__main__":
number = input("Enter a number")
display_bin(int(number))
| true |
bb3455c61e127d8462c979b13ac4c61104cafcca | IndranilRay/PythonRecipes | /GeeksForGeeks/stringIsPalindromeRecursive.py | 526 | 4.34375 | 4 | """
WAP to check if input string is palindrome recursive version
"""
def isPalindrome(input_string, start=0, end=0):
if start >= end:
return True
return (input_string[start] == input_string[end]) and isPalindrome(input_string, start+1, end-1)
if __name__ == '__main__':
string = input("Enter the string:")
is_string_palindrome = isPalindrome(string, start=0, end=len(string)-1)
if is_string_palindrome:
print('String is Palindrome')
else:
print('String is not palindrome') | true |
f812c8ea740c64c629b3c325152c12d249b31412 | Supermac30/CTF-Stuff | /Mystery Twister/Autokey_Cipher/Autokey Encoder.py | 327 | 4.1875 | 4 | """
This script encodes words with the AutoKey Cipher
"""
plaintext = input("input plaintext ")
key = input("input key ")
ciphertext = ""
for i in range(len(plaintext)):
ciphertext += chr((ord(plaintext[i]) + ord(key[i]))%26 + ord("A"))
key += plaintext[i]
print("Your encoded String is:",ciphertext)
| true |
5a98e54f9762d2fab78ea8134bb80bb385dce851 | vaibhavs33/RockPaperScissors | /loops.py | 1,110 | 4.1875 | 4 | keepPlaying = True
player1 = input("What is player 1's choice? ")
while(player1 != "rock" and player1 !="paper" and player1 != "scissors"):
player1 = input("Please choose a valid choice (rock,paper, or scissors): ")
# print(player1,"is the right choice")
player2 = input("What is player 2's choice? ")
while(player2 != "rock" and player2 !="paper" and player2 != "scissors"):
player2 = input("Please choose a valid choice (rock,paper, or scissors): ")
# print(player2,"is the right choice")
if player1 == player2:
print("Tie")
elif player1 == 'rock' and player2 == 'scissors':
print("Player 1 wins.")
elif player1 == 'paper' and player2 == 'rock':
print("Player 1 wins.")
elif player1 == 'scissors' and player2 == 'paper':
print("Player 1 wins.")
elif player2 == 'rock' and player1 == 'scissors':
print("Player 2 wins.")
elif player2 == 'paper' and player1 == 'rock':
print("Player 2 wins.")
elif player2 == 'scissors' and player1 == 'paper':
print("Player 2 wins.")
choice = input("Would you like to play again?(y/n): ")
if(choice == "n"):
keepPlaying = False | true |
ccfc5b68b5272b0ed16c06f5c44793e8dea81923 | king-tomi/python-learning | /family.py | 2,621 | 4.5625 | 5 | class Family:
"""This is a program representation of a nuclear family.
parent_name: name of the mother or father of the family.
children_name: a list of the children in the family.
child_gender: a list of the corresponding genders of each child."""
def __init__(self,parent_name,children_name=[],child_gender=[]):
if children_name == [] and child_gender == []:
print("You don't have a child or your children have not been given a gender.")
self.children_name = children_name
self.child_gender = child_gender
else:
self.parent_name = parent_name
self.children_name = children_name
self.child_gender = child_gender
def is_male(self,name):
if not self.children_name: #checks if list is empty
print("You don't have a child.") #returns this when list is empty
else:
if name in self.children_name: #checks if name is in list
return self.child_gender[self.children_name.index(name)] == "male" #returns this when name in list
def is_female(self,name): #does the same as the is_male method
if not self.children_name:
print("You don't have a child")
else:
if name in self.children_name:
return self.child_gender[self.children_name.index(name)] == "male"
def set_parents(self,child_name,parent_name):
self.parent_name = parent_name
self.children_name.append(child_name)
def get_parents(self,name):
"""This returns the parent name if the list of children is not empty and the parameter 'name' is in the
list of children."""
if not self.children_name:
print("This child is not part of the family")
else:
if name in self.children_name:
return self.parent_name
def get_children(self,name):
"""This first check if the parameter 'name' is in the list of children return the corresponding
output. if the list is empty is tells the user. if the child is not in the list, it also informs
the user and if it is there, ut returns the name."""
if not self.children_name:
print("This child is not part of the family")
else:
if name in self.children_name:
return name
else:
print("This child is not your child")
def __repr__(self):
return "Family:{}\t{}".format(self.parent_name,self.children_name) | true |
e6e4a103b43fd3dae304d8b953ac6f3532e1851e | dexter2206/redis-classes | /examples/sets.py | 980 | 4.15625 | 4 | """Basic examples of using sets."""
from redis import Redis
import settings
if __name__ == '__main__':
client = Redis(
host=settings.HOST,
port=settings.PORT,
password=settings.PASSWORD,
decode_responses=True
)
name = 'kj:set'
# Create some set by adding elements to it.
client.sadd(name, 'Foo')
client.sadd(name, 'Bar')
client.sadd(name, 'Baz')
# Print elements of a set
print(client.smembers(name))
# Notice: adding the same element twice does not change a set
client.sadd(name, 'Baz')
print(client.smembers(name))
# Print total number of elements in a set
print(client.scard(name))
# Check if given element is in a set
print(client.sismember(name, 'Foo'))
print(client.sismember(name, 'FooBarBaz'))
# Get random member of a set
print(client.srandmember(name))
# Remove 'Foo' from the set
print(client.srem(name, 'Foo'))
print(client.smembers(name)) | true |
87ec263519dcd85bc7b003549ff02d2421dd1aa4 | LauraBrogan/pands-problem-set-2019 | /solution-1.py | 1,024 | 4.4375 | 4 | # Solution to Problem 1
# Ask the user to Input any positive integer and output the sum of all numbers between one and that number.
# n is asking the user to input a postive integer.
n = int(input("Input a Positive Integer: "))
# If the user inputs a negative number or a zero the programe displays "this is not a positive integer" and ends the program.
total = 0
if n <= 0:
print("Unfortunately this is not a Positive Integer.")
quit()
# If the user inputs a postive number greater than zero the program runs.
# It sums all of the numbers between one and that number.
while n > 0:
total = total + n
n = n - 1
# The answer is then displayed to the user with an explanation.
print(total,"This is the sum of all the numbers between one and the interger inputted above.")
# Used Class Tutorial for Factorial Problem as base for creation of the above.
# Reference: https://stackoverflow.com/questions/50012895/pythonwrite-a-program-that-keeps-reading-positive-numbers-from-the-user
# Laura Brogan 19/02/2019 | true |
c32e91fef72a2d2a87d0f63dca588965d3f83cd9 | ericel/python101 | /hypotenuse.py | 1,882 | 4.25 | 4 |
import math
# Calculates length of the hypotenuse of a
# right trianle given lengths of other 2 legs
def hypotenuse(a, b):
# should return a float
print(0.0)
return 0.0
# return 0.0
hypotenuse(3, 4)
# Calculates length of the hypotenuse of a
# right trianle given lengths of other 2 legs
def hypotenuse(a, b):
#Square of both legs parameters
asquared = a**2
bsquared = b**2
print('leg a squared is ' + str(asquared))
print('leg b squared is ' + str(bsquared))
# should return a float
return 0.0
hypotenuse(3, 4)
# Calculates length of the hypotenuse of a
# right trianle given lengths of other 2 legs
def hypotenuse(a, b):
# square of both legs
asquared = a**2
bsquared = b**2
print('leg a squared is ' + str(asquared))
print('leg b squared is ' + str(bsquared))
# Sum of both squared legs
absum = asquared + bsquared
print('Sum of both sqaured legs is ' + str(absum))
# should return a float
return 0.0
hypotenuse(3, 4)
# Calculates length of the hypotenuse of a
# right trianle given lengths of other 2 legs
def hypotenuse(a, b):
# square of both legs
asquared = a**2
bsquared = b**2
# Sum of both squared legs
absum = asquared + bsquared
# Hypotenuse formular to get length
c = math.sqrt(absum)
print('length of hypotenuse of a triangle is ' + str(c))
# return the length of hypotenuse of a triangle
return c
hypotenuse(4, 5)
# Calculates length of the hypotenuse of a
# right trianle given lengths of other 2 legs
def hypotenuse(a, b):
# square of both legs
asquared = a**2
bsquared = b**2
# Sum of both squared legs
absum = asquared + bsquared
# Hypotenuse formular to get length
c = math.sqrt(absum)
# return the length of hypotenuse of a triangle
return c
hypotenuse(3, 4)
hypotenuse(2, 3)
hypotenuse(4, 5)
| true |
d124c6551c0f8d07c3737d412b690cac1af08876 | ericel/python101 | /volume_of_sphere.py | 982 | 4.34375 | 4 | import math
# Calculate the volume of a sphere
def volume_of_sphere(r):
print('returns a float 0.0')
return 0.0
# Call to check function initial works
volume_of_sphere(2)
# Calculate the volume of a sphere
def volume_of_sphere(r):
# calculate cubed of radius r
r3 = r ** 3
print('Sphere Radius cubed is ' + str(r3))
return 0.0
# Call to check function initial works
volume_of_sphere(2)
# Calculate the volume of a sphere
def volume_of_sphere(r):
# calculate cubed of radius r
r3 = r ** 3
# calculate pi(π)
pi = math.pi
print('π is ' + str(pi))
return 0.0
# Call to check function initial works
volume_of_sphere(2)
# Calculate the volume of a sphere
def volume_of_sphere(r):
# calculate cubed of radius r
r3 = r ** 3
# calculate pi(π)
pi = math.pi
# volume of sphere
v = (4/3) * pi * r3
print('Volume of sphere is ' + str(v))
return v
# Call to check function initial works
volume_of_sphere(4)
| true |
66ff09519b7f56fb7c8639106c08d1fcddef5d97 | mariskalucia/Py | /Ditctionaries.py | 393 | 4.375 | 4 | # Ditctionaries
print("Ditctionaries")
capitals = {"Japan":"Tokyo", "South Korea":"Seoul"}
print(capitals)
print(len(capitals))
capital = capitals["Japan"]
print(capital)
capitals["China"] = "Beijing"
capitals["Australia"] = "canberra"
print(capitals)
for country in capitals:
capital = capitals[country]
print("The capital of {} is {}.".format(country, capital)) | false |
8bba4750eceea388549be9f89eaee45227ca4942 | akaybanez/hacktoberfest2k | /scripts/aballe-melchi-3.py | 500 | 4.21875 | 4 | def incrementWhileLoop (a):
print ("While Loop increment values")
print ("Condition while a != b = (a + 5)")
b = a + 5
while (a != b):
print (a)
a += 1
def decrementWhileLoop (a):
print ("While Loop decrement values")
print ("Condition while a != b = (a - 5)")
b = a - 5
while (a != b):
print(a)
a -= 1
print (" ")
print ("Function for increment and decrement loops")
inpt1 = int(input("Enter a number: "))
incrementWhileLoop(inpt1)
print (" ")
decrementWhileLoop(inpt1)
print (" ") | false |
f5ed880f569a31a33a77d7968835351baf81e70e | Fortune-Adekogbe/ECX_30_days_of_code_Python | /Python files/Fortune_Adekogbe_day_25.py | 751 | 4.25 | 4 | def desc_triangle(a,b,c):
'''
This function takes in 3 integers a,b,c representing the length of the sides
of a triangle and Returns a tuple of 2 elements whose first element is a
string describing the triangle and second element is the area of the
triangle...
'''
s= (a+b+c)/2
area = ((s-a)*(s-b)*(s-c))**0.5
scalene = a!=b and b!=c and a!=c
equilateral = a==b==c
isosceles = len({a,b,c})==2
right = a**2 == b**2 + c**2 or a**2 == abs(b**2 - c**2)
if scalene: desc='Scalene Triangle'
elif equilateral: desc='Equilateral Triangle'
elif isosceles: desc = 'Isosceles Triangle'
if right: desc=desc[:-8]+'and Right Triangle'
return desc,round(area,2)
'''print(desc_triangle(3,4,5))'''
| true |
c5e1ebe304d4912e18203c00702e6d3f2967be21 | Fortune-Adekogbe/ECX_30_days_of_code_Python | /Python files/Fortune_Adekogbe_day_23.py | 736 | 4.40625 | 4 | def find_Armstrong(x,y):
'''
find_Armstrong is based on a definition for armstrong numbers that involves
summing the cubes of the digits in the number.
Parameters:
x: an integer representing the start of the interval
y:an integer representing the last number in the interval
Returns:
A list of all the armstrong numbers in the interval
'''
assert type(x)==int and type(y)==int and 0<=x<y,'Wrong range input'
if x>1000: return []
if y>1000: y=1000
arm= lambda num: sum(int(n)**3 for n in str(num))==num
return list(filter(arm,range(x,y+1)))
'''
print(find_Armstrong(-50,-100))
print(find_Armstrong(1,1000))
print(find_Armstrong(10000,10000000000))
print(find_Armstrong(152,153))
print(find_Armstrong(152,1520000))
''' | true |
fbc42a844313b04a8c38ea4f5b7c08f4fb08a276 | Fortune-Adekogbe/ECX_30_days_of_code_Python | /Python files/Fortune_Adekogbe_day_6.py | 463 | 4.15625 | 4 | def power_list(List):
"""
This function takes a list as parameter and returns its power list
(a list containing all the sub lists of a particular super list including null
list and list itself).
"""
if List==[]:
return [[]]
a=List[0]
b=power_list(List[1:])
c=[]
for d in b:
c.append([a]+ d)
return sorted(c+b,key=len)
'''
#test cases
x = power_list([2,4,6,8])
print(x)
print(power_list([9,100]))
''' | true |
f34b7153bc2df4a97fcbbe8a41ebfcf7e5ffc0b2 | DemetrioCN/random_walk | /1D_random_walk.py | 1,028 | 4.25 | 4 | # Random Walk in One Dimension
# DemetrioCN
import random
# Choose the next step and add it to the previous one
def walk_1D(steps):
count = 0
for i in range(steps):
walk = random.choice([(1),(-1)])
count += walk
return count
# Compute the distance from 0
def random_walk_1D(steps, attempts):
distance_sqrt = 0
for attempt in range(attempts):
distance = walk_1D(steps)
distance_sqrt += distance**2
average_distance = (distance_sqrt/attempts)**0.5
return round(average_distance,2)
def main(steps_list, attempts):
print("\n")
print(10*"-","RandomWalk's distances in One Dimension" ,10*"-")
print("\n")
print(f'Number of attempts: ', attempts)
print("\n")
for i in steps_list:
d = random_walk_1D(i,attempts)
print(f'The final distance for {i} steps is {d}')
print("\n")
# Program entry
if __name__ == '__main__':
steps_list = [100,200,300,400,500]
attempts = 10000
main(steps_list, attempts)
| true |
5abb7140a4733fbbed83230dcea680826002f5f6 | ian-gallmeister/sorting_algorithms | /pep8/radixsort.py | 1,259 | 4.21875 | 4 | #!/usr/bin/env python3
""" An implementation of radixsort """
import random
SHOW_LISTS = True
def radixsort(seq):
""" The radix sort algorithm """
max_val = max(seq)
oom = 0 #order of magnitude
while max_val // 10**oom > 0:
countingsort(seq, oom)
oom += 1
#adapt to take arg for which digit to use
def countingsort(seq, oom):
""" Countingsort adapted for radix sorts needs """
count_array = [0]*10 #decimal integer sort so only 10 digits
output_array = [0]*len(seq)
for val in seq:
newval = (val % 10**(oom+1))//(10**oom)
count_array[newval] += 1
for _ in range(1, 10): #decimal inegers
count_array[_] += count_array[_-1]
posn = len(seq) - 1
while posn >= 0:
newval = (seq[posn] % 10**(oom+1))//(10**oom)
output_array[count_array[newval]-1] = seq[posn]
count_array[newval] -= 1
posn -= 1
seq[0:] = output_array
def main():
""" Running radixsort for timing and whatever """
#length = random.randint(100000,1000000000)
length = 25
seq = [random.randint(0, 1000) for i in range(length)]
if SHOW_LISTS:
print(seq)
radixsort(seq)
if SHOW_LISTS:
print(seq)
if __name__ == '__main__':
main()
| true |
535a90af8ae6c271edaa538259579ee69cc24c0f | ES2Spring2019-ComputinginEngineering/hw3-sofialevy | /ES2BubbleLevel.py | 2,893 | 4.25 | 4 | # HOMEWORK 3 --- ES2
# Bubble Level
# FILL THESE COMMENTS IN
#*****************************************
# YOUR NAME: Sofia Levy
# NUMBER OF HOURS TO COMPLETE: 6
# YOUR COLLABORATION STATEMENT(s):
# I worked with Rene Jameson on this assignment.
# I received assistance from Dr. Cross on this assignment.
#*****************************************
import math
from microbit import *
def get_accel_x(): #returns the acceleration of x axis
return accelerometer.get_x()
def get_accel_y(): #returns the acceleration of y axis
return accelerometer.get_y()
def get_accel_z(): #returns the acceleration of z axis
return accelerometer.get_z()
def get_radians_y(x, y, z): #returns the angle between y and z in radians
x = get_accel_x()
y = get_accel_y()
z = get_accel_z()
return math.atan2(y, math.sqrt(x**2 + z**2))
def get_radians_x(x, y, z): #returns the angle between x and z in radians
x = get_accel_x()
y = get_accel_y()
z = get_accel_z()
return math.atan2(x, math.sqrt(y**2 + z**2))
def get_degrees_y(x, y, z): #returns the angle between y and z in degrees
return ((get_radians_y(x, y, z)*180)/math.pi)
def get_degrees_x(x, y, z): #returns the angle between x and z in degrees
return((get_radians_x(x, y, z)*180)/math.pi)
while True:
sleep(100)
x = get_accel_x()
y = get_accel_y()
z = get_accel_z()
a_y = get_degrees_y(x, y, z)
a_x = get_degrees_x(x, y, z)
#print((a_x, a_y))
if ((a_x >= -5 and a_x < 5) and (a_y >= -5 and a_y < 5)): #displays happy face when microbit is approximatley level
display.show(Image.HAPPY)
elif ((a_x <= 90 and a_x > 45) and (a_y >= -5 and a_y < 5)): #displays east arrow when microbit tilted east
display.show(Image.ARROW_E)
elif ((a_x >= -90 and a_x < -45) and (a_y >= -5 and a_y < 5)): #displays west arrow when microbit tilted west
display.show(Image.ARROW_W)
elif ((a_x >= -5 and a_x < 5) and (a_y <= 90 and a_y > 45)): #displays south arrow when microbit tilted south
display.show(Image.ARROW_S)
elif ((a_x >= -5 and a_x < 5) and (a_y >= -90 and a_y < -45)): #displays north arrow when microbit tilted north
display.show(Image.ARROW_N)
elif ((a_x <= 45 and a_x >= 5) and (a_y <= 45 and a_y >= 5)): #displays southeast arrow when microbit tilted southeast
display.show(Image.ARROW_SE)
elif ((a_x <= 45 and a_x >= 5) and (a_y >= -45 and a_y < -5)): #displays northeast arrow when microbit tilted northeast
display.show(Image.ARROW_NE)
elif ((a_x >= -45 and a_x < -5) and (a_y <= 45 and a_y >= 5)): #displays southwest arrow when microbit tilted southwest
display.show(Image.ARROW_SW)
elif ((a_x >= -45 and a_x < -5) and (a_y >= -45 and a_y < -5)): #displays northwest arrow when microbit tilted northwest
display.show(Image.ARROW_NW)
else:
None | true |
1ff4255feadcfcd2d20c8de6c5622fefd2354f45 | kmoreti/python-masterclass | /CreateDB/checkdb.py | 321 | 4.15625 | 4 | import sqlite3
conn = sqlite3.connect("contacts.sqlite")
name = input("Please enter a name to search for: ")
select_sql = "SELECT * FROM contacts WHERE name = ? "
result = conn.execute(select_sql, (name,))
print(result.fetchone())
# for row in conn.execute("SELECT * FROM contacts"):
# print(row)
conn.close()
| true |
0ef62d90642adc8a915ce64ae750fd0ee554c2d8 | mef21/GirlsWhoCode | /Lesson 1 - Variables/examples/example1.py | 1,041 | 4.59375 | 5 | """
WELCOME TO VARIABLES EXAMPLE 1
BEFORE YOU DO ANY CODING COPY THE BELOW TEXT INTO THE .replit FILE
language = "python3"
run = "cd 'Lesson 1 - Variables'; cd examples; clear; python3 example1.py"
Below are a series of examples using different types of variables and how to manipulate them:
"""
""" STRING EXAMPLE
Print out the value of a_string with other text such that the output is - hello world! Have a great day! Python is cool.
"""
# Solution 1
a_string = "hello world"
print(a_string + "! Have a great day! Python is cool.")
# Solution 2
a_string = "hello world"
a_string = a_string + "! Have a great day! Python is cool."
print(a_string)
# Solution 3
a_string = "hello world"
b_string = "! Have a great day! Python is cool."
print(a_string + b_string)
""" INTEGER/FLOAT EXAMPLE
Add multiply and divide to print out - number: 10
"""
# Solution 1
num1 = 2
num2 = 10
num3 = (num1*num2)/2
print("number: " + str(num3))
# Solution 2
num1 = 5
num2 = 4
num3 = 2
num4 = (num2/num3)*num1
print("number: " + str(num4))
| true |
0d0f05a92e4d6662322708f86ccf50a94699938b | mef21/GirlsWhoCode | /Lesson 2 - Conditionals/examples/examples.py | 888 | 4.46875 | 4 | """
WELCOME TO CONDITIONAL EXAMPLES
BEFORE YOU DO ANY CODING COPY THE BELOW TEXT INTO THE .replit FILE
language = "python3"
run = "cd 'Lesson 2 - Conditionals'; clear; cd examples; python3 examples.py"
"""
""" EXAMPLE 1 """
if(1 < 2):
print("1 is less than 2")
else:
print("1 is not less than 2")
""" EXAMPLE 2 - with VARIABLES """
x = 5
y = 10
if(x < y):
print("x is less than y")
else:
print("x is not less than y")
""" EXAMPLE 3 - with EQUALS sign """
x = 5
y = 10
if(x == y):
print("x is equal to y")
else:
print("x is not equal to y")
""" EXAMPLE 4 - with ELIF """
x = 5
y = 5
if (x < y):
print("x is less than y")
elif(x == y):
print("x is equal to y")
else:
print("x is greater than y")
""" EXAMPLE 5 - Nested if statements """
temperature = 80
if(temperature >= 80):
print("It is hot")
if(temperature >= 100):
print("You should stay indoors")
| true |
a28e74d2bc450034db3c043b4722d89f92b6827d | 712Danila712/edu_projects | /python/Stepic_1.12_3.py | 380 | 4.15625 | 4 | a = float(input())
b = float(input())
o = input()
if b == 0 and (o == "/" or o == "mod" or o == "div"):
print("Деление на 0!")
elif o == "+":
print(a + b)
elif o == "-":
print(a - b)
elif o == "/":
print(a / b)
elif o == "*":
print(a * b)
elif o == "mod":
print(a % b)
elif o == "div":
print(a // b)
elif o == "pow":
print(a ** b)
| false |
fb2abdde6842295463e0aa0aba32a99999663fa1 | cyhe/Python-Note | /Base/1.4_List.py | 2,154 | 4.3125 | 4 | # -*- coding: utf-8 -*-
# # list是一种有序的集合,可以随时添加和删除其中的元素。
workmates = ['jack', 'steve', 'boers']
print(workmates)
# 取元素
print('取出下标为1的元素', workmates[1])
# 取出最后一个元素还可以直接取-1 负号表示倒数 ,倒数第一(-1),倒数第二个(-2)
print('取出最后一个的元素', workmates[-1])
# 数组越界
"""
print('取出下标为-1的元素', workmates[3])
Traceback (most recent call last):
File "/Users/cyhe/Desktop/py/list.py", line 7, in <module>
print('取出下标为-1的元素', workmates[3])
IndexError: list index out of range
"""
# 数组操作
# list是可变的有序表 可以追加元素到末尾
workmates.append('lily')
print(workmates)
# 元素插入 插入到指定位置
workmates.insert(1, "mary")
print(workmates)
# 元素删除
# 1.删除末尾元素
workmates.pop()
# 2.删除指定位置
workmates.pop(2)
# 元素替换 某个元素替换为别的元素
workmates[1] = 'michel'
# list的元素类型可以不同
list = ['list', 123456, True]
print(list)
# list也支持索引和切片
print('切片后:', list[1:3])
# [123456, True]
# 删除操作
list[1:3] = []
print('删除后:', list)
# 判断值是否存在列表中
a = 'list' in list
print(a) # True
b = 20 in list
print(b) # False
# list的元素可以是一个list 相当于二维数组
fruits = ['apple', 'orange', ['redPitaya', 'whitePitaya'], 'Grape']
print(fruits)
print(fruits[2])
# 数组长度len()
print(len(fruits))
# --------------------------------- 分割线---------------------------------
# tuple 另一种有序列表 元组 tuple一旦初始化就不能修改 不可变
# 定义空tuple
t = ()
# 定义有一个元素的tuple (1, ) 消除与单纯()歧义
t1 = (1, )
# 问题? t = ('a', 'b', ['A', 'B'])
t2 = ('a', 'b', ['A', 'B'])
t2[2][0] = 'X'
t2[2][1] = 'Y'
print(t2)
"""
tuple说不能变,但是却变了, 但变的不是tuple的元素,而是list元素,
tuple一开始指向list并没有改成别的list,tuple的每个元素,永远
指向不变,之所以变了,是指向的list没变,而指向的list本身是可变的
"""
| false |
9a08902a1af1388c059b11369ec44726a9f09944 | IgnacioZentenoSmith/notable_challenges | /All or Any.py | 1,475 | 4.21875 | 4 | '''
CREDITS TO HACKERRANK FOR THIS CHALLENGE
TASK
You are given a space separated list of integers. If all the integers are positive, then you need to check if any integer is a palindromic integer.
Input Format
The first line contains an integer . is the total number of integers in the list.
The second line contains the space separated list of integers.
Constraints
0 < N < 100
Output Format
Print True if all the conditions of the problem statement are satisfied. Otherwise, print False.
Sample Input
5
12 9 61 5 14
Sample Output
True
Explanation
Condition 1: All the integers in the list are positive.
Condition 2: 5 is a palindromic integer.
Hence, the output is True.
SOLVE THIS CHALLENGE IN 3 LINES
'''
s = [int(input())] + [int(i) for i in(input().split())]
if (all(i >= 0 for i in s) and any(str(i) == str(i)[::-1] for i in s[2:])): print(True)
else: print(False)
'''
FIRST LINE: creates a joined list by making a list of the first integer in the input and the string generated by the split function over the input(), then the list comprehension transform into int each element of the string and transform it into a list
SECOND LINE: checks if every element of the ints list is positive
checks if any element of the ints list transformed to strings is the same as reversed (palindromic integer), transformed to string to reverse it easier
if these conditions are met, prints True
'''
| true |
a21cc3d5bc986b700af3d5c863c0ef80b1d41b51 | Samarkina/PythonTasks | /6.py | 907 | 4.125 | 4 | # Monthly interest rate = (Annual interest rate) / 12.0
# Monthly payment lower bound = Balance / 12
# Monthly payment upper bound = (Balance x (1 + Monthly interest rate)^12) / 12.0
balance = float(input("balance - the outstanding balance on the credit card: "))
AnnualInterestRate = float(input("annualInterestRate - annual interest rate as a decimal: "))
r = AnnualInterestRate / 12.0
payment = 0
begBalance = balance
lowerBound = balance / 12
upperBound = (balance * (1 + r)**12) / 12.0
e = 0.03
while abs(balance) > e:
payment = (lowerBound + upperBound) / 2
balance = begBalance
for i in range(12):
ub = balance - payment
interest = r * ub
balance = ub + interest
if balance > e:
lowerBound = payment
elif balance < -e:
upperBound = payment
else:
break
print("Lowest Payment: {}".format(round(payment, 2)))
# 5000
# 0.18
| true |
8b5fe8de96e8e778ec30d5cf23371ae2c4cfc6e1 | IhebChatti/holbertonschool-higher_level_programming | /0x10-python-network_0/6-peak.py | 904 | 4.1875 | 4 | #!/usr/bin/python3
"""[python script to find peak of list]
"""
def peakfinder(list_of_integers, bot, top):
"""[recursively search for peak in list]
Args:
list_of_integers ([list]): [list of ints]
bot ([int]): [first item of list]
top ([int]): [last item of list]
Returns:
[int]: [peak of list]
"""
if bot == top:
return list_of_integers[top]
mid = (bot + top) // 2
if list_of_integers[mid + 1] < list_of_integers[mid]:
return peakfinder(list_of_integers, bot, mid)
return peakfinder(list_of_integers, mid + 1, top)
def find_peak(list_of_integers):
"""[find peak function]
Args:
list_of_integers ([list]): [list containing ints]
"""
n = len(list_of_integers)
if n == 0:
return None
if n == 1:
return list_of_integers[0]
return peakfinder(list_of_integers, 0, n - 1)
| false |
ea6a053af6727ae9a3c09ac44e21ad29230235a4 | dfilter/udemy-flask-restapi | /section-2/29-lambda-functions.py | 719 | 4.34375 | 4 | def add(x, y):
return x + y
# Same as above function
add = lambda x, y: x + y
print(add(1, 2))
# lambda function can be executed without being named like this:
sum_ = (lambda x, y: x + y)(5, 7)
print(sum_)
def double(x):
return x * 2
sequence = [1, 3, 5, 9]
doubled = [double(x) for x in sequence]
# same as above but using "map()" function.
# Note that map is slower then list comprehension
# Note that map returns a map object and not a list
doubled = list(map(double, sequence))
# to do the same as above but with a lambda expression:
# Note that the bottom one is preferred as it is more readable
doubled = [(lambda x: x * 2)(x) for x in sequence)]
doubled = list(map(lambda x: x * 2, sequence))
| true |
f04e411b6921aff654df609b8ac717beedd27b7c | Ellis-Anderson/Pluralsight_Python | /Getting_Started/hs_students.py | 703 | 4.15625 | 4 | class HighSchoolStudent(Student):
"""
Adds a High School Student to the list.
:param name: string - student name
:param student_id: integer - optional student ID
"""
# Derived/child class. Attributes, like school_name, can be overridden
school_name = "Springfield High School"
# Methods can also be overridden, as below
def get_school_name(self):
return "This is a high school student"
# You can also modify parent methods as shown below
# super() refers to the parent classes method
def get_name_capitalized(self):
original_value = super().get_name_capitalized()
return original_value + ' -HS'
| true |
e8e49bbf5245a46172cd6e1b36124e3337c9de65 | Ran05/cwd-marketing-bot | /bot.py | 1,930 | 4.15625 | 4 | def greetings(bot_name):
outputLine = f"""==========================================================================="""
print(outputLine)
print("Hello! My name is {0}.".format(bot_name))
print("We'd like to help you with your digital marketing needs! \nWe'll help you build your brand online by creating a website, SEO, Social media marketing and more!\nReady to take your business to the next level?")
# all input data will stored here in client info list
client_info = []
def remind_name():
print('Please, remind me your name.')
name = input("Enter Here: ")
client_info.append(name)
print("What a great name you have, {0}!".format(name))
def client_query():
print('Now I want to know how can I help you?')
services= str(input("Your Answer here: "))
client_info.append(services)
print(client_info)
print(output)
output = f"""
========== Please Select by choosing number ==========
"""
def website_offer():
print("Okay now Can you tell me what type of website you want to build?")
print("Here is the ordered list: ")
print("1. Informational ")
print("2. E-commerce")
print("3. Online Booking")
print("4. Membership")
print("5. Combination")
# answer = 1
guess = int(input("Please select by a number: "))
client_info.append(guess)
print(client_info)
# while guess != int():
# print("Please, try again.")
# guess = int(print(input("Please select by choosing number:" )))
# print(input("Please select by choosing number: " + " "+ str(guess)))
def end():
print('Thank you, have a nice day!')
print('.................................')
print('.................................')
print('.................................')
#Here is my define functions
greetings('Randolfh') # change it as you need
remind_name()
client_query()
website_offer()
end()
| true |
39ee7a169e9a69700650de41712c7629b6d90926 | wdampier2000/pyton-curso | /10-sets-diccionarios/diccionarios.py | 732 | 4.125 | 4 |
"""
Como una lista pero son datos que almacena indices alfanumerico
formato clave > valos
"""
persona= {
"nombre": "Victor", #nompre es el indice, Victor es el valor
"apellido": "Rigacci",
"email": "riga@rmi.com.ar",
}
print(type(persona))
print(persona)
print(persona["apellido"])
print("\n")
#lista con diccionarios
contactos=[
{
'nombre': 'Antonio',
'email': 'antonio@gmail.com'
},
{
'nombre': 'Jose',
'email': 'jose@gmail.com'
},
{
'nombre': 'Raul',
'email': 'raul@gmail.com'
},
{
'nombre': 'Ricardo',
'email': 'ricardo@gmail.com'
}
]
print(contactos)
print(contactos[1]['nombre'])
contactos[1]['nombre']="Josesito"
print(contactos[1]['nombre'])
| false |
249ffde4bd50f3d91ba7e4cf03bb0d76197a32d1 | sheleh/homeworks | /lesson_25/task_25_3.py | 1,176 | 4.375 | 4 | # Implement a queue using a singly linked list.
from lesson_25.task_25_1 import Node
class Queue:
def __init__(self):
self._head = self._tail = None
def is_empty(self):
if self._head is None:
return True
else:
return False
def enqueue(self, item):
current = Node(item)
if self._tail is None:
self._head = self._tail = current
return
self._tail.set_next(current)
self._tail = current
def dequeue(self):
current = self._head
self._head = current.get_next()
def display(self):
current = self._head
if self.is_empty():
print('Nothing in queue')
else:
rep = f'head = {self._head.get_data()} tail = {self._tail.get_data()} -> \n'
while current is not None:
rep += f'{current.get_data()} -> '
current = current.get_next()
return rep
my_queue = Queue()
my_queue.enqueue(5)
my_queue.enqueue(10)
my_queue.enqueue(15)
my_queue.enqueue(20)
my_queue.enqueue(25)
my_queue.dequeue()
print(my_queue.is_empty())
print(my_queue.display())
| true |
6d1bdf281cb4c1a2ece1b5944ece0aa444acfc4b | sheleh/homeworks | /lesson11/task_11_1.py | 1,798 | 4.15625 | 4 | #School
#Make a class structure in python representing people at school. Make a base class called Person, a class called Student,
# and another one called Teacher. Try to find as many methods and attributes as you can which belong to different classes,
# and keep in mind which are common and which are not. For example, the name should be a Person attribute,
# while salary should only be available to the teacher.
class Person:
def __init__(self, gender, name, age, height, weight):
self.gender = gender
self.name = name
self.age = age
self.height = height
self.weight = weight
def bmi(self):
res = self.weight / ((self.height/100)**2)
if res < 25:
print(f'{self.name}\'s weight is normal')
elif 25 < res <= 29:
print(f'{self.name}\'s have overweight')
elif res > 30:
print(f'{self.name}\' Obese')
return res
class Teacher(Person):
def __init__(self, gender, name, age, height, weight, salary):
super().__init__(gender, name, age, height, weight)
self.salary = salary
def going_to_job(self):
print(f'Teacher {self.name} going to work and maybe will have a salary {self.salary}')
class Student(Person):
def __init__(self, gender, name, age, height, weight, class_num, class_literal):
super().__init__(gender, name, age, height, weight)
self.class_num = class_num
self.class_literal = class_literal
def going_to_study(self):
print(f'Student {self.name} going to study in class = {str(self.class_num) + self.class_literal}')
alex = Teacher('male', 'Alex', 35, 185, 77, 3500)
alex.bmi()
alex.going_to_job()
donald = Student('male', 'Donald', 17, 180, 74, 11, 'B')
donald.bmi()
donald.going_to_study() | true |
0340793c8ad45699b466d2a4d25e4f6ad630e7e1 | sheleh/homeworks | /lesson3/task_3.py | 807 | 4.1875 | 4 | #Write a program that has a variable with your name stored (in lowercase)
# and then asks for your name as input. The program should check if your input is equal to the stored name
# even if the given name has another case, e.g., if your input is “Anton” and the stored name is “anton”,
# it should return True.
name = 'dmytro'
input_name = 'Dmytro'
if name == input_name.lower():
print(f'right_name {name} is correct')
else: print('Wrong, please try again')
# variant2
status = False
while not status:
input_name2 = input('Please try to guess a name or press 0 to exit: ')
if input_name2 == name.lower():
print('right')
status = True
break
elif input_name2 == '0':
print('looser')
break
else:
print('wrong! please try again')
| true |
0bde00df76938a0e0dbf9938b2ce4ccfce89b8a2 | leecmoses/intro-to-cs | /18-how-programs-run/notes.py | 2,624 | 4.1875 | 4 | #############
# Notes #
# Lesson 18 #
#############
'''
Algorithm - is a procedure that always finishes and produces the correct result
Procedure - is a well defined sequence of steps that can be executed mechanically
Equivalent Expressions
* A property 'ord' and 'chr' is that they are inverses.
* This means that if you input a single letter string to ord and then input the answer to chr, you get back the original single letter.
* ord(<one-letter string>) -> Number
* If you input a number to chr and then input the answer to that into ord, you get back the original number (as long as that number is within a certain range, 0 to 255 inclusive)
* chr(<Number>) -> <one-letter string>
'''
'''
Quiz: Better Hash Functions
'''
# my solution
def hash_string(keyword,buckets):
h = 0
for c in keyword:
h += ord(c)
return h % buckets
# alternative solution
def hash_string(keyword,buckets):
h = 0
for c in keyword:
h = (h + ord(c)) % buckets
return h
'''
Quiz: Empty Hash Table
'''
def make_hashtable(nbuckets):
i = 0
table = []
while i < nbuckets:
table.append([])
i += 1
return table
# alternative solution
def make_hashtable(nbuckets):
table = []
for unused in range(0,nbuckets):
table.append([])
return table
'''
Quiz: Find Buckets
'''
def hashtable_get_bucket(htable,keyword):
return htable[hash_string(keyword,len(htable))]
'''
Quiz: Adding Keywords
'''
def hashtable_add(htable,key,value):
hashtable_get_bucket(htable,key).append([key, value])
return htable
'''
Quiz: Lookup
'''
def hashtable_lookup(htable,key):
bucket = hashtable_get_bucket(htable,key)
for entry in bucket:
if entry[0] == key:
return entry[1]
return None
'''
Quiz: Update
'''
# my solution
def hashtable_update(htable,key,value):
bucket = hashtable_get_bucket(htable,key)
if hashtable_lookup(htable,key):
for entry in bucket:
if entry[0] == key:
entry[1] = value
else:
hashtable_add(htable,key,value)
return htable
# alternative solution
def hashtable_update(htable,key,value):
bucket = hashtable_get_bucket(htable,key)
for entry in bucket:
if entry[0] == key:
entry[1] = value
return htable
bucket.append([key, value])
return htable
'''
Dictionaries
String - sequence of characters (immutable)
List - list of elements (mutable) []
Dictionary - set of key-value pairs, <key, value> (mutable) {}
* Essentially python's built-in hash function.
'''
| true |
e5952bd822051b4e4a0a5fb7f0f6a8c9d08ecbc3 | Pav0l/Sorting | /src/searching/searching.py | 2,544 | 4.21875 | 4 | # STRETCH: implement Linear Search
def linear_search(arr, target):
res = False
for i in arr:
if arr[i] == target:
res = i
if not res:
print('Linear Search: Target not found!')
else:
print(f'Linear Search: Found the target value at index {res}')
# linear_search([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 5)
# STRETCH: write an iterative implementation of Binary Search
def binary_search(arr, target):
if len(arr) == 0:
return -1 # array empty
# check value at mid_idx vs. target value
# if equal => return mid_idx and end
# if val[mid_idx] < target => cut out left side from mid_idx and repeat
# if val[mid_idx] > target => cut out right side from mid_idx and repeat
low = 0
high = len(arr)-1
while low <= high:
print('\n***New while loop***')
middle_idx = (high + low) // 2
print(
f'list of {arr[low:high]}:\nlow: {low}\nhigh: {high}\nmid_idx: {middle_idx}\ntarget: {target}')
if target < arr[middle_idx]:
high = middle_idx - 1
print(
f'\nRemoved RHS. New values: \nlow: {low}\nhigh: {high}')
elif target > arr[middle_idx]:
low = middle_idx + 1
print(
f'\nRemoved LHS. New values: \nlow: {low}\nhigh: {high}')
else:
return f'\nTarget found at index: {middle_idx}'
return '\nTarget not found'
# print(binary_search([0, 1, 2, 3, 4, 5, 6, 8, 9], 7))
# STRETCH: write a recursive implementation of Binary Search
def binary_search_recursive(arr, target, low, high):
middle = (low+high)//2
if len(arr) == 0:
return 'Can not serach in empty list'
# TO-DO: add missing if/else statements, recursive calls
print(
f'\nSearching in arr: {arr[low:high]}\nTarget: {target}\nMid point: {arr[middle]} at index {middle}')
if target < arr[middle]:
print(
f'Target lower than mid. Removing RHS. Resulting arr: {arr[0:middle-1]}')
return binary_search_recursive(arr, target, 0, middle-1)
elif target > arr[middle]:
print(
f'Target higher than mid. Removing LHS. Resulting arr: {arr[middle+1:high]}')
return binary_search_recursive(arr, target, middle+1, high)
elif target == arr[middle]:
return middle
else:
return 'Target not found'
return f'Target found at index: {middle}'
a = [0, 1, 2, 3, 4, 5, 6, 8, 9]
low = 0
high = len(a)-1
print(binary_search_recursive(a, 8, low, high))
| true |
9d001981862c261062a6ae6b0507c5e24c9b2cc8 | zackguerra/git_practice | /PycharmProjects/IntroToAlgorithmsPython/6_Conditionals/conditional_statements.py | 373 | 4.25 | 4 | # Conditional Statements
# (if-else statements)
# Getting user input
# input(prompt) - atkes user input and returns as string
# Later (Error handling and validation)
age = int(input("Enter your age:"))
# or use age = int(age)
if age >= 21:
print("You can start drinking!")
elif 13 < age < 21:
print("Study hard fot SAT!")
else:
print("Play video games!") | true |
21949834637a1b26e3264dbe55536f0b35d23ec6 | zackguerra/git_practice | /PycharmProjects/IntroToAlgorithmsPython/Labs/Lab_Binary_Linear_Search.py | 1,607 | 4.375 | 4 | # In this lab, you will be using two searching algorithms we covered in class to
# search for a word in dictionary. Compare the performance for each algorithm.
# You will have to output the number of steps for both algorithms when used for searching
# for the same word. (case-insensitive)
# Your output should look like this. Try to search for 5 different words of your choice.
#
# ex)
# Searching for "orange"...
# Linear Search: {} steps
# Binary Search: {} steps
#
# Searching for "orangeeeeee"...
# Linear Search: no matching word found
# Binary Search: no matching word found
# Open the dictionary file and read all lines as a list of words.
with open('words') as f:
lines = f.readlines()
# Strip off the newline character for each word.
lines = [line.strip() for line in lines]
print(lines)
def binary_search(items, target):
steps = 0
start = 0
end = len(items)-1
while start<=end:
middle= (start+end)//2
print(target,items[middle])
if target == items[middle]:
return middle,steps
elif target< items[middle]:
end = middle-1
else:
start = middle+1
print(start,end)
steps +=1
return -1,steps
def linear_search(items,target):
step = 0
for i in items:
if target == i:
return step,step
step += 1
return step,step
search = input("word to search: ")
print("Looking for :",search)
print("Binary search: (index, steps) ",binary_search(lines,search))
print("Linear search: (index, steps) ",linear_search(lines,search)) | true |
8d0e859942bbf5c1c23304140465496ee8fb4f54 | zackguerra/git_practice | /PycharmProjects/IntroToAlgorithmsPython/12_SortingAlgorithm/bubble_sort.py | 887 | 4.21875 | 4 | # Bubble Sort
# - Time Complexity: O(n^2)
#
# For each scan,
# For each comparison (two adjacent items),
# if left item > right item:
# "swap" two items
items = [5, 2, 1, 4, 3]
# Naive Bubble Sort -> can be improved!
def naive_bubble_sort(items):
steps = 0
for scan in range(len(items)):
for j in range(len(items) - 1):
steps += 1
if items[j] > items[j+1]:
items[j], items[j+1] = items[j+1], items[j]
print(steps)
def bubble_sort(items):
steps = 0
for scan in range(len(items)):
is_swapped = False
for j in range(len(items) - 1 - scan):
steps += 1
if items[j] > items[j+1]:
# swap
items[j], items[j+1] = items[j+1], items[j]
is_swapped = True
if not is_swapped:
break
print(steps) | true |
5d83e64d0b90935ff1f01fb4565dd914c3060628 | HasibeZaferr/PythonBasicExamples | /tuples.py | 745 | 4.34375 | 4 | # -*- coding: utf-8 -*-
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # tuple içindeki tüm elemanları yazar.
print (tuple[0]) # tuple içindeki ilk elemanı yazar.
print (tuple[1:3]) # 2. elemandan 3. elemana kadar olanları yazar.
print (tuple[2:]) # 3. elemandan ve sonrasındaki bütün elemanları yazar.
print (tinytuple * 2) # tinytuple içindeki elemanları iki kere yazar.
print (tuple + tinytuple) # tuple ve tinytuple içindeki elemanları birleştirerek yazar.
#Listeler ve tuple'ler arasındaki temel fark: listeler köşeli parantez içerisindedir []
# ve elemanları ve boyutu değiştirilebilir, ancak tuple parantez içine alınır () ve güncellenemez. | false |
6c253aa9c69ea1a582068e67507a27c1143a1fbb | Akshaykumara62/Assignment-1 | /Factorial Assignment.py | 391 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#5! = 1*2*3*4*5 =120
# In[13]:
factorial = 1
num = 5
if num<0:
print("factorial does not exist 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)
# In[ ]:
# In[ ]:
# In[ ]:
| false |
87054dbe6be6523dbe9af5a6eb9c4e636d74a338 | Himstar8/Algorithm-Enthusiasts | /algorithms/sorting/shell_sort/shell_sort.py | 565 | 4.15625 | 4 | def shell_sort(arr):
length = len(arr)
h = 1
# find the starting h value
while h < length / 3:
h = 3 * h + 1
while h >= 1:
for i in range(h, length):
tmp = arr[i]
pos = i
while pos >= h and arr[pos - h] > tmp:
arr[pos] = arr[pos - h]
pos -= h
arr[pos] = tmp
h = int(h / 3)
return arr
if __name__ == '__main__':
arr = [4, 7, 10, 2, 0, 5, -9, 13]
print(shell_sort(arr))
assert shell_sort(arr) == [-9, 0, 2, 4, 5, 7, 10, 13]
| false |
1c0c8fc7666041fba47bcec27315971b5d13c746 | Himstar8/Algorithm-Enthusiasts | /algorithms/arrays/search_in_rotated_sorted_array/search_in_rotated_sorted_array.py | 824 | 4.21875 | 4 | def search_in_rotated_sorted_array(nums, target):
def binary_search(start, end):
while start <= end:
mid = (end + start) // 2
if target == nums[mid]:
return mid
elif target > nums[mid]:
start = mid + 1
else:
end = mid - 1
return -1
i = 0
len_n = len(nums)
if len_n == 1:
return 0 if nums[0] == target else -1
while i < len_n - 1 and nums[i] < nums[i + 1]:
i += 1
if i == len_n - 1:
return binary_search(0, len_n - 1)
elif target > nums[0]:
return binary_search(0, i)
elif target < nums[0]:
return binary_search(i + 1, len_n - 1)
else:
return 0
if __name__ == '__main__':
print(search_in_rotated_sorted_array([1, 3], 3))
| false |
2f265398b7026b9291f91c99981fbc0024a12e96 | np-n/Python-Basics-GCA | /Session 1/Variable.py | 1,499 | 4.4375 | 4 |
"""-------------------------------------------------"""
##print("Hello World") # First program
msg = "Hello World"
##print(msg)
"""-------------------------------------------------"""
# Knowing the type of the variable
##print("Msg is of type: ", type(msg))
##print("1 is of type: ", type(1))
##print("-1 is of type: ", type(-1))
##print("4.2 is of type: ", type(4.2))
"""-------------------------------------------------"""
# Finding the volume of a sphere
##pi = 3.1416
##radius = 0.6
##
##"""Note: Execution follows pedmas rule which
## is Parenthesis, Exponential, Division,
## Multiplication, Addition and Subtraction"""
##
##volume = 4/3*pi*(radius**3)
##print("Volume is: ", volume)
"""-------------------------------------------------"""
# Use of + operator for number and string
### print("Adding 1 and 2: ", 1 + 2)
##first_name = "Bob"
##last_name = "Dylan"
##full_name = first_name + " " + last_name
##print("Adding Bob and Dylan: ", full_name)
"""-------------------------------------------------"""
# Printing person name along with dob
##first_name = input("Enter your first name: ")
##last_name = input("Enter your last name: ")
##
##print("Enter your date of birth: ")
##
##month = input("Month? ")
##day = input("Day? ")
##year = input("Year? ")
##
##print(first_name + " " + last_name + " "
## + "was born on " + month + " " + day + " " + year)
"""Note: + operator concatenetes two string along with
addition of numbers"""
# To find squre root
print(99**0.5)
| true |
925f6c07306067409e400ce657ac9a00932c61e5 | np-n/Python-Basics-GCA | /Session 3/reverse_string.py | 431 | 4.25 | 4 |
"""
Module to reverse a string either a word or sentence
using loops and inbuilt methods
"""
sentence = "Python is beautiful"
_reverse = []
# print(len(sentence))
# Using loops
##for c in range(len(sentence)-1, -1, -1):
## # print(sentence[c])
## _reverse.append(sentence[c])
##
### print(_reverse)
##
##_revstr = ''.join(_reverse)
##print(_revstr)
##
### Using slicing
_reverse = sentence[::-1]
print(_reverse)
| true |
e1fb187e9da12e64a048cc922a2ef8c753f02200 | 8chill3s/py4e | /ex_5_2.py | 546 | 4.1875 | 4 | largest = None
smallest = None
while True:
num = input('Enter a number: ')
if num == 'done': break
#validate input
try:
num = int(num)
except:
print('Invalid input')
continue
#compare integers
if largest is None:
largest = num
elif num > largest:
largest = num
elif smallest is None:
smallest = num
elif num < smallest:
smallest = num
#print (num)
print('Maximum is',largest)
print('Minimum is',smallest)
| true |
ef5950d0d2be143fd223df9f191fa60f7be0b9d4 | AtheeshRathnaweera/Cryptography_with_python | /hash.py | 1,073 | 4.1875 | 4 | from Crypto.Hash import SHA256
print ("\n\t\t____________ PASSWORD MANAGEMENT DEMO USING HASH VALUES ____________\n")
createdHash = 0
#Check the created password and validate
def passwordCreation():
userPw = input("\tCreate a new password : ")
print ("\tPassword: "+userPw)
global createdHash
createdHash = hashing(userPw)
print ("\tPassword HASH : "+createdHash)
def hashing(valueToHash): #hashing function
encodedValue = valueToHash.encode('utf-8') #Unicode text should be encoded to the bytes before hashing
tempHash = SHA256.new(encodedValue).hexdigest()
return tempHash
def checkThePassword():
print("\n\t\t_____________ DEMO PASSWORD CHECKING ____________\n")
tempPassword = input("\tEnter your password : ")
pwHash = hashing(tempPassword)
global createdHash
if (pwHash == createdHash) :
print ("\tPassword matched.")
else:
print("\tPassword mismatched.")
print ("\n\tnew hash: "+pwHash+" \n\thash in db: "+str(createdHash))
passwordCreation()
checkThePassword()
| false |
b95f5e7efa0c5dfc3ac527dac1f8a33a1443843b | netxeye/Python-programming-exercises | /answers/q65.py | 1,039 | 4.21875 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
def question65_fibonacci(n):
if not isinstance(n, int):
raise ValueError('Exception: Function only accepts integer value')
if n == 1:
return 1
elif n == 0:
return 0
else:
return question65_fibonacci(n - 1) + question65_fibonacci(n - 2)
def question65_fibonacci_tail_recursion(n, result=1):
if not isinstance(n, int):
raise ValueError('Exception: Function only accepts integer value')
if n == 1:
return result
else:
return question65_fibonacci_tail_recursion(n - 2, result + n - 1)
def question65_fibonacci_generator(n):
if not isinstance(n, int):
raise ValueError('Exception: Function only accepts integer values')
i, a, b = 0, 0, 1
while i < n:
yield a
a, b = b, a + b
i += 1
print(question65_fibonacci(10))
print(question65_fibonacci_tail_recursion(5))
print(list(question65_fibonacci_generator(8))[-1:])
print(list(question65_fibonacci_generator(10)))
| false |
641a2855da5e639eaa2b6f2bd0219fe29bbd39f1 | techsoftw/General-Coding | /Python/lab8.2.py | 1,644 | 4.21875 | 4 | #!/usr/bin/python
# NAME: Dylan Tu
# FILE: lab8.2.py
# DESC: Connect to sqlite3 database, insert and prints data
import sqlite3
# sqlite3.connect creates a file named 'databasefile.db' on the system.
connection = sqlite3.connect('week16.db')
# The cursor is the control structure that traverses records in the database.
cursor = connection.cursor()
cursor.execute("INSERT INTO products values(null, ?, ?, ?, ?)", ('Hurricane Jelly Beans','jelly beans','abc123', '1.00'))
cursor.execute("INSERT INTO products values(null, ?, ?, ?, ?)", ('Typhoon Model Boat','plastic model boat', 'abc456', '12.00'))
cursor.execute("INSERT INTO products values(null, ?, ?, ?, ?)", ('Supermarine Spitfire', 'plastic model airplane', 'bcd123', '3.00'))
cursor.execute("INSERT INTO products values(null, ?, ?, ?, ?)", ('ENIAC', 'model of first computer', 'bcd456', '21.00'))
cursor.execute("INSERT INTO products values(null, ?, ?, ?, ?)", ('The Structure and Interpretation of Computer Programs','book','abc123', '36.00'))
cursor.execute("INSERT INTO products values(null, ?, ?, ?, ?)", ('Black Rice and Salmon','food', 'abc456', '15.00'))
cursor.execute("INSERT INTO products values(null, ?, ?, ?, ?)", ('ZTE Atom', 'smartphone', 'bcd123', '350.00'))
cursor.execute("INSERT INTO products values(null, ?, ?, ?, ?)", ('Coca-Cola Can', 'soft drink', 'bcd456', '0.75'))
cursor.execute("INSERT INTO products values(null, ?, ?, ?, ?)", ('SQL Server 2012', 'enterprise database subscription', 'bcd123', '10000.00'))
cursor.execute("INSERT INTO products values(null, ?, ?, ?, ?)", ('Plastic Forks', 'utensils', 'bcd456', '2.75'))
# Commit the changes
connection.commit()
| true |
d9d91e1f2191bd6722dac905a5008ecb75773af9 | viver2003/school | /odd>even.py | 656 | 4.28125 | 4 | x = float(input('input a number: '))
y = float(input('input another number: '))
n = float(input('input yet another number: '))
if x % 2 == 0 and y % 2 == 0:
print 'There are more even numbers than odd numbers!'
if x % 2 == 0 and n % 2 == 0:
print 'There are more even numbers than odd numbers!'
if y % 2 == 0 and n % 2 == 0:
print 'There are more even numbers than odd numbers!'
if x % 2 == 1 and y % 2 == 1:
print 'There are more odd numbers than even numbers!'
if x % 2 == 1 and n % 2 == 1:
print 'There are more odd numbers than even numbers!'
if y % 2 == 1 and n % 2 == 1:
print 'There are more odd numbers than even numbers!'
| false |
661be2d62d9259abc244533ccccc8ccfdb408b3b | ttop5/ChallengePython | /page_02/19.py | 367 | 4.21875 | 4 | # 思路一:转换成同字符以后用in:
UPPER = a.upper()
if 'LOVE' in UPPER:
print 'LOVE'
else:
print 'SINGLE'
# 或者使用find
UPPER = a.upper()
if UPPER.find('LOVE') >= 0:
print 'LOVE'
else:
print 'SINGLE'
# 思路二:使用正则
import re
flag = re.findall("[lL][oO][vV][eE]",a)
if flag:
print 'LOVE'
else:
print 'SINGLE'
| false |
d3ac5b7e14663381177c3d0a2ca40d63cecfe139 | Wambita/pythonprework | /looping/forloop/for_loop.py | 327 | 4.375 | 4 | #A for loop is used when one wants to repeat something a number of times. Just like the if statements, blocks of code in a for loop are indented, otherwise they will not run.
numbers = [1,2,3,4,5]
for number in numbers:
print(number)
letters = ['a','b','c','d','e','f','g','h']
for letter in letters:
print(letter) | true |
0b46922e480d9e580a6b613afc9da7260cd11c10 | Vitalii-Tolkachov/Test_05092020 | /home_work_3/6.py | 552 | 4.3125 | 4 | # Пишем программу, которая попросит пользователя ввести слово
# (строка без пробелов в середине, а вначале и в конце пробелы могут быть),
# состоящее только из символов букв.
# Пока он не введёт правильно, просите его ввести.
while True:
mess = input("enter no space word: ")
mess = mess.strip()
if ' ' not in mess and mess.isalpha():
break
print("Ok")
| false |
496b1b48419b12ca3a808e5ddf2c527e889a4983 | Eternally1/web | /python/基础/one16.py | 615 | 4.1875 | 4 | """
一个摄氏度 华氏度转换的例子
"""
class Celsius:
def __init__(self,value=26.0):
self.value = value
def __get__(self,instance,owner):
return self.value
def __set__(self,instance,value):
self.value = value
class Fahrenheit:
def __get__(self,instance,owner):
return instance.cel * 1.8 + 32
def __set__(self,instance,value):
instance.cel = (float(value)-32)/1.8
class Temperature:
cel = Celsius()
fah = Fahrenheit()
temp = Temperature()
print(temp.cel)
temp.cel = 32
print(temp.cel,temp.fah)
temp.fah = 100
print(temp.cel,temp.fah) | false |
16108ab9efad2788494da28d46bb1074c77d9458 | AJV1416/test2 | /Story.py | 981 | 4.21875 | 4 | start = '''
You are now playing as Alice from Wonderland, Try and get through all the Disney characters!
'''
keepplaying = "yes"
print(start)
while keepplaying == "yes" or keepplaying =="Yes":
print("Mickey is your first character, make sure you answer his question to get through")
userchoice = input("What is my dog's name?")
if userchoice == "Pluto"or userchoice =="pluto":
print(" He looks happy and says Great job!")
keepplaying = "no"
else:
print("That is not correct try again, hint: It's similar to a planet.")
keepplaying = "yes"
while keepplaying == "yes" or keepplaying == "Yes":
print(" Great job, you've made it to your second character: Daisy Duck ")
userchoice = input(" Who is her boyfriend?")
if userchoice == "Donald Duck" or userchoice == "donald duck":
print("Good job! that is correct.")
keepplaying = "no"
else:
print("That is not correct try again,")
| true |
733b4f77c9f50f7d09226b4f44363bca86e1b25d | tmiklu/hra | /game.py | 1,850 | 4.15625 | 4 | import os
import random
print("Zahraj si hru kamen, papier a noznice")
print("Vzdy napise len jedno slovo: kamen, papier alebo noznice")
# score
your_score = 0
# game cycle
while True:
if your_score == -1:
print("Koniec hry, prehral si! ---> Tvoje score: " + str(your_score))
break
print("#########")
print("Score: " + str(your_score), end='\n')
print("#########")
print("Tvoja volba:", end=' ')
your_turn = input().lower()
# computer
computer_turn = [ "kamen", "papier", "noznice" ]
computer_turn = random.choice(computer_turn)
print("Super vybral: " + computer_turn)
#main logic
#kamen
if "kamen" == your_turn or "papier" == your_turn or "noznice" == your_turn:
if your_turn == "kamen":
if your_turn == computer_turn:
print("Remiza!")
elif "kamen" != computer_turn:
if "noznice" == computer_turn:
print("-----> Vyhral si!")
your_score += 1
else:
print("!!!--> Prehral si!")
your_score -= 1
# papier
if your_turn == "papier":
if your_turn == computer_turn:
print("Remiza!")
elif "papier" != computer_turn:
if "kamen" == computer_turn:
print("-----> Vyhral si!")
your_score += 1
else:
print("!!!--> Prehral si!")
your_score -= 1
#noznice
if your_turn == "noznice":
if your_turn == computer_turn:
print("Remiza!")
elif "noznice" != computer_turn:
if "papier" == computer_turn:
print("-----> Vyhral si!")
your_score += 1
else:
print("!!!--> Prehral si!")
your_score -= 1
else:
print("---->> !! Neplatna hodnota: " + str(your_turn))
| false |
62d58174a8ded907a52059b474528397a55d694d | dlx24x7/Automate_boring_stuff_w_Python | /vampire.py | 348 | 4.21875 | 4 | # this code teaches you how to program
# Its a great way to learn coding
name = 'sam'
age = 2001
print(age)
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age > 100:
print('You are not Alice, grannie.')
| true |
8518c2915a015826ba851b3f509e9b323d6d7bd5 | bgoldstone/Computer_Science_I | /Labs/5_factorial.py | 444 | 4.3125 | 4 | # 5_factorial.py
# A program that asks the user for input and tells user what that numbers factorial is
# Date: 9/22/2020
# Name: Ben Goldstone
num = 0
while num >= 0:
num = int(input("Enter an integer (negative to quit): "))
factorial = 1
# if negative print a goodbye message
if num < 0:
print("Done!")
else:
for number in range(1, num + 1):
factorial *= number
print(f"{num}! = {factorial}")
| true |
d53451899b3bc1a4dc06537a2be24b93bf2a1ec4 | syth3/Teaching-Tech-Topics | /Python/Loops/break_keyword.py | 335 | 4.21875 | 4 | print("Break Keyword with a while loop")
counter = 0
while counter < 10:
counter += 1
if counter == 3:
print("Exit the loop entirely")
break
print(counter)
print()
print("Break Keyword with a for loop")
for i in range(10):
if i == 5:
print("Exit the loop entirely")
break
print(i)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.