blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ed1decde6fc97b53b1ab2026b61be047f22125ca | rajeshsvv/Lenovo_Back | /1 PYTHON/9 PYTHON PROGRAMS/PYTHON PROGRAMS NOUS/1_Dataflair/Beginner/4_tuple_functions.py | 1,416 | 4.28125 | 4 | # Python Tuples Packing
b=1,2.0,"three",
x,y,z=b
print(b)
print(type(b))
percentages=(99,95,90,89,93,96)
a,b,c,d,e,f=percentages
# print(a,b,d,e,f,c)
# print(type(percentages))
# print(percentages[1])
# print(percentages[2:-1])
# print(percentages)
# print(percentages[:-2])
# print(percentages[2:-3])
# print(percentages[:])
# del percentages[:2] tuple does not support item deletion
# print(percentages)
# del percentages
# print(percentages)
# percentages[3]=9 tuple does not support item assignment
# print(percentages)
# 13. Built-in List Functions
#A lot of functions that work on lists work on tuples too.
# A function applies on a construct and returns a result. It does not modify the construct
# sum() max() min() any()
# all() tuple() sorted() len()
h=max(('Hi','hi','Hello'))
print(h)
# b=max(('Hi', 9)) # not supported between instances of 'int' and 'str'
# print(b)
a=any(('','0','')) #If even one item in the tuple has a Boolean value of True, then this function returns True
print(a)
b=any(('',0,'')) #The string ‘0’ does have a Boolean value of True. If it was rather the integer 0
print(b)
#
# list=[1,2,3,4,5,6]
# print(tuple(list))
#
string1="string"
print(tuple(string1))
#
# set1={2,1,3}
# print(tuple(set1))
# print(set1)
# | true |
3e1029de5c6d8dd891f5b0265d6f9bd28a2ee562 | rajeshsvv/Lenovo_Back | /1 PYTHON/7 PROGRAMMING KNOWLEDGE/11_If_else_if.py | 603 | 4.125 | 4 |
'''
x=100
if x!=100:
print("x value is=",x)
else:
print("you entered wrong value")
'''
'''
x=100
if x==100:
print("x is =")
print(x)
if x>0:
print("x is positive")
else:
print("finish")
'''
name=input("Enter Name:")
if name=="Arjun":
print("The Name is",name)
elif name=="Ashok":
print("The Name is",name)
elif name=="Shankar":
print("The Name is",name)
else:
print("Name Entered was wrong")
'''
x=10
if x>0:
print("x is positive")
if (x % 2 == 0):
print("x is even")
else:
print("x is odd")
else:
print("x is negative")
''' | true |
4ee34cde27b1028f5965db21d5adcd3311859a62 | rajeshsvv/Lenovo_Back | /1 PYTHON/2 COREY SCHAFER/PART 1/25_File Objects Reading and Writing.py | 2,058 | 4.59375 | 5 | # File Object How to read and write File in Python using COntext manager
# Reading(r) Writing(w) Appending(a) or Reading and Writing(r+) Operations on File Default is Reading if we dont mention anything
# context manager use is no need to mention the close the file it automatically take care about that.
# with open("text File.txt", "r") as f:
# pass
# print(f.closed)
with open("text File.txt", "r") as f:
f_content = f.read()
f_content = f.read(100)
print(f_content, end="")
# f_content = f.read(100)
# print(f_content, end="")
# f_content = f.readlines()
# f_content = f.readline()
# print(f_content, end="")
# f_content = f.readline()
# print(f_content, end="")
# for line in f:
# print(line, end="")
# print(f.closed) #no need to mention this line when we are in context manager it will take care of that
# print(f.read()) #IO operation on closed file error it gets
# size_to_read = 10
# f_contents = f.read(size_to_read)
# print(f_contents, end="")
# f.seek(0)
# f_contents = f.read(size_to_read)
# print(f_contents)
# print(f.tell())
# while len(f_contents) > 0:
# print(f_contents, end="*")
# f_contents = f.read(size_to_read)
# f.write("test")
# with open("text2.txt", "w") as f:
# # pass # pass in the sense dont do anything rightnow with this function use it later otherwise no error k
# f.write("Test")
# f.seek(0)
# f.write("R")
# read and write operations
# with open("text File.txt", "r") as rf:
# with open("text_copy.txt", "w") as wf:
# for line in rf:
# wf.write(line)
# for pics purpose we use rb and wb because pics are in string mode its not work actually
# we havee to convert in binary mode so for that we use rb and wb
# with open("Nazria.jpg", "rb") as rf:
# with open("Nazria_1.jpg", "wb") as wf:
# # for line in rf:
# # wf.write(line)
# chunk_size = 4096
# rf_chunk = rf.read(chunk_size)
# while len(rf_chunk) > 0:
# wf.write(rf_chunk)
# rf_chunk = rf.read(chunk_size)
| true |
1c068daa9bc712bd4ce6d49ed728da8666c080a9 | rajeshsvv/Lenovo_Back | /1 PYTHON/3 TELUSKO/42_Filter_Map_Reduce.py | 1,155 | 4.34375 | 4 | # program to find even numbers in the list with basic function
# def is_even(a):
# return a%2==0
#
# nums=[2,3,4,5,6,8,9]
#
# evens=list(filter(is_even,nums))
# print(evens)
# program to find even numbers in the list with lambda function
# nums=[2,3,4,5,6,8,9]
#
# evens=list(filter(lambda n:n%2==0,nums))
# print(evens)
# # program to double the numbers in the list with normal function
#
# def update(a):
# return a*2
# nums=[2,3,4,5,6,8,9]
# evens=list(filter(lambda n:n%2==0,nums))
# doubles=list(map(update,evens))
# print(evens)
# print(doubles)
# program to double the numbers in the list with lambda function
# nums=[2,3,4,5,6,8,9]
# evens=list(filter(lambda n:n%2==0,nums))
# doubles=list(map(lambda n:n*2,evens))
# print(evens)
# print(doubles)
# program to add two numbers in the list in the list with reduce function
from functools import reduce
# def Add_All(a,b):
# return a+b
nums=[2,3,4,5,6,8,9]
evens=list(filter(lambda n:n%2==0,nums))
doubles=list(map(lambda n:n*2,evens))
# sum=reduce(Add_All,doubles)
sum=reduce(lambda a,b:a+b,doubles) # with lambda function
print(evens)
print(doubles)
print(sum) | true |
0d88ba61da25a2c6cbec00a3b2df6a25a339d8e0 | rajeshsvv/Lenovo_Back | /1 PYTHON/3 TELUSKO/12_operators.py | 327 | 4.125 | 4 | # Assignment Operators:
x = 2
x += 3
print(x)
x *= 5
print(x)
x /= 5
print(x)
a, b, c = 1, 5, 6.3
print(a, b)
# Unary Operator
n = 4
n = -n
print(n)
# Relational Operators
a = 20
b = 20.1
print(a == b)
print(a != b)
# Logical Operators
a, v = 3, 9
print(a < 5 and v < 10)
print(a < 5 or v < 10)
print(not a)
print(not v)
| false |
efd5cdb227947d02ae194e4c1100bfbf1f8097db | rajeshsvv/Lenovo_Back | /1 PYTHON/7 PROGRAMMING KNOWLEDGE/45_Python_Generator.py | 1,064 | 4.125 | 4 | '''
def my_func():
yield "a"
yield "b"
yield "c"
yield "d"
x=my_func()
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x)) # this is extra print statement it raises stop iteration exception.
#using for loop we did not stopiteration exception.
# for i in x:
# print(i)
'''
'''
def func():
n=1
print("--------------------",n)
yield n
print("-----------------",n)
n+=1
yield n
print("----------------",n)
n+=1
yield n
print("----------------", n)
x=func()
print(next(x))
print(next(x))
print(next(x))
'''
'''
def my_func():
for i in range(6):
print("----------",i)
yield i
x=my_func()
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
'''
def list_generator(list):
for i in list:
yield i
a=[1,2,3,4,5,6]
x=list_generator(a)
# print(next(x))
# print(next(x))
# print(next(x))
# print(next(x))
# print(next(x))
# print(next(x))
# print(next(x))
for i in x:
print(i) | false |
3c0c21e334d161aa174acd2875a8b8bf9afdc56d | rajeshsvv/Lenovo_Back | /1 PYTHON/2 COREY SCHAFER/PART 1/4.2_Sets.py | 689 | 4.25 | 4 | # sets
are unorder list of items and no duplicates in it means it throws the duplicate values and in output it gives unique values k
#strange when we execute each time set its output order will be change strnage right
cs_courses={"History","Math","Physics","ComputerScience"}
print(cs_courses)
cs_courses={"History","Math","Physics","ComputerScience","ComputerScience","Physics"}
print(cs_courses)
print("Math" in cs_courses) ; print("Path" in cs_courses);
cs_courses={"History","Math","Physics","ComputerScience"}
art_courses={"History","Math","Art","Design"}
print(cs_courses.intersection(art_courses))
print(cs_courses.difference(art_courses))
print(cs_courses.union(art_courses))
| true |
f6e317ef55d8b358a5b2a97a8366375d876d1afd | rajeshsvv/Lenovo_Back | /1 PYTHON/2 COREY SCHAFER/PART 2/33_Generators.py | 1,324 | 4.5 | 4 | # Generators have advantages over Lists
# Actual way to find the square root of the numbers
# def sqaure_numbers(nums):
# result = []
# for i in nums:
# result.append(i * i)
# return result
# my_numbers = sqaure_numbers([1, 2, 3, 4, 5])
# print(my_numbers)
# through Generator we can find the square root of the numbers
# Generators don't hold entire list in memory it gives one by one result
# def sqaure_numbers(nums):
# for i in nums:
# yield(i * i)
# my_numbers = sqaure_numbers([1, 2, 3, 4, 5])
# print(my_numbers) # it generates object instead of ressult
# # print(next(my_numbers)) #
# # print(next(my_numbers))
# # print(next(my_numbers))
# # print(next(my_numbers))
# # print(next(my_numbers))
# # instead of use next keyword create for loop so it will give line by line output
# for num in my_numbers:
# print(num)
# simplify the above code in list comprehension way k
# my_numbers = [i * i for i in [1, 2, 3, 4, 5]] # list comprehension way u will get print(my_numbers) result also
# print(my_numbers)
my_numbers = (i * i for i in [1, 2, 3, 4, 5]) # list comprehension way for generatos.u dont get print(my_numbers) result here.for loop requird
print(list(my_numbers)) # if we add list to my numbers then no need of for loop we get result k
| true |
fea628a45ae7f13a0b7fcf46dec0a17cea59ec74 | rajeshsvv/Lenovo_Back | /1 PYTHON/9 PYTHON PROGRAMS/PYTHON PROGRAMS NOUS/Techbeamers/ds tuples techbeam2.py | 1,397 | 4.3125 | 4 | # https://www.techbeamers.com/python-programming-questions-list-tuple-dictionary/
# Tuples
'''
init_tuple = (1,.2,3)
print(init_tuple.__len__()) # answer:0
'''
"""
init_tuple_a = 'a', 'b',
init_tuple_b = ('a', 'b')
print (init_tuple_a == init_tuple_b) # answer:True
"""
'''
init_tuple_a = '1', '2'
init_tuple_b = ('3', '4')
print (init_tuple_a + init_tuple_b) # answer:('1', '2', '3', '4')
'''
'''
init_tuple_a = [1, 2]
init_tuple_b = [3, 4]
[print(sum(x)) for x in [init_tuple_a + init_tuple_b]] # answer:10
'''
'''
init_tuple = [(0, 1), (1, 2), (2, 3)]
result = sum(n for _,n in init_tuple)
print(result) # answer:6
'''
'''
Tuples have structure, lists have an order
Tuples are immutable, lists are mutable.
'''
'''
l = [1, 2, 3]
init_tuple = ('Python',) * (l.__len__() - l[::-1][0])
print(init_tuple) # answer: ()
'''
'''
init_tuple = ('Python') * 0
print(type(init_tuple)) # answer:str
'''
'''
init_tuple = (1,) * 3
init_tuple[0] = 2
print(init_tuple) # answer:tuple object does not support item assignment
'''
'''
init_tuple = ((1, 2),) * 7
print(len(init_tuple[3:8])) # answer:4
''' | false |
9f919efc97f5d420ac4e5fe9bcc7894ae34bb20d | dehvCurtis/Fortnight-Choose-Your-Own-Adventure | /game.py | 754 | 4.1875 | 4 | print ("Welcome to Fortnite - Battle Royal")
#When the gamer first starts the game
print ("Your above Tilted Towers do you jump?.")
print('Do you want to jump')
## raw_input gets input from the user
## Here, we take the input, and *assign* it to a variable called 'ans'
answer = input("please type yes or no ")
## conditionals
## see if the user's answer is interesting or not
if answer=="yes":
print ("That was foolish! You are now dead.")
## elif means "else-if"
elif answer == "no":
print ("That was wise! You are alive, but thoroughly bored.")
## else is a 'catch-all' for "any condition not all ready covered"
else:
print ("I don't know what to do, based on what you said, which was, |", ans, "|")
print ("Thank you for playing!")
| true |
0afd492ae8246c953c088cf735ae1a525d2d49b9 | sidneyalex/Desafios-do-Curso | /Desafio075.py | 756 | 4.125 | 4 | #Desenvolva um pgm que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:
#A)Quantas vezes apareceu o numero 9.
#B)Em que posição foi digitado o primeiro 3.
#C)Quais foram os numeros pares.
print(f'O Programa coleta 4 numeros inteiros e os guarda em uma tupla.')
num = (int(input('1º numero: ')),
int(input('2º numero: ')),
int(input('3º numero: ')),
int(input('4º numero: ')))
print(f'Os Valores digitados foram: {num}')
print(f'O numero 9 aparece {num.count(9)} vezes')
if 3 in num:
print(f'O primeiro 3 foi digitado na posição {num.index(3) + 1}')
else:
print('O numero 3 não foi digitado.')
print(f'Os numeros pares digitados: ', end='')
for c in num:
if c % 2 == 0:
print(c, end=' ')
| false |
2122beb8f83cb24f1c617d9fb388abdf42becd63 | Laurentlsb/Leetcode | /leetcode/editor/en/[101]Symmetric Tree.py | 2,992 | 4.375 | 4 | #Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
#
# For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
#
#
# 1
# / \
# 2 2
# / \ / \
#3 4 4 3
#
#
#
#
# But the following [1,2,2,null,3,null,3] is not:
#
#
# 1
# / \
# 2 2
# \ \
# 3 3
#
#
#
#
# Note:
#Bonus points if you could solve it both recursively and iteratively.
# Related Topics Tree Depth-first Search Breadth-first Search
#leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# # iteration
# class Solution:
# def isSymmetric(self, root: TreeNode) -> bool:
# if not root:
# return True
# left_stack = [root]
# right_stack = [root]
# while left_stack and right_stack:
# node_left = left_stack.pop()
# node_right = right_stack.pop()
# if (node_left is None and node_right is not None) or (node_left is not None and node_right is None):
# return False
# elif node_left is None and node_right is None:
# pass
#
# if node_left and node_right:
# if node_left.val != node_right.val:
# return False
# else:
# left_stack.append(node_left.right)
# left_stack.append(node_left.left)
# right_stack.append(node_right.left)
# right_stack.append(node_right.right)
# return True
# recursion
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root is None:
return True
return self.check(root.left, root.right)
def check(self, l, r):
if not l and not r:
return True
elif (not l and r) or (l and not r):
return False
elif l.val != r.val:
return False
else:
return self.check(l.left, r.right) and self.check(l.right, r.left)
# 递归,比较左右最外侧的边缘节点,再依次向内,对称比较(分析一个最简单的三层结构就好)
# class Solution:
# def isSymmetric(self, root: TreeNode) -> bool:
# if root is None:
# return True
#
# if root.left is None and root.right is not None:
# return False
# elif root.left is not None and root.right is None:
# return False
# elif root.left == root.right is None:
# return True
# else:
# if root.left.val != root.right.val:
# return False
# else:
# return self.isSymmetric(root.left) and self.isSymmetric(root.right)
# # wrong idea, since you were checking if the subtree is symmetric
#leetcode submit region end(Prohibit modification and deletion)
| true |
b27939b3a840c30900ec11f6c41372108c8a78d0 | njenga5/python-problems-and-solutions | /Solutions/problem62.py | 224 | 4.46875 | 4 | '''
Question 62:
Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8.
Hints:
Use unicode() function to convert.
'''
word = 'Hello world'
word2 = unicode(word, 'utf-8')
# print(word2)
| true |
b8b8639b7244a36bce240fd61986e799027c1c4e | njenga5/python-problems-and-solutions | /Solutions/problem47.py | 396 | 4.15625 | 4 | '''
Question 47:
Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10].
Hints:
Use map() to generate a list.
Use filter() to filter elements of a list.
Use lambda to define anonymous functions.
'''
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
nums3 = map(lambda x: x**2, filter(lambda x: x % 2 == 0, nums))
print(list(nums3))
| true |
cd526869d4d51b2b674b9335c89ad71efddde994 | njenga5/python-problems-and-solutions | /Solutions/problem59.py | 621 | 4.34375 | 4 | '''
Question 59:
Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only.
Example:
If the following email address is given as input to the program:
john@google.com
Then, the output of the program should be:
google
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
Use \w to match letters.
'''
import re
emails = input(': ')
match = re.search('([a-z]+)@([a-z]+)(\.[a-z]+)', emails)
if match:
print(match.group(2))
| true |
4eac214e15a3d21aef858726865d0e633c8e799d | njenga5/python-problems-and-solutions | /Solutions/problem49.py | 293 | 4.15625 | 4 | '''
Question 49:
Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included).
Hints:
Use map() to generate a list.
Use lambda to define anonymous functions.
'''
nums = [i for i in range(1, 21)]
print(list(map(lambda x: x**2, nums)))
| true |
878e52902b63ed79cd80fd9ceefe909528bc7abd | njenga5/python-problems-and-solutions | /Solutions/problem28.py | 210 | 4.1875 | 4 | '''
Question 28:
Define a function that can convert a integer into a string and print it in console.
Hints:
Use str() to convert a number to string.
'''
def convert(n):
return str(n)
print(convert(5))
| true |
84c639d15de0b7af4d3bcc57c6363de03c15d018 | narendragnv/test | /2_datatypes.py | 937 | 4.25 | 4 | # list == array
# tuple
# dict
## LIST
a = ["somestring", 2, 4.0]
print(a)
b = [2.3, a]
b = [2.3, ["somestring", 2, 4.0]] # same as above line
print(b)
print(2 in a)
print(3 not in a)
print("somestring" in a)
print("string" in a)
a = ["somestring", 2, 4.0]
print(a)
print(a[1])
a[1] = 32 # list is mutable
print(a)
print(a[1])
a.append(40)
print(a)
## TUPLE is immutable
a = ("somestring", 2.0, 564)
a = tuple(("somestring", 2.0, 564))
print(a)
print(a[0])
# a[0] = 123 # ERROR! since tuples are immutable
## DICT
# a = {"key": "value"}
a = {"a": 1, "b": 2}
print(a)
a = {1: "a", 2: "b"}
print(a)
a = {"a": [1, 2, 3], "b": ("12312", 123)}
print(a)
dict1 = {"a": 1, "b": 2}
print(dict1["b"])
print(dict1.keys())
print(dict1.values())
print(dict1.items())
dict1 = {"a": [1, 2, 3], "b": ("12312", 123)}
print(dict1["a"][1])
dict1 = {"a": 1, "b": 2}
dict1["a"] = 100
print(dict1)
dict1 = {"a": 1, "b": 2, "a": 200}
print(dict1)
| false |
62ed099d5b99fafc9fa44d21f696402333524451 | romitheguru/ProjectEuler | /4.py | 821 | 4.125 | 4 | """
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def num_reverse(n):
reverse = 0
while n:
r = n % 10
n = n // 10
reverse = reverse * 10 + r
return reverse
def is_palindrome(n):
reverse = num_reverse(n)
return (n == reverse)
def solve():
large = 0
combination = None
for i in range(999, 99, -1):
for j in range(999, 99, -1):
num = i * j
if is_palindrome(num) and num > large:
large = num
combination = (i, j)
print(combination)
return large
def main():
print(solve())
if __name__ == '__main__':
main()
| true |
230f3b9c7735deadb877274b1dfc9c6203f407c7 | umahato/pythonDemos | /4_MethodAndFunctions/7_argsAndKwargs.py | 1,279 | 4.1875 | 4 | '''
def myfunc(a,b):
#Return 5% of the sum of a and b
return sum((a,b)) * 0.05
print(myfunc(40,60))
def myfunc(*args):
return sum(args) * 0.05
print(myfunc(34,53,53))
def myfunc (**kwargs):
print(kwargs)
if 'fruit' in kwargs:
print('My fruit of choise is {}'.format(kwargs['fruit']))
else:
print('I did not find any fruit here')
print(myfunc(fruit='apple'))
# Define a function called myfunc that takes in an arbitrary number of arguments, and return a list containing
# only those arguments that are even
def myfunc(*args):
return [x for x in args if x %2 ==0]
print(myfunc(23,33,24,35,66))
'''
# Define a function called myfunc that takes in a string and returns a matching string where every even letter
# is uppercase and every odd letter is lowercase. Assume that the incoming string only contains letters
# and don't worry about numbers , spaces or punctuations. The output string can start with either an
# uppercase letter , so long as letter alternate throughout the string.
def myfunc(val):
st = ''
count = 1
for i in val:
if count%2 ==0:
st = st + i.upper()
else:
st = st + i.lower()
count = count + 1
return st
print(myfunc('hello'))
| true |
cf4bf78e08205d21f77080dc552247a94a3283e4 | umahato/pythonDemos | /3_PythonStatements/3_whileLoops.py | 909 | 4.375 | 4 | # While loops will continue to execute a block of code while some condition remain true.
# For example , while my pool is not full , keep filling my pool with water.
# Or While my dogs are still hungry, keep feeding my dogs.
'''
x = 0
while x < 5:
print(f'The current value of x is {x}')
#x = x +1
x += 1
else:
print('X is not less than 5')
'''
# Break , Continue and Pass
# We can use break, continue and pass statements in our loops to add additional functionality for various cases.
# The three statements are defined by:
# break: Breaks out of the current closest enclosing loop.
# continue: Goes to the top of the closest enclosing loop.
# pass: Does nothing at all.
'''
x = [1,2,3]
for item in x:
pass
print('end of my script')
'''
mystring = 'Sammy'
for letter in mystring:
if letter == 'a':
break # can be use break or continue
print(letter)
| true |
b7f0c53ae0215250ecf91d5f59489c8fd1f8793c | SilviaVazSua/Python | /Basics/coding_life.py | 376 | 4.15625 | 4 | # a program about something in real life :D
number_of_stairs_1_2 = int(input("Tell me how many stairs from floor 1 to floor 2, please: "))
floor = int(input("In which floor you live? "))
total_stairs = number_of_stairs_1_2 * floor
print("Then, if the elevator doesn\'t work, you will have ", total_stairs, "until your home! Maybe you want to stay at a friend's home! :D")
| true |
247b7c1a9aba17644415a90f117b4d327e3f332d | SilviaVazSua/Python | /Basics/leap_years.py | 719 | 4.25 | 4 | # This program asks for a starting year and an ending year and then puts all the leap years between them (and including them, if they are also leap years). Leap years are years divisible by 4 (like 1984 and 2004). However, years divisible by 100 are not leap years (such as 1800 and 1900) unless they are also divisible by 400 (such as 1600 and 2000, which were in fact leap years).
start_date = int(input("Tell me a start date, please: "))
end_date = int(input("Tell me a end date, please: "))
end_date2 = end_date + 1
print("The leap years between these two dates (including them) are:")
for dates in range (start_date, end_date2):
if dates % 4 == 0:
print (dates)
print("Yes, I know, I'm pretty smart! :D")
| true |
43c40e8eb46f891023aea282aa8fff1e081581fc | razvanalex30/Exercitiul3 | /test_input_old.py | 1,138 | 4.21875 | 4 | print("Hi! Please choose 1 of these 3 inputs")
print("1 - Random joke, 2 - 10 Random jokes, 3 - Random jokes by type")
while True:
try:
inputus = int(input("Enter your choice: "))
if inputus == 1:
print("You have chosen a random joke!")
break
elif inputus == 2:
print("You have chosen 10 Random Jokes!")
break
elif inputus == 3:
types = ["general","programming","knock-knock"]
numbers = [1, 10]
typee = None
number = None
while typee not in types:
typee = str(input("Please choose a type: "))
if typee in types:
break
else:
print("Try again!")
print("Your type chosen was {}".format(typee))
while number not in numbers:
number = int(input("Please choose the number of jokes: "))
if number in numbers:
break
else:
print("Try again!")
print("Here are your jokes!")
break
print("Please enter a valid number!\n")
except Exception:
print("Please choose a valid input\n") | true |
a70be84406ab8fdf4944f6030533fbda0297b11e | ashishp0894/CS50 | /Test folder/Classes.py | 910 | 4.125 | 4 | """class point(): #Create a new class of type point
def __init__(self,x_coord,y_coord): #initialize values of class
self.x = x_coord
self.y = y_coord
p = point(10,20)
q = point (30,22)
print(f"{p.x},{p.y} ")
"""
class flight():
def __init__(self,capacity):
self.capacity = capacity
self.passengers = []
def add_passenger (self,Passenger_name): #New function created inside class
if not self.open_seats():
return False
else:
self.passengers.append(Passenger_name)
return True
def open_seats(self):
return self.capacity - len(self.passengers)
f90 = flight(3)
people = ["Harry","Ron","Hermoine","Ginnie"]
for person in people:
success = f90.add_passenger("person")
if success:
print(f"Added {person} successfully")
else:
print(f"Unable to add {person} successfully")
| true |
eec8d6944bf8b9bf6eeaa515fd1ca7a8e0896328 | ashishp0894/CS50 | /Test folder/Conditions.py | 213 | 4.125 | 4 | Number_to_test = int(input("Number"))
if Number_to_test>0:
print(f"{Number_to_test} is Positive")
elif Number_to_test<0:
print (f"{Number_to_test} is Negative")
else:
print(f"{Number_to_test} is Zero") | false |
23f6a8643e06ed18a73c9bf1519b9719e0a3283c | christophe12/RaspberryPython | /codeSamples/fileManipulation/functions.py | 933 | 4.25 | 4 | #----handy functions----
#The os() function
#os.chdir('directory_name') -> changes your present working directory to directory_name
#os.getcwd() -> provides the present working directory's absolute directory reference
#os.listdir('directory_name') -> provides the files and subdirectories located in directory_name. if no directory_name is provided, it returns the files and subdirectories located in the present working directory.
#os.mkdir('directory_name') -> creates a new directory
#os.remove('file_name') -> deletes file_name from your present working directory. it will not remove directories or subdirectories. There are no "Are you sure?" questions provided.
#os.rename('from_file', 'to_file') -> renames a file from the name from_file to the name to_file in your present working directory.
#os.rmdir('directory_name') -> deletes the directory directory_name. it will not delete the directory if it contains any files.
| true |
ff0e7cbbf0cff9dd00e60a14d1382e52aac4331f | SuryakantKumar/Data-Structures-Algorithms | /Functions/Check_Prime.py | 554 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 24 05:36:47 2019
@author: suryakantkumar
"""
'''
Problem : Write a function to check whether the number N is prime or not.
Sample Input 1 :
5
Sample output 1 :
prime
Sample input 2 :
4
Sample output 2:
Not Prime
'''
def IsPrime(n):
if n < 2:
return False
d = 2
while d < n:
if n % d == 0:
return False
d += 1
return True
n = int(input())
result = IsPrime(n)
if result:
print('prime')
else:
print('Not Prime') | true |
1c4ccd633778efae1e6d402385ff2eb10a509c91 | SuryakantKumar/Data-Structures-Algorithms | /Exception Handling/Else-And-Finally-Block.py | 1,101 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 7 14:42:20 2020
@author: suryakantkumar
"""
while True:
try:
numerator = int(input('Enter numerator : '))
denominator = int(input('Enter denominator : '))
division = numerator / denominator
except ValueError: # handling ValueError exception explicitly
print('Numerator and denominator should be integers')
except ZeroDivisionError: # handling ZeroDivisionError exception explicitly
print('Denominator should not bee zero')
except (ValueError, ZeroDivisionError): # Handling multiple exceptions at a time
print('Numerator and denominator should be integers and Denominator should not bee zero')
except:
print('Another exception has been raised')
else: # Else will execute when no any exception will be raised
print(division)
break
finally: # Finally block will execute whether exception will be raised or not
print('Exception raised or not')
| true |
649b45e5fb2fe8b50542cbab310a8cc2d22b511d | SuryakantKumar/Data-Structures-Algorithms | /Miscellaneous Problems/Chessboard-Game.py | 629 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 13:32:07 2020
@author: suryakantkumar
"""
from functools import lru_cache
@lru_cache
def chessboardGame(x, y):
print(x, y)
if x <= 2 or y <= 2:
return 'Second'
if chessboardGame(x - 2, y + 1) == True or chessboardGame(x - 2, y - 1) == True or chessboardGame(x + 1, y - 2) == True or chessboardGame(x - 1, y - 2) == True:
return 'Second'
else:
return 'First'
if __name__ == '__main__':
xy = input().split()
x = int(xy[0])
y = int(xy[1])
result = chessboardGame(x, y)
print(result) | false |
b895e3cd708cd102baaf7f4126f4d1a13c32e889 | SuryakantKumar/Data-Structures-Algorithms | /Object Oriented Programming/Class-Method.py | 1,374 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 6 06:20:20 2020
@author: suryakantkumar
"""
from datetime import date
class Student:
def __init__(self, name, age, percentage = 80): # Init method
self.name = name
self.age = age
self.percentage = percentage
@classmethod # Class method are factory methods which returns object of the class specified
def FromBirthYear(cls, name, year, percentage):
return cls(name, date.today().year - year, percentage) # class method returns object of the class
def StudentDetails(self):
print('name :', self.name)
print('age :', self.age)
print('percentage :', self.percentage)
def IsPassed(self):
if self.percentage > 40:
print(self.name, 'is passed')
else:
print(self.name, 'is not passed')
@staticmethod
def WelcomeToSchool():
print('Welcome to School')
@staticmethod
def IsTeen(age): # Static methods are used as utility functions, used to check some functionalities
return age >= 16
s = Student('Suryakant', 21, 90)
s.StudentDetails()
print()
s1 = Student.FromBirthYear('shashikant', 2000, 70) # Object creation from class method
s1.StudentDetails()
| true |
0beb688b4af8803550204cf01f8879b8f327050e | SuryakantKumar/Data-Structures-Algorithms | /Functions/Fahrenheit_To_Celcius.py | 878 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 24 07:44:35 2019
@author: suryakantkumar
"""
'''
Problem : Given three values - Start Fahrenheit Value (S), End Fahrenheit value (E) and Step Size (W), you need to convert all Fahrenheit values from Start to End at the gap of W, into their corresponding Celsius values and print the table.
Input Format : 3 integers - S, E and W respectively
Output Format : Fahrenheit to Celsius conversion table. One line for every Fahrenheit and Celsius Fahrenheit value.
Fahrenheit value and its corresponding Celsius value should be separate by tab ("\t")
Sample Input :
0
100
20
Sample Output :
0 -17
20 -6
40 4
60 15
80 26
100 37
'''
s = int(input())
e = int(input())
w = int(input())
def f2c(s, e, w):
for s in range(s, e+1, w):
c = int((s-32)*5/9)
print(s, '\t', c)
f2c(s, e, w) | true |
2450c7cccafa7d66157ef16b35ced3b903ee0b60 | SuryakantKumar/Data-Structures-Algorithms | /Searching & Sorting/Insertion-Sort.py | 1,120 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 1 08:42:58 2020
@author: suryakantkumar
"""
'''
Problem : Given a random integer array. Sort this array using insertion sort.
Change in the input array itself. You don't need to return or print elements.
Input format : Line 1 : Integer N, Array Size
Line 2 : Array elements (separated by space)
Constraints : 1 <= N <= 10^3
Sample Input 1:
7
2 13 4 1 3 6 28
Sample Output 1:
1 2 3 4 6 13 28
Sample Input 2:
5
9 3 6 2 0
Sample Output 2:
0 2 3 6 9
'''
def InsertionSort(n, li):
for i in range(1, n):
consider = li[i] # Choose one element
j = i - 1 # Last index of sorted lements
while j >= 0 and li[j] > consider: # Compare considered element with sorted elements in reverse
li[j+1] = li[j] # Shift element one index right
j = j - 1
li[j+1] = consider # Put considered element on right position
n = int(input())
li = [int(x) for x in input().strip().split()]
InsertionSort(n, li)
print(*li) | true |
574b565c7bc5fecb11693ef0b7e7687437ae429d | SuryakantKumar/Data-Structures-Algorithms | /Miscellaneous Problems/Bishop-Move.py | 1,112 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 11:57:07 2020
@author: suryakantkumar
"""
'''
Find out number of positions on chess where bishop can attack.
Bishop position is given as (x, y) coordinates and chess dimension is n * n.
'''
def bishopMove(chess, position):
count = 0
x, y = position
while x >= 1 and y >= 1:
x = x - 1
y = y - 1
if x >= 1 and y >= 1:
count += 1
x, y = position
while x <= n and y >= 1:
x = x + 1
y = y - 1
if x <= n and y >= 1:
count += 1
x, y = position
while x >= 1 and y <= n:
x = x - 1
y = y + 1
if x >= 1 and y <= n:
count += 1
x, y = position
while x <= n and y <= n:
x = x + 1
y = y + 1
if x <= n and y <= n:
count += 1
return count
n = int(input())
x = int(input())
y = int(input())
position = (x, y)
chess = [[[i, j] for j in range(1, n+1) ]for i in range(1, n+1)]
result = bishopMove(chess, position)
print(result) | false |
b50a873c8d0d45fd4ebac22fdeaa92097cdea731 | rakshithsingh55/Clg_project | /FoodSearch/webapp/test.py | 550 | 4.5 | 4 | # Python3 code to demonstrate working of
# Common words among tuple strings
# Using join() + set() + & operator + split()
# Initializing tuple
test_tup = ('gfg is best', 'gfg is for geeks', 'gfg is for all')
# printing original tuple
print("The original tuple is : " + str(test_tup))
# Common words among tuple strings
# Using join() + set() + & operator + split()
res = ", ".join(sorted(set(test_tup[0].split()) & set(test_tup[1].split()) & set(test_tup[2].split())))
# printing result
print("Common words among tuple are : " + res)
| true |
20ce051e440910c78ca5b3c409ff8ebb566520c0 | am3030/IPT | /data/HW5/hw5_182.py | 1,171 | 4.28125 | 4 | def main():
num1 = int(input("Please enter the width of the box: "))
num2 = int(input("Please enter the height of the box: "))
symbol1 = input("Please enter a symbol for the box outline: ")
symbol2 = input("Please enter a symbol for the box fill: ")
boxTop = ""
insideBox = ""
for i in range(num1): # This loop constructs the top and bottom of the box
boxTop = boxTop + symbol1
for n in range(num2 + 1): # This loop ensures the box does not exceed
if n == 1 or n == num2: # This if statement prints out the top and
print(boxTop)
elif n < num2 and n > 1: # This if statement defines how and when the
insideBox = "" # Resets the inside of the box so that the length is
for j in range(num1 + 1): # This loop creates the inside of the box
if j == 1 or j == num1: # This if statement sets when the
insideBox = insideBox + symbol1
elif j < num1 and j > 1: # This if statement sets when the
insideBox = insideBox + symbol2
print(insideBox) # prints the inside of the box for the user
main()
| true |
5de5d8d3bedb628d5dfd81a6d4f1df396678c98c | am3030/IPT | /data/HW5/hw5_453.py | 747 | 4.3125 | 4 |
def main():
width = int(input("Please enter the width of the box: ")) # Prompt user for the width of the box
height = int(input("Please enter the height of the box: ")) # Prompt user for the height of the box
outline = input("Please enter a symbol for the box outline: ") # Prompt user for the symbol that will make up the box's outline
fill = input("Please enter a symbol for the box fill: ") # Prompt user for the content that will fill the interior of the box
BUFFER = 2 # When creating the fill for the box, set this much aside for the border
for i in range(height):
print((outline + fill * (width-BUFFER) + (outline if width > 1 else "")) if i not in [0, height-1] else outline * width) # Print the box
main() | true |
7c2eb614d8ed545815425e6181dc9b77cd285d16 | am3030/IPT | /data/HW4/hw4_340.py | 451 | 4.21875 | 4 |
flavorText = "Hail is currently at height"
def main():
height = 0 # 0 is not a valid input because it is not "positive"
while height < 1:
height = int(input("Please enter the starting height of the hailstone: "))
while height != 1:
print(flavorText, height)
if (height % 2) == 0:
height //= 2
else:
height = (height * 3) + 1
print("Hail stopped at height", height)
main()
| true |
203e316cac71640f97fb1cc26ecf2eac7d3e76ae | matheusb432/hello-world | /Learning Python/loops2.py | 1,060 | 4.1875 | 4 | car_started = False
while True:
command = input('>')
if command.lower() == 'start': # Utilizando o metodo lower() para tornar o input case insensitive
if car_started: # Mesmo que if car_started == True:
print('The car is already started!')
else:
print('Car started... Ready to go!')
car_started = True
elif command.lower() == 'stop':
if not car_started: # Mesmo que if car_started == False:
print('The car is already stopped!')
else:
print('Car stopped')
car_started = False
elif command.lower() == 'quit':
break
elif command.lower() == 'help':
print("""
start - to start the car
stop - to stop the car
quit - to exit
""") # String de multiplas linhas, utilizandos aspas triplas """ """, note que o espacamento normal do elif nao eh necessario, e se houver, ira aparecer espacado no output.
else:
print("What") | false |
853882de1ef0c0ac6ddc0c41cbfd480fdcaabfef | agatakaraskiewicz/magic-pencil | /eveningsWithPython/stonePaperScissorsGame.py | 1,229 | 4.1875 | 4 | from random import randint
"""
1 - Paper
2 - Stone
3 - Scissors
1 beats 2
2 beats 3
3 beats 1
"""
points = 0
userPoints = 0
howManyWins = int(input('How many wins?'))
def userWins(currentUserScore):
print(f'You won!')
return currentUserScore + 1
def compWins(currentCompScore):
print(f'You loose!')
return currentCompScore + 1
#1. Create some randomized number (1,3), which will be the comp attack
#3. Compare the created values and decide, who won
while points < howManyWins and userPoints < howManyWins:
userAttack = int(input('What is your attack? Input 1 for Paper, 2 for Stone or 3 for Scissors'))
attack = randint(1,3)
if userAttack == attack:
print (f'Tie! No one gets the point!')
continue
elif userAttack == 1:
if attack == 2:
userPoints = userWins(userPoints)
else:
points = compWins(points)
elif userAttack == 2:
if attack == 3:
userPoints = userWins(userPoints)
else:
points = compWins(points)
elif userAttack == 3:
if attack == 1:
userPoints = userWins(userPoints)
else:
points = compWins(points)
else:
print('You were supposed to provide 1-3 number... Try again')
if points > userPoints:
print('Computer won the battle!')
else:
print('You won the battle!')
| true |
1fe6cd8e407ae44133b561e4c885bc0ef4904560 | kaceyabbott/intro-python | /while_loop.py | 489 | 4.28125 | 4 | """
Learn conditional repetition
two loops: for loops and while loops
"""
counter = 5
while counter != 0:
print(counter)
# augmented operators
counter -= 1
print("outside while loop")
counter = 5
while counter:
print(counter)
counter -= 1
print("outside while loop")
# run forever
while True:
print("enter a number")
response = input() #take user input
if int(response) % 7 == 0:
break #exit loop
print("outside while loop")
| true |
b5efc5698eac40c55d378f100337a8e52f9936fa | Nihadkp/python | /co1/16_swap_charecter.py | 396 | 4.1875 | 4 | # create a single string seperated with space from two strings by swapping the charecter at position 1
str1 = "apple"
str2 = "orange"
str1_list = list(str1)
str2_list = list(str2)
temp = str1_list[1]
str1_list[1] = str2_list[1]
str2_list[1] = temp
print("Before exchanging elements:", str1, str2)
print("string after exchanging charecter at position 1:", "".join(str1_list), "".join(str2_list))
| true |
65efd951f0153acbaee277e256b3e891376ab64a | Nihadkp/python | /co1/4_occurance_of_words.py | 211 | 4.3125 | 4 | #Count the occurrences of each word in a line of text.
text=input("Enter the line : ")
for i in text.strip().split():
print("Number of occurence of word ","\"",i,"\""," is :",text.strip().split().count(i))
| true |
97b16a9798970f1f2d734ed16a60187ae7f3f7e1 | sudhanthiran/Python_Practice | /Competitive Coding/RegEx matching.py | 1,621 | 4.5625 | 5 | """
Given a pattern string and a test string, Your task is to implement RegEx substring matching.
If the pattern is preceded by a ^, the pattern(excluding the ^) will be matched with
the starting position of the text string. Similarly, if it is preceded by a $, the
pattern(excluding the ^) will be matched with the ending position of the text string.
If no such markers are present, it will be checked whether pattern is a substring of test.
Example :
^coal
coaltar
Result : 1
tar$
coaltar
Result : 1
rat
algorate
Result: 1
abcd
efgh
Result :0
Input: The first line of input contains an integer T denoting the no of test cases.
Then T test cases follow. Each test case contains two lines.
The first line of each test case contains a pattern string.
The second line of each test case consists of a text string.
Output: Corresponding to every test case, print 1 or 0 in a new line.
Constrains:
1<=T<=100
1<=length of the string<=1000
"""
def isSubString(test_string,base_string):
flag = base_string.find(test_string)
if(flag == -1):
return False
else:
return True
def test_for_regex():
test_string = str(input())
base_string = str(input())
flag=False
if (test_string.startswith('^')):
flag = (test_string[1:] == base_string[:len(test_string)-1])
elif(test_string.endswith('$')):
flag = (test_string[:len(test_string)-1] == base_string[(len(test_string)-1)*-1:])
else:
flag = (isSubString(test_string, base_string))
if(flag==True):
print("1")
else:
print("0")
t = int(input())
for i in range(t):
test_for_regex() | true |
dd5e52323d02710e902a1bb7ca8615a18ecfb258 | RockMurdock/Python-Book-1-Tuples | /zoo.py | 1,703 | 4.46875 | 4 | # Create a tuple named zoo that contains 10 of your favorite animals.
zoo = (
"elephant",
"giraffe",
"hippopotamus",
"monkey",
"otter",
"peacock",
"panther",
"rhino",
"alligator",
"lama"
)
# Find one of your animals using the tuple.index(value) syntax on the tuple.
print(zoo.index("hippopotamus"))
# Determine if an animal is in your tuple by using value in tuple syntax.
animal_to_find = "hippopotamus"
if animal_to_find in zoo:
print(f"We found the {animal_to_find}")
# You can reverse engineer (unpack) a tuple into another tuple with the following syntax.
"""
children = ("Sally", "Hansel", "Gretel", "Svetlana")
(first_child, second_child, third_child, fourth_child) = children
print(first_child) # Output is "Sally"
print(second_child) # Output is "Hansel"
print(third_child) # Output is "Gretel"
print(fourth_child) # Output is "Svetlana"
"""
# Create a variable for the animals in your zoo tuple, and print them to the console.
(
first_animal,
second_animal,
third_animal,
fourth_animal,
fifth_animal,
sixth_animal,
seventh_animal,
eighth_animal,
ninth_animal,
tenth_animal
) = zoo
print(first_animal)
print(second_animal)
print(third_animal)
print(fourth_animal)
print(fifth_animal)
print(sixth_animal)
print(seventh_animal)
print(eighth_animal)
print(ninth_animal)
print(tenth_animal)
# Convert your tuple into a list.
zooList = list(zoo)
print(zooList)
# Use extend() to add three more animals to your zoo.
three_animals = ["zebra", "jellyfish", "antelope"]
zooList.extend(three_animals)
print(zooList)
# Convert the list back into a tuple.
zooListToTuple = tuple(zooList)
print(zooListToTuple) | true |
a610e27f93578dff94bf13b4d8c1a213f2997af0 | kmollee/2014_fall_cp | /7/other/isPalindrome.py | 919 | 4.25 | 4 | # palindrome
# remove all white space
# and don;t care about capitalization, all character should be lowercase
# base case
# a string of length 0 or 1 is a palindrome
# recursive case
# if first character matches last character,
# then is a palindrome if middle section is palindrome
# http://www.palindromelist.net/
def isPalindrome(s):
def toChars(s):
s = s.lower()
ans = ''
for c in s:
if c in 'abcdefghijklmnopqrstuvwxyz':
ans += c
return ans
def isPal(s):
if len(s) <= 1:
return True
return s[0] == s[-1] and isPalindrome(s[1:-1])
return isPal(toChars(s))
assert True == isPalindrome('abba')
assert False == isPalindrome('abbac') # should fail
assert True == isPalindrome('A but tuba.')
assert True == isPalindrome('A Santa at Nasa.')
assert True == isPalindrome('A Santa dog lived as a devil God at NASA.')
| false |
c95d54e49c03fc707c8081fb3fa6f67bb27a8046 | kmollee/2014_fall_cp | /7/other/quiz/McNuggets.py | 1,336 | 4.34375 | 4 | '''
McDonald’s sells Chicken McNuggets in packages of 6, 9 or 20 McNuggets. Thus, it is possible, for example, to buy exactly 15 McNuggets (with one package of 6 and a second package of 9), but it is not possible to buy exactly 16 McNuggets, since no non- negative integer combination of 6's, 9's and 20's add up to 16. To determine if it is possible to buy exactly n McNuggets, one has to find non-negative integer (can be 0) values of a, b, and c such that
6a+9b+20c=n
Write a function, called McNuggets that takes one argument, n, and returns True if it is possible to buy a combination of 6, 9 and 20 pack units such that the total number of McNuggets equals n, and otherwise returns False. Hint: use a guess and check approach.
'''
def McNuggets(n):
"""
n is an int
Returns True if some integer combination of 6, 9 and 20 equals n
Otherwise returns False.
"""
# Your Code Here
a = 6
b = 9
c = 20
aRange, bRange, cRange = int(n / a), int(n / b), int(n / b)
isPossible = False
for _a in range(aRange + 1):
for _b in range(bRange + 1):
for _c in range(cRange + 1):
if n == _a * a + _b * b + _c * c:
return True
return isPossible
assert McNuggets(15) == True
assert McNuggets(16) == False
assert McNuggets(32) == True
| true |
deaaf816ff3deab54b62b699d53b417ad3cbb3f1 | MehdiNV/programming-challenges | /challenges/Staircase | 1,216 | 4.34375 | 4 | #!/bin/python3
"""
Problem:
Consider a staircase of size (n=4):
#
##
###
####
Observe that its base and height are both equal to n and the image is drawn using # symbols and spaces.
The last line is not preceded by any spaces.
Write a program that prints a staircase of size n
"""
import math
import os
import random
import re
import sys
# Complete the staircase function below.
# Solution for the Staircase problem
# Author: Mehdi Naderi Varandi
def staircase(n):
stringOutput="#" #String variable used later on to output the # character
spaceCharacters=" "
spacePosition=1
stringOutput=((spaceCharacters*(n-spacePosition)) + "#")
initialCharacter="#"
stringHorziontal=2
spacePosition+=1
for i in range(1,n): #Goes from each level to N e.g. from 1 to 5 (maximum level)
stringOutput += ("\n" + (spaceCharacters*(n-spacePosition))+ (stringHorziontal*initialCharacter))
#Outputs line/# elements equal to the relevant number needed at that specific position
stringHorziontal+=1
spacePosition+=1
print(stringOutput) #Return answer
#End of submission
if __name__ == '__main__':
n = int(input())
staircase(n)
| true |
c957f654ddb5d6c2fa6353ad749a7dbbb151bc44 | MehdiNV/programming-challenges | /challenges/Diagonal Difference | 1,576 | 4.5 | 4 | #!/bin/python3
"""
Problem:
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix (arr) is shown below:
1 2 3
4 5 6
9 8 9
Looking at the above, you can see that...
The left-to-right diagonal = 1 + 5 + 9 = 15.
The right to left diagonal = 3 + 5 + 9 = 17 .
Their absolute difference is |15-17| = 2
The aim is to complete the function 'diagonalDifference',
which returns an integer representing the absolute diagonal difference (when inputted the parameter arr)
"""
import math
import os
import random
import re
import sys
# Complete the diagonalDifference function below.
# Author: Mehdi Naderi Varandi
def diagonalDifference(arr): #Start of code submission
columnAndRow=arr[0]
leftDiag=0
rightDiag=0
leftPointer=0
rightPointer=(len(arr[0])-1)
for i in range(0,len(arr[0])):
for j in range(0,len(arr[0])):
if (j==leftPointer):
leftDiag+=arr[i][j]
if(j==rightPointer):
rightDiag+=arr[i][j]
leftPointer+=1
rightPointer-=1
return (abs(rightDiag-leftDiag)) #Return absolute difference (irregardless of whether its + or -)
#End of code submission
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
result = diagonalDifference(arr)
fptr.write(str(result) + '\n')
fptr.close()
| true |
586bd4a6b6ec0a7d844531448285fab1499f10bd | NontandoMathebula/AI-futuristic | /Python functions.py | 1,492 | 4.53125 | 5 | import math
#define a basic function
#def function1():
# print("I am a cute function")
#function that takes arguments
#def function2(arg1, arg2):
#print(arg1, " ", arg2)
#funcion that returns a value
#def cube(x):
#return x*x*x
#function with default value for an argument
def power(num, x = 1):
result = 1
for i in range(x):
result = result * num #it takes a number and raises it to the given power
return result
#function with variable number of arguments
#def multi_add(*args): #the star character means I can pass a variable number of arguments
#result = 0
#for x in args:
# result = result + x #the function loops over each argument and adds them all to a running total, which is then returned
#return result
#"Parameter values" of the above functions
#function1() #functions are objects that can be passed around to other pieces of Python code
#print(function1()) #here the function is called inside the print statement the output should be "I am a cute function"
#print(function1) #this function doesn't return a value, therefore, the output is set to "None" meaning it is not executed because there are no parathesis
#function2(10,20)
#print(function2(10,20))
#print(cube(3))
print(power(2, 1))
print(power(2, 3))
print(power(x=3, num=2))#function can be called in no particular order, if you supply the names along with the values
print(math.pow(2,3))
#print(multi_add(30, 5, 10, 4))
| true |
cf8e3546673231056cd11c663e0dfde3b158fb9c | albertisfu/devz-community | /stacks-queues/stacks-queues-2.py | 2,013 | 4.21875 | 4 |
#Node Class
class Node:
def __init__(self, data):
self.data = data
self.next_node = None
#LinkedList Class
class Stack:
def __init__(self):
self.head = None
#append new elements to linked list method
def push(self, data):
new_node = Node(data)
if self.head == None:
self.head = new_node
else:
prev_head = self.head
self.head = new_node
new_node.next_node = prev_head
def peek(self):
if self.head != None:
#print(self.head.data)
return self.head.data
else:
#print('None')
return None
def pop(self):
if self.head != None:
last_node = self.head
#print(last_node.data)
self.head = last_node.next_node
return last_node.data
else:
#print('None')
return None
#print elements of linked list
def print_list(self):
if self.head != None:
current_node = self.head
while current_node != None:
print(current_node.data)
current_node = current_node.next_node
class StackQueue:
def __init__(self):
self.in_stack = Stack()
self.out_stack = Stack()
def push(self, data):
self.in_stack.push(data)
def pop(self):
while self.in_stack.peek() != None:
value = self.in_stack.pop()
self.out_stack.push(value)
return self.out_stack.pop()
def peek(self):
while self.in_stack.peek() != None:
value = self.in_stack.pop()
self.out_stack.push(value)
return self.out_stack.peek()
new_stack = StackQueue()
new_stack.push(1)
new_stack.push(2)
new_stack.push(3)
new_stack.push(4)
new_stack.push(5)
print('peek: ', new_stack.peek() )
print('pop: ', new_stack.pop() )
print('peek: ', new_stack.peek() )
| true |
796196c624f370d5237a3f5102e900e534adc4e7 | sandeepmendiratta/python-stuff | /pi_value_to_digit.py | 1,004 | 4.28125 | 4 | #!/usr/bin/env python3
""""Find PI to the Nth Digit -
Enter a number and have the program generate PI up to that many decimal places.
Keep a limit to how far the program will go."""
import math
def getValueOfPi(k):
return '%.*f' % (k, math.pi)
def main():
"""
Console Function to create the interactive Shell.
Runs only when __name__ == __main__ that is when the script is being called directly
No return value and Parameters
"""
print("Welcome to Pi Calculator. In the shell below Enter the number of digits upto which the value of Pi should be calculated or enter quit to exit")
while True:
try:
entry = int(input("How many spaces? "))
if entry > 50:
print("Number to large")
# elif str(entry) == "quit":
# break
else:
print(getValueOfPi(int(entry)))
except:
print("You did not enter an integer")
if __name__ == '__main__':
main() | true |
092a3fd97569804c742af907c3279274384885fa | 333TRS-CWO/scripting_challenge_questions | /draw_box.py | 545 | 4.25 | 4 | from typing import List
'''
Complete the draw_box function so that given a non-negative integer that represents the height and width of a box,
the function should create an ASCII art box for returning a list of strings.
Then wall of the box should be made up of the "X" character
The interior of the box should be made up of the " "(space) character
Don't try to stack the box, just ensure you return the appropriate strings that could be stacked vertically, given proper formatting.
'''
def draw_box(box_size: int) -> List[str]:
pass | true |
4698e65f6b47edcf78afa0b583ccc0bb873df5a3 | shouryaraj/Artificial_Intelligence | /uniformed_search_technique/uniform-cost-search.py | 1,787 | 4.21875 | 4 | """
Implementation of the uniform cost search, better version of the BFS.
Instead of expanding the shallowest node, uniform-cost search expands the node n with the lowest path cost
"""
from queue import PriorityQueue
# Graph function implementation
class Graph:
def __init__(self):
self.edges = {}
self.weights = {}
def neighbors(self, node):
return self.edges[node]
def get_cost(self, from_node, to_node):
return self.weights[(from_node + to_node)]
def uniform_cost_search(graph, start_node, goal):
"""
:param graph: The simple directed graph with the weight as string
:param start_node: start node is the starting point
:param goal: The end point to reach, that is goal state
:return: nothing to return, prints the total cost
"""
path = set()
explored = set()
if start_node == goal:
return path, explored
path.add(start_node)
path_cost = 0
frontier = PriorityQueue()
frontier.put((path_cost, start_node))
while frontier:
cost, node = frontier.get()
if node not in explored:
explored.add(node)
if node == goal:
print("all good")
print("At the cost of " + str(cost))
return
for neighbor in graph.neighbors(node):
if neighbor not in explored:
total_cost = cost + graph.get_cost(node, neighbor)
frontier.put((total_cost, neighbor))
# Driver Function
edges = {
'S': ['R', 'F'],
'R': ['P'],
'F': ['B'],
'P': ['B']
}
weigth = {
'SR': 80,
'SF': 99,
'RP': 97,
'PB': 101,
'FB': 211
}
simple_graph = Graph()
simple_graph.edges = edges
simple_graph.weights = weigth
uniform_cost_search(simple_graph, 'S', 'B')
| true |
2e5e44ba73492ca11a60fc193f088a191b7fd91f | akdutt/simple-programs | /193negative.py | 202 | 4.1875 | 4 | a=raw_input("Enter a no which you want to finf Negative , Positive or Zero. ")
if int(a)>0:
print ("No is Positive. ")
elif int(a)<0:
print("No is Negative. ")
else :
print ("No is Zero. ")
| false |
d9c92cbd819418374239d8e0915c76926a994e13 | Pavithralakshmi/corekata | /poer.py | 207 | 4.125 | 4 | print(" power of input")
y=0
while y==0:
number1 = int(input('Enter First number : '))
number2 = int(input('Enter Second number : '))
o=number1**number2
print(o)
y=int(input("0 to continue"))
| false |
5f40dec210d36c3114c1d66a8c2c63371e93fa88 | Pavithralakshmi/corekata | /m7.py | 356 | 4.1875 | 4 | print("cheack the given input is mulitiple by 7");
y=0
while y==0:
num=int(input("enter ur first input"))
if num>1:
for i in range(1,num):
if num%7==0:
print (num,"this number is multiple by 7")
break
else:
print(num,"this number is not multiple by 7")
y=int(input("ënter 0 to continue else press 1"))
| true |
581c8b441de9dcafd76d98cfc6841f3b95bdf2c2 | Pavithralakshmi/corekata | /sec.py | 290 | 4.1875 | 4 | print("calculate amounts of seconds ")
days =int(input("Inputdays: ")) * 3600* 24
hours = int(input("Input hours: ")) * 3600
minutes = int(input("Input minutes: ")) * 60
seconds = int(input("Input seconds: "))
time = days + hours + minutes + seconds
print("The amounts of seconds ", time)
| true |
886e48bc59c4e8c424270e8491c16569ed458dd8 | faisalmoinuddin99/python | /python/chapter1/complexType.py | 879 | 4.15625 | 4 | def __main__():
tuple = (2,5,6)
#tuples are fixed
print(tuple)
#List
list = [4,1,9,3,2,0,45]
list.sort()
print(list)
#Dictionary
dict1 = {'one':1,'two':2}
print(dict1)
dict2 = dict([('one',1),('two',2)])
print(dict2)
dict3 = dict(one=1,two=2)
print(dict3)
#Python | Merging two Dictionaries
dictA = dict(one=1,two=2)
dictB = dict(goku=4000)
dictC = dictA.update(dictB)
print(dictA)
#Python Exercise: Check if a given key already exists in a dictionary
d = dict(one=1,two=2,five=5,three=3)
def __ispresent__(x):
if x in d:
print('already exists')
else:
print('not found')
__ispresent__(5)
__ispresent__(2)
if __name__ == '__main__':__ispresent__()
if __name__ == '__main__':__main__()
| false |
da849e60a9415fcab68301964185eec25d87a179 | ExerciseAndrew/Algorithms | /python/Stack.py | 1,271 | 4.25 | 4 | ### Implementation of a stack using python list
class Stack:
def __init__(self, items):
#creates empty stack
self._theItems = list()
def isEmpty(self)
#returns True if stack is empty
return len(self) == 0
def __len__(self):
#returns number of items in the stack
return len( self._theItems )
def peek(self):
#returns top item of stack without removing it
assert not self.isEmpty(), "cannot peek at an empty stack"
return self._theItems[-1]
def pop(self):
#removes and returns the top item of the stack
assert not self.isEmpty(), "cannot pop an empty stack"
return self._theItems.pop()
def push(self, itema):
return self._theItems.append( item )
#Push an item to the top of the stack
def is_balanced(self):
#determines if stack is balanced or not
for char in _theItems:
if char in ['(', '[']:
stack.push(char)
else:
if isEmpty(): return False
stack.pop()
if (top == '[' and char != ']') or (top == '(' and char != ')'):
return False
return | true |
eea7f7d0ba7898a1710816682b1aa4fad7ca2731 | Surfsol/Intro-Python-I | /src/12_scopes.py | 1,019 | 4.375 | 4 | # Experiment with scopes in Python.
# Good reading: https://www.programiz.com/python-programming/global-local-nonlocal-variables
# When you use a variable in a function, it's local in scope to the function.
x = 12
def change_x():
x = 99
change_x()
x = 99
# This prints 12. What do we have to modify in change_x() to get it to print 99?
print(x)
# This nested function has a similar problem.
def outer():
y = 120
def inner():
y = 999
inner()
# This prints 120. What do we have to change in inner() to get it to print
# 999?
# Note: Google "python nested function scope".
print(y)
outer()
#local, enclosing, global, built in
#local
x = 1
y = 2
def mmm(x):
y = 3
print(x, y)
mmm(10)
print(x, y)
x = 100
def my_outer(x):
y = 50
def inner():
print(x,y)
inner()
my_outer(75)
#last scope to be searched Builtin
print(pow(2, 3))
#see builtin variables
#puts a variable in global scope
def vus():
global x
x = 100
vus()
print(x) | true |
609f758927e1418796543ffde2c9dc366c38bc59 | MuhammadEhtisham60/dev-code2 | /string.py | 723 | 4.1875 | 4 |
"""
print('Hello')
print("Hello")
a="Hello World"
print(a)
"""
#string are array
"""
a="Hello_World"
print(a[9])
"""
#b="hello,world"
#print(b[-5:-3])
#c="Hello, shami"
#print(len(c))
#print(c.strip())
#print(c.lower())
#print(c.upper())
#print(c.replace("shami","world"))
#print(c.split(","))
"""
txt="The rain in Spain stays mainly in the plain"
x="ain" not in txt
print(x)"""
"""
a="hello"
b="world"
c=a+" "+b
print(c)
"""
"""
qty=3
itemno=500
prise=45.89
myorder="I want {} pieces of item {} for pay {} dollar"
print(myorder.format(qty, itemno, prise))
"""
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
| false |
6576d205ded2eb55bb61f325c12e4c57926e3961 | Chaudhari-Chirag/sippython | /exercise/ex2.py | 256 | 4.1875 | 4 | # -*- coding: utf-8 -*-
def max_of_three(num1, num2, num3):
if num1 > num2 > num3:
return num1
elif num1 < num2 < num3:
return num3
else: return num2
print (max_of_three(2, 3, 4))
print (max_of_three(4, 3, 2))
print (max_of_three(2, 4, 3)) | false |
4fd91d5b414a5268ea4baceed3e5a36a65e289a4 | Chaudhari-Chirag/sippython | /sip/sipA24_revloops.py | 458 | 4.21875 | 4 | # -*- coding: utf-8 -*-
#loops
#for loop
for i in range(1,5):
print(i, end=' ')
for i in range(1, 20):
if i%2==0:
print(i, 'is even number')
for i in range(1, 100):
if i%i==0 and i%2>0 and i%3>0 and i%5>0:
print(i, 'is prime number')
#while
while True:
s = input("Enter something, end to exit : ")
if s == 'end':
break;
if (len(s) < 3):
print('small text')
continue
| false |
beaeb644f8fe8229b68743dd33a8c898fa70a701 | Nathiington/COMP322 | /Lab03/greatest.py | 279 | 4.1875 | 4 | num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
if num1 > num2:
print('{0} is greater than {1}'.format(num1,num2))
if num2 > num1:
print('{0} is greater than {1}'.format(num2, num1))
else:
print('Both numbers are equal')
| true |
15c333a2098d819b9a27780609d683801c0e8643 | Btrenary/Module6 | /basic_function_assignment.py | 737 | 4.15625 | 4 | """
Author: Brady Trenary
Program: basic_function_assignment.py
Program takes an employee's name, hours worked, hourly wage and prints them.
"""
def hourly_employee_input():
try:
name = input('Enter employee name: ')
hours_worked = int(input('Enter hours worked: '))
hourly_pay_rate = float(input('Enter hourly pay rate: '))
result = f'{name}, {hours_worked} hours worked, {hourly_pay_rate}/hr.'
if name.isdigit():
print('Invalid name input')
elif hours_worked < 0 or hourly_pay_rate < 0:
print("Invalid input")
else:
print(result)
except ValueError:
print('Invalid input')
if __name__ == '__main__':
hourly_employee_input()
| true |
b247074ec75f920382e80eeae0f68a123d8e15d0 | mathe-codecian/Collatz-Conjecture-check | /Collatz Conjecture.py | 743 | 4.3125 | 4 | """
The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n.
Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term.
If the previous term is odd, the next term is 3 times the previous term plus 1.
The conjecture is that no matter what value of n, the sequence will always reach 1.
"""
x = int(input("Enter a Number:\n"))
step = 0
'''' Comment - (Loop for Finding The Whole sequence leading
to 1 and number of steps involved)'''
while x != 1:
if x%2 == 0:
x= x/2
else:
x = 3*x +1
print(x)
step +=1
print("Number of steps involved are " + str(step))
| true |
1f77b65cded382e0c1c0b149edf94e02c67f5bb5 | farremireia/len-slice | /script.py | 375 | 4.15625 | 4 | toppings = ['pepperoni', 'pineapple', 'cheese', 'sausage', 'olives', 'anchovies', 'mushrooms']
prices = [2,6,1,3,2,7,2]
num_pizzas = len(toppings)
print('We sell ' + str(num_pizzas) + ' different kinds of pizzas!')
pizzas = list(zip(prices, toppings))
print(pizzas)
pizzas.sort()
print(pizzas)
cheapest_pizza = pizzas[0]
priciest_pizza = pizzas[-1]
print(priciest_pizza) | true |
87d31fe1d670b7c6dc43441b6eefc8f578cadc52 | truevines/GenericExercise | /isomorphic_strings.py | 1,115 | 4.1875 | 4 | '''
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
For example,
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
Note:
You may assume both s and t have the same length.
'''
def isomorph(s, t):
#boundary case
if (len(s)!=len(t)):
return False
dic={}
# s as the key; t as the value
i=0
while (i<len(s)):
# i-th character:
#if s is in key, value must match
if (s[i] in dic) and (dic[s[i]]!=t[i]):
return False
#if s is not in key, t must not in value
if (s[i] not in dic) and (t[i] in iter(dic.values())):
return False
#if s is not in key, t not in value -> never appear
#add relationship
if (s[i] not in dic) and (t[i] not in iter(dic.values())):
dic[s[i]]=t[i]
i+=1
return True
| true |
d46999e4c6dd96a8edeac232fa3a989160530596 | alexzinoviev/itea_c | /advance/advance_04_3.py | 1,234 | 4.15625 | 4 | # class A:
# def __init__(self):
# self.x = 0 # public переменная
# self._x = 0 # private - не использовать!
# self.__x = 0 # hidden
#
#
# a = A()
# print(a.x)
# print(a._x)
# #print(a.__x)
#
# print(vars(a))
#
# print(a._A__x)
# class A:
# def __init__(self):
# self.__x = 1 # hidden
#
# def f(self):
# print(self.__x)
#
# class B(A):
# def __init__(self):
# self.__x = 2
# super().__init__()
# def g(self):
# print(self.__x)
#
# b = B()
# print(b.f())
#-------------
# class A:
# def __init__(self):
# self.a = 1
# a = 2
#
# def f(self):
# print(self.a)
# @staticmethod # позволяет вызывать функции от имени класса
# def g():
# print(A.a)
# @classmethod
# def h(cls):
# print(cls.a)
#
# a = A()
#
# print(a.f())
# a.g()
# a.h()
# A.g()
# A.h()
# #A.f()
#-------------------
class A:
a = 1
@classmethod
def f(cls):
print(cls.a)
@staticmethod # явно привязан к классу
def g():
print(A.a)
class B(A):
a = 22
A.f()
B.f()
A.g()
B.g() | false |
3d8460e71d08dfd3446437d5ac6904822c59f6a2 | gavinchen523/learning_python | /part2.py | 2,046 | 4.21875 | 4 | #!/usr/bin/env python
#DATA type
# 1. Number
num1=3
num2=2
num3=num1/num2
print(type(num1))
print(type(num2))
print(type(num3))
# 2. String
str = 'abcdefasdsfa'
print('string len: ', len(str))
es_str=r'\t'
print('string len: ', len(es_str))
es2_str="""
a
ab
abc
"""
print('string len: ', len(es2_str))
# 3. Boolean
# in python , None==null
#python false值: False None [] {} "" set() () 0.0
is_num_bigger_than_one = 1>2
print(is_num_bigger_than_one) #False
x=None
print(x == None) #true
# 4. List
list_num = [1, 2, 3]
list = ['string', 1, [], list_num]
list_length = len(list_num)
num_sum=sum(list_num)
print(list_length)
print(num_sum)
x=range(10)
zero = x[0]
nine = x[-1]
#x[0] = -1
print(x[:3])
print(x[3:])
print(x[1:5])
print(x[0:-1])
print(x[-1:-1])
print(1 in [1, 2, 3])
a=[1, 2, 3]
a.extend([4, 5, 6])
print(a[:])
b=a+[7, 8, 9]
print(b[:])
b.append(0)
print(b[:])
# 5. Tuple : 類似List,但宣告後不能修改。
my_list = [1, 2]
my_tuple = (1, 2)
my_list[1] = 3
try:
my_tuple[1] = 4
except TypeError:
print('cannot modify a tuple')
x, y = 1, 2
x, y = y, x
print(x, y)
# 6. Dictionary : 類似map,包含鍵值和key值
dict1 = {}
dict2 = dict()
grades = {'Mark': 70, 'Jack': 40}
print(grades['Mark'])
grades['KD'] = 100
print(len(grades), grades['KD'])
try:
grade = grades['XD']
except KeyError:
print('no grade for XD')
grades.get('XD',40)
print(grades.keys())
print(grades.values())
print(grades.items())
#defaultdict
#一般作法
document=grades
word_counts={}
for word in document:
try:
word_counts[word] += 1
except KeyError:
word_counts[word] = 1
word_count = {}
for word in document:
previous_count = word_counts.get(word, 0)
word_counts[word] = previous_count + 1
from collections import defaultdict
word_counts = defaultdict(int)
for word in document:
word_counts[word] += 1
# Set :栠合中不包括重複的元素值
s = set()
s.add(1)
s.add(2)
s.add(3)
print(len(s), 1 in s)
list_item = [1, 2, 3, 1, 2, 3]
set_item = set(list_item)
print(set_item)
| false |
2087c9753aaa8e60bd2add3256f03431a538d185 | HarleyRogers51295/PYTHON-LEARNING | /1.1 PYTHON/1.4 pythong-numbers.py | 1,445 | 4.21875 | 4 | import math
import random
print("-------------BASICS & MATH--------------")
#integer is a whole number ex. 4, 500, 67, 2........ no decimals
#float has a decimal point ex. 1.521346584 .....
#python auto changes these for you if you do 1 + 1.5 it will be 2.5.
#you can use +, -, /, *, %, **(to the power of!)
print(abs(-50)) #returns the positive of the number entered
print(abs(50))
print(10 + 5)
print(10 - 5)
print(10 * 5)
print(10 / 5)
print(10 % 5)
print(10 ** 5)
print(math.pow(10, 5))
print(math.log2(100000000)) #this will come up in the algo area
print(random.randint(0, 1000)) #random number generator
print("--------------TYPE CASTING-------------")
result = "10" + "10"
print(result)
#type cast as such!
result = int("10") + int("10") ##typically used with variuables. look below.
print(result)
print(type("10"))
num_1 = "20"
num_2 = "14"
result = int(num_1) + int(num_2) # change to int
print(result)
print(type(result))
num_3 = 10
num_4 = 45
result_2 = num_3 + num_4
result_2= str(result_2) #chamge to string
print(result_2)
print(type(result_2))
####CANNOT CONVERT things that are not numbers to an int! ex, harley cannot be a number.####
print("--------------INPUT FROM USER-------------")
print("Welcome here! PLease enter yur numbers to be multiplied!")
print("-" * 30)
num_5 = input("Enter Your first number here: ")
num_6 = input("Enter Your second number here: ")
result_3 = int(num_5) * int(num_6)
print(result_3) | true |
ade8f044c63fbfac40e25b851ded70da30ab1533 | the-potato-man/lc | /2018/21-merge-two-sorted-lists.py | 776 | 4.125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# Creating pointers so the original lists aren't modified
p1 = l1
p2 = l2
dummy = p3 = ListNode(0)
while p1 and p2:
if p1.val < p2.val:
p3.next = ListNode(p1.val)
p1 = p1.next
else:
p3.next = ListNode(p2.val)
p2 = p2.next
p3 = p3.next
if p1:
p3.next = p1
else:
p3.next = p2
return dummy.next
| true |
87cee9d43718c10c989e16c6c993abd82d40d4ef | uit-inf-1400-2017/uit-inf-1400-2017.github.io | /lectures/05-summary-and-examples/code/PointRobust.py | 1,947 | 4.34375 | 4 | # Program: RobustPoint.py
# Authors: Michael H. Goldwasser
# David Letscher
#
# This example is discussed in Chapter 6 of the book
# Object-Oriented Programming in Python
#
from math import sqrt # needed for computing distances
class Point:
def __init__(self, initialX=0, initialY=0):
self._x = initialX
self._y = initialY
def getX(self):
return self._x
def setX(self, val):
self._x = val
def getY(self):
return self._y
def setY(self, val):
self._y = val
def scale(self, factor):
self._x *= factor
self._y *= factor
def distance(self, other):
dx = self._x - other._x
dy = self._y - other._y
return sqrt(dx * dx + dy * dy) # imported from math module
def normalize(self):
mag = self.distance( Point() )
if mag > 0:
self.scale(1/mag)
def __str__(self):
return '<' + str(self._x) + ',' + str(self._y) + '>'
def __add__(self, other):
return Point(self._x + other._x, self._y + other._y)
def __mul__(self, operand):
if isinstance(operand, (int,float)): # multiply by constant
return Point(self._x * operand, self._y * operand)
elif isinstance(operand, Point): # dot product
return self._x * operand._x + self._y * operand._y
def __rmul__(self, operand):
return self * operand
if __name__ == '__main__':
a = Point()
a.setX(-5)
a.setY(7)
print('a is', a) # demonstrates __str__
b = Point(8, 6)
print('b is', b)
print('distance between is', a.distance(b))
print(' should be same as', b.distance(a))
c = a + b
print('c = a + b results in', c)
print('magnitude of b is', b.distance(Point()))
b.normalize()
print('normalized b is', b)
print('magnitude of b is', b.distance(Point()))
print('a * b =', a * b)
print('a * 3 =', a * 3)
print('3 * a =', 3 * a)
| true |
afec1e0f73187993bcccc19b708eca0234b959f1 | merileewheelock/python-basics | /objects/Person.py | 1,904 | 4.21875 | 4 | class Person(object): #have to pass the object right away in Python
def __init__(self, name, gender, number_of_arms, cell): #always pass self, name is optional
self.name = name
self.gender = gender #these don't have to be the same but often make the same
self.species = "Human" #all Persons are automatically set to human
self.number_of_arms = number_of_arms
self.phone = {
"cell": cell,
"home": "Who has a home phone anymore?"
}
def greet(self, other_person):
print "Hello %s, I am %s!" % (other_person, self.name)
def print_contact_info(self):
if (self.phone["cell"] != ""):
print "%s's number is %s" % (self.name, self.phone["cell"])
marissa = Person("Marissa", "female", 3, "770-777-7777") #self is always implied, don't pass self
print marissa.name, marissa.gender, marissa.species, marissa.number_of_arms
merilee = Person("Merilee", "female", 2, "770-555-5555")
print merilee.species #this will return Human
merilee.species = "Robot"
print merilee.species #this will return Robot due to reassigning .species to robot
print merilee.number_of_arms
print marissa.phone["cell"]
print marissa.phone["home"]
marissa.greet("Rob")
marissa.print_contact_info() #This will run the code
print merilee.print_contact_info #This will not error but will print the actual method
class Vehicle(object):
def __init__(self, make2, model2, year2):
self.make = make2 #2 added to make clearer
self.model = model2
self.year = year2
def print_info(self):
print self.year, self.model, self.make
def change_year(self, new_year):
self.year = new_year
def get_year(self):
return self.year
david_cummings_car = Vehicle("Mcclaren", "Mp4-12c", 2013)
david_cummings_car.print_info()
david_cummings_car.change_year(2015) #These two are the same
david_cummings_car.year = 2015
print david_cummings_car.year #These two are the same
print david_cummings_car.get_year()
| true |
9a16c86ce7f42e1d826b67de35c866885e79c9b6 | merileewheelock/python-basics | /dc_challenge.py | 2,153 | 4.5 | 4 | # 1) Declare two variables, a strig and an integer
# named "fullName" and "age". Set them equal to your name and age.
full_name = "Merilee Wheelock"
age = 27
#There are no arrays, but there are lists. Not push, append.
my_array = []
my_array.append(full_name)
my_array.append(age)
print my_array
def say_hello():
print "Hello!"
say_hello()
# 4) Declare a variable named splitName and set it equal to
# fullName split into two seperate objects in an array.
# (In other words, if the variable fullName is equal to "John Smith", then splitName should
# equal ["John", "Smith"].)
# Print splitName to the console.
# HINT: Remember to research the methods and concepts listed in the instructions PDF.
split_name = full_name.split()
print split_name
# 5) Write another simple function that takes no parameters called "sayName".
# When called, this function should print "Hello, ____!" to the console, where the blank is
# equal to the first value in the splitName array from #4.
# Call the function. (In our example, "Hello, John!" would be printed to the console.)
def say_name():
print ("Hello, " + split_name[0])
say_name()
# 6) Write another function named myAge. This function should take one parameter: the year you
# were born, and it should print the implied age to the console.
# Call the function, passing the year you were born as the argument/parameter.
# HINT: http://www.w3schools.com/js/js_functions.asp
def my_age(birthyear):
print (2017 - birthyear)
my_age(1989)
# 7) Using the basic function given below, add code so that sum_odd_numbers will print to the console the sum of all the odd numbers from 1 to 5000. Don't forget to call the function!
# HINT: Consider using a 'for loop'.
def sum_odd_numbers():
sum = 0
for i in range(1,5001,2): #2 is the step (increases by 2)
sum += i
return sum
print sum_odd_numbers()
# def sum_odd_numbers():
# sum = 0
# for i in range(1,5001):
# if (i % 2 == 1): #This uses the modulus instead of the step
# sum += i
# return sum
# print sum_odd_numbers()
i = 0
while 1: #this alone will run forever
i += 1
print i
if (i ==10):
break
print "We broke out of the loop!" | true |
d18cc25296b06719cefe2efa1c9c836a6689b982 | Orcha02/Mock_Interviews | /Python/No_c.py | 309 | 4.15625 | 4 | #!/usr/bin/env python3
def no_c(my_string):
the_new_string = ''
for char in my_string:
if char == 'C' or char == 'c':
continue
the_new_string = the_new_string + char
return the_new_string
print(no_c("Holberton School"))
print(no_c("Chicago"))
print(no_c("C is fun!"))
| false |
fa07c4342580abebebeb3107c1a642a5fdc3d580 | manaya078/Python_base | /0Deep/ReLU.py | 413 | 4.21875 | 4 | """
ReLU関数(Rectified Linear Unit)
入力が0より大きいなら入力をそのまま出力し、0以下なら0を出力する
def relu(x):
return np.maximum(0, x)
"""
import numpy as np
import matplotlib.pylab as plt
def relu(x):#ReLU関数
return np.maximum(0, x)
x = np.arange(-5.0, 5.0, 0.1)#-5.0から5.0まで0.1刻み
y = relu(x)
plt.plot(x, y)
plt.ylim(-0.1, 5.0)#y軸の範囲
plt.show() | false |
737f4b4ac58e7c1cd65b096b1f93db0fccfdfaa6 | Zubair-Ali61997/learnOOPspring2020 | /main1.py | 1,752 | 4.3125 | 4 | #Taking the range of number from the user to find even and odd using for loop
startNum = int(input("Enter starting value: "))
endNum = int(input("Enter end value: "))
for eachNumber in range(startNum,endNum+1):
modeValue = eachNumber % 2
if modeValue == 0:
print(eachNumber, "is an even")
else:
print(eachNumber, "is an odd")
#Taking the range of number from the user to find even and odd using while loop
# taking_a_value = int(input("Enter a value: "))
startNum = int(input("Enter starting value: "))
endNum = int(input("Enter end value: "))
while (startNum >= endNum):
modeValue = endNum % 2
if modeValue == 0:
print(endNum, "is an even")
else:
print(endNum, "is an odd")
endNum=endNum+1
#Finding totel number of odd and even in a range using for loop
startNum = int(input("Enter starting value: "))
endNum = int(input("Enter end value: "))
evenNumber = 0
oddNumber = 0
for eachNumber in range (startNum, endNum+1):
modeValue = eachNumber % 2
if modeValue == 0:
evenNumber = evenNumber + 1
else:
oddNumber = oddNumber + 1
print ("Total number of even number is = ",evenNumber)
print ("Total number of odd number is = ",oddNumber)
# Finding totel number of odd and even in a range using while loop
startNum = int(input("Enter starting value: "))
endNum = int(input("Enter end value: "))
evenNumber = 0
oddNumber = 0
while (startNum >= endNum):
modeValue = endNum % 2
if modeValue== 0:
evenNumber = evenNumber + 1
else:
oddNumber = oddNumber + 1
endNum = endNum + 1
print ("Total number of even number is = ",evenNumber)
print ("Total number of odd number is = ",oddNumber) | true |
6e892b4f6d70d5c79be4b157697d474eb6ebd5cb | G00387847/Bonny2020 | /second_string.py | 279 | 4.25 | 4 | # Bonny Nwosu
# This program takes asks a user to input a string
# And output every second letter in reverse order.
# Using Loop
num1 = input("Please enter a sentence")
def reverse(num1):
str = ""
for i in num1:
str = i + str
return str
print(end="")
print(num1[::-2])
| true |
f5c751a2014f66acb82280c0ae522afd590fd8fd | yanethvg/Python_stuff | /concepts/entrada.py | 407 | 4.15625 | 4 | #print("¿Cual es tu nombre?")
nombre = input("¿Cual es tu nombre?\n")
#print("¿Cual es tu edad?")
edad = int(input("¿Cual es tu edad?\n"))
#print("¿Cual es tu peso?")
peso = float(input("¿Cual es tu peso?\n"))
#print("Estas autorizado?(si/no)")
autorizado = input("Estas autorizado?(si/no)\n") == "si"
print("Hola",nombre, "tu edad es: ", edad, " tu peso es: ",peso)
print("Autorizado",autorizado) | false |
da72a6c6f6470375671f399c4118d57d0346938c | yanethvg/Python_stuff | /class/herencia_multiple.py | 1,330 | 4.21875 | 4 | # como se lee de arriba hacia abajo
# se deben definir las clases antes que las clases hijas
class Animal:
def __init__(self,nombre):
self.nombre = nombre
def comer(self):
print("Comiendo")
def dormir(self):
print("Durmiendo")
def comun(self):
print("Este es un metodo de Animal")
# que sucede si hay un metodo en comun en ambas clases a heredar
class Mascota:
def fecha_adopcion(self,fecha):
self.fecha_de_adopcion = fecha
def comun(self):
print("Este es un metodo de Mascota")
#herencia por medio de parentesis
# se colocan separados por una coma
# busca de izquierda a derecha
# busca en la primera clase padre
# si no existe en la primera busca en la segunda y asi sucesivamente
class Perro(Animal, Mascota):
def ladrar(self):
print("Ladrando")
#busca el metodos dentro de perro antes que en las demas
"""
def comun(self):
print("Este es un metodo de Perro")
"""
class Gato(Animal, Mascota):
def ronroneo(self):
print("Ronroneo")
firulais = Perro("Firulais")
firulais.comer()
firulais.dormir()
firulais.ladrar()
firulais.fecha_adopcion("Hoy")
print(firulais.fecha_de_adopcion)
firulais.comun()
print("\n")
gatito = Gato("Gatito")
gatito.comer()
gatito.dormir()
gatito.ronroneo() | false |
fb2bb0a3eaab6f9cdc2cc9d35b0d23b992d21e41 | skolte/python | /python2.7/largest.py | 825 | 4.1875 | 4 | # Write a program that repeatedly prompts a user for integer numbers until
# the user enters 'done'. Once 'done' is entered, print out the largest and
# smallest of the numbers. If the user enters anything other than a valid number
# catch it with a try/except and put out an appropriate message and ignore the number.
# Enter the numbers from the book for problem 5.1 and Match the desired output as shown.
# Uses Python 2.7
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
try:
int(num)
if (num > largest or largest is None):
largest = num
if (num < smallest or smallest is None):
smallest = num
except ValueError:
print "Invalid input"
print "Maximum is", largest
print "Minimum is", smallest | true |
d0e11c937aed44b865d184c98db570bfb5d522d5 | jegarciaor/Python-Object-Oriented-Programming---4th-edition | /ch_14/src/threads_1.py | 587 | 4.1875 | 4 | """
Python 3 Object-Oriented Programming
Chapter 14. Concurrency
"""
from threading import Thread
class InputReader(Thread):
def run(self) -> None:
self.line_of_text = input()
if __name__ == "__main__":
print("Enter some text and press enter: ")
thread = InputReader()
# thread.start() # Concurrent
thread.run() # Sequential
count = result = 1
while thread.is_alive():
result = count * count
count += 1
print(f"calculated squares up to {count} * {count} = {result}")
print(f"while you typed {thread.line_of_text!r}")
| true |
531389502dac8cacf8f628a76453a2760f6d51d7 | ningshengit/small_spider | /PythonExample/PythonExample/菜鸟编程网站基础实例/Python 翻转列表.py | 410 | 4.1875 | 4 | 实例 1
def Reverse(lst):
return [ele for ele in reversed(lst)]
lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))
实例 2
def Reverse(lst):
lst.reverse()
return lst
lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))
实例 3
def Reverse(lst):
new_lst = lst[::-1]
return new_lst
lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))
| false |
42912022fbc9cb00f9ee3721a18434e955d46f69 | ningshengit/small_spider | /PythonExample/PythonExample/菜鸟编程网站基础实例/Python 将列表中的指定位置的两个元素对调.py | 822 | 4.125 | 4 | 实例 1
def swapPositions(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
return list
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
实例 2
def swapPositions(list, pos1, pos2):
first_ele = list.pop(pos1)
second_ele = list.pop(pos2-1)
list.insert(pos1, second_ele)
list.insert(pos2, first_ele)
return list
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
实例 3
def swapPositions(list, pos1, pos2):
get = list[pos1], list[pos2]
list[pos2], list[pos1] = get
return list
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
| false |
0c98aecf543889b9c73f73b014508a184b0507e2 | Tower5954/Instagram-higher-lower-game | /main.py | 1,790 | 4.21875 | 4 | # Display art
# Generate a random account from the game data.
# Format account data into printable format.
# Ask user for a guess.
# Check if user is correct.
## Get follower count.
## If Statement
# Feedback.
# Score Keeping.
# Make game repeatable.
# Make B become the next A.
# Add art.
# Clear screen between rounds.
from game_data import data
import random
from art import logo, vs
from replit import clear
def format_account(account):
"""Format the data values into an account"""
account_name = account["name"]
account_descr = account["description"]
account_country = account["country"]
return f"{account_name}, a {account_descr}, from {account_country}"
def check_answer(guess, a_followers, b_followers):
"""Take the users guess and compares with followers then returns if correct """
if a_followers > b_followers:
return guess == "a"
else:
return guess == "b"
print(logo)
score = 0
game_continues = True
account_b = random.choice(data)
while game_continues:
account_a = account_b
account_b = random.choice(data)
if account_a == account_b:
account_b = random.choice(data)
print(f"Compare A: {format_account(account_a)}")
print(vs)
print("")
print(f"Against B: {format_account(account_b)}")
print("")
guess = input("Who has more instagram followers? Type 'A' or 'B' ").lower()
a_follower_account = account_a["follower_count"]
b_follower_account = account_b["follower_count"]
is_correct = check_answer(guess, a_follower_account, b_follower_account)
clear()
print(logo)
if is_correct:
score += 1
print(f"Well done, you're correct! You're score is {score}")
else:
game_continues = False
print(f"Who would have thought it, however Unfortunately you're wrong this time. You're final score is {score}") | true |
80ac17949c445619dda20aa217ae6a7158b014ce | wz33/MagicNumber | /magic_number.py | 1,761 | 4.3125 | 4 | from builtins import input # for handling user input gracefully in Python 2 & 3
#!/usr/bin/env Python3
# Python 2 & 3
"""
Program generates a random number between 1 and 100, inclusive. User has five attempts to correctly guess the number.
"""
# Import Python module
import random # for "magic" number generation
# Define variable
MAX_ATTEMPTS = 5 # maximum number of guesses
# Define functions
def num_gen():
"""
Return random number between 1 and 100, inclusive.
"""
return random.randint(1, 100)
def user_guess():
"""
Prompt player for guess.
Return integer.
"""
while True:
try:
return int(input('Enter a guess: '))
except ValueError:
print('Sorry, try again.')
def play_again():
"""
Prompt user for Y/N input.
Return y or n.
"""
while True:
again = input('Play again? Y/N: ').lower()
if again == 'y' or again == 'n':
return again
def guessing_game():
"""
Compare user guess to magic number.
Provide user feedback.
"""
magic_number = num_gen()
for attempt in range(MAX_ATTEMPTS):
guess = user_guess()
if guess < magic_number:
print('Higher...')
elif guess > magic_number:
print('Lower...')
else:
print('That\'s right!')
break
if guess != magic_number:
print('Out of guesses! The magic number was: %s.' % magic_number)
def game_play():
"""
Play game. Allow user to play multiple rounds or resign.
"""
while True:
play = guessing_game()
another_round = play_again()
if another_round == 'y':
continue
else:
break
if __name__ == '__main__':
print("\nWelcome to the magic number guessing game!\nSee if you can guess the magic number (1-100) in 5 attempts or less.\n")
game_play()
| true |
8d56284d45480737b0b2cd79d8c2358355828f8b | zahidkhawaja/cs-module-project-iterative-sorting | /src/iterative_sorting/iterative_sorting.py | 1,989 | 4.375 | 4 | # Runtime complexity: O(n ^ 2) - Quadratic
# Nested for-loop
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for x in range(cur_index, len(arr)):
if arr[x] < arr[smallest_index]:
smallest_index = x
# Swapping the values
arr[smallest_index], arr[cur_index] = arr[cur_index], arr[smallest_index]
return arr
# Runtime complexity: O(n ^ 2) - Quadratic
def bubble_sort(arr):
needs_swapping = True
while needs_swapping:
# Change to false and change back to true only if a swap occurs
# If a swap doesn't occur, it stays on false and the loop ends
needs_swapping = False
for x in range(len(arr) - 1):
# If the current value is greater than the next value, swap the values
if arr[x] > arr[x + 1]:
arr[x], arr[x + 1] = arr[x + 1], arr[x]
needs_swapping = True
return arr
'''
STRETCH: implement the Counting Sort function below
Counting sort is a sorting algorithm that works on a set of data where
we specifically know the maximum value that can exist in that set of
data. The idea behind this algorithm then is that we can create "buckets"
from 0 up to the max value. This is most easily done by initializing an
array of 0s whose length is the max value + 1 (why do we need this "+ 1"?).
Each buckets[i] then is responsible for keeping track of how many times
we've seen `i` in the input set of data as we iterate through it.
Once we know exactly how many times each piece of data in the input set
showed up, we can construct a sorted set of the input data from the
buckets.
What is the time and space complexity of the counting sort algorithm?
'''
def counting_sort(arr, maximum=None):
# Your code here
return arr
| true |
54dde7561bb2c3ef7fab4db446088c997c168037 | ZhaohanJackWang/me | /week3/exercise3.py | 2,448 | 4.40625 | 4 | """Week 3, Exercise 3.
Steps on the way to making your own guessing game.
"""
import random
def check_number(number):
while True:
try:
number = int(number)
return number
except Exception:
number = input("it is not number plz enter again: ")
def check_upper(upper, low):
upper = check_number(upper)
print(type(upper))
while True:
if upper > low:
return upper
else:
upper = check_number(input("upper should bigger than low, plz enter again: "))
def advancedGuessingGame():
"""Play a guessing game with a user.
The exercise here is to rewrite the exampleGuessingGame() function
from exercise 3, but to allow for:
* a lower bound to be entered, e.g. guess numbers between 10 and 20
* ask for a better input if the user gives a non integer value anywhere.
I.e. throw away inputs like "ten" or "8!" but instead of crashing
ask for another value.
* chastise them if they pick a number outside the bounds.
* see if you can find the other failure modes.
There are three that I can think of. (They are tested for.)
NOTE: whilst you CAN write this from scratch, and it'd be good for you to
be able to eventually, it'd be better to take the code from exercise 2 and
merge it with code from excercise 1.
Remember to think modular. Try to keep your functions small and single
purpose if you can!
"""
lowBound = input("Enter an low bound: ")
lowBound = check_number(lowBound)
upperBound = input("Enter an upper bound: ")
upperBound = check_upper(upperBound, lowBound)
actualNumber = random.randint(lowBound, upperBound)
guessed = -1
while guessed != actualNumber:
guessedNumber = input("Guess a number: ")
guessedNumber = check_number(guessedNumber)
print("You guessed {},".format(guessedNumber),)
if guessedNumber == actualNumber:
print("You got it!! It was {}".format(actualNumber))
guessed = actualNumber
elif guessedNumber > upperBound or guessedNumber < lowBound:
print("outside of bounds")
elif guessedNumber < actualNumber:
print("Too small, try again :'(")
else:
print("Too big, try again :'(")
return "You got it!"
# the tests are looking for the exact string "You got it!". Don't modify that!
if __name__ == "__main__":
print(advancedGuessingGame())
| true |
69d705b017380b3127c4c7cfda8636c3d8c16e3d | SOURADEEP-DONNY/PYTHON-3-PROGRAMMING | /week 4/ALIASING.py | 636 | 4.21875 | 4 | list1=[10,20,30]
list2=[10,20,30]
#CHECKING WHETHER THE TWO LISTS ARE SAME OR NOT.
print(list1 is list2)
#CHECKING THE IDS OF THE TWO LISTS.
print('THE ID OF list1 is',id(list1))
print('THE ID OF list2 is',id(list2))
#CHECKING WHETHER THE LISTS ARE EQUIVALENT OR NOT.
print(list1==list2)
#--------ALIASING----------
list1=list2
#AGAIN CHECKING THE IDS OF THE TWO LISTS.
print('THE ID OF list1 is',id(list1))
print('THE ID OF list2 is',id(list2))
#AGAIN CHECKING WHETHER THE TWO LISTS ARE SAME OR NOT.
print(list1 is list2)
#AGAIN CHECKING WHETHER THE LISTS ARE EQUIVALENT OR NOT.
print(list1==list2)
| true |
b5278bb8872dd0ad65f8cc46180085c42e9fcdc0 | SOURADEEP-DONNY/PYTHON-3-PROGRAMMING | /week 2/indexing.py | 204 | 4.46875 | 4 | #STRING AND LIST INDEXING
st="SMARTPHONE"
list1=['moto','mi','nokia','samsung']
#PRINTING THE LIST IN REVERSE ORDER
print(list1[-1::-1])
#PRINTING THE STRING IN REVERSE ORDER
print(st[-1::-1])
| false |
b259e685aef03dabe48233184d84bd228beac2a9 | SOURADEEP-DONNY/PYTHON-3-PROGRAMMING | /PYTHON FUNCTIONS FILES AND DICTIONARIES/week 4/ADDITION OF AS MANY NUMBERS AS POSSIBLE.py | 263 | 4.5 | 4 | #PROGRAM TO ADD AS MANY NUMBERS AS POSSIBLE. TO STOP THE ADDITION ENTER ZERO.
#THIS KIND OF LOOP IS ALSO KNOWN AS LISTENER'S LOOP.
SUM=0
number=1
while number!=0:
number=int(input('Enter a number to add-'))
SUM=SUM+number
print('The sum =',SUM)
| true |
ca0a7ee0294a77402a773cd3e928cdf7d2e075b6 | SOURADEEP-DONNY/PYTHON-3-PROGRAMMING | /week 4/NON MUTATING METHODS OF STRINGS.py | 499 | 4.1875 | 4 | #NON MUTATING METHODS OF STRINGS
# 1.UPPER METHOD
s=' souradeep is an engineer '
print(s.upper())
# 2.LOWER METHOD
s2=' SOURADEEP IS AN ENGINEER. '
SS=s2.lower()
print(SS)
#3. COUNT METHOD
c=s.count('e')
print('THE TOTAL NUMBER OF "e"',c)
#4. STRIP METHOD
print('***'+s.strip()+"***")
#5. REPLACE METHOD
s3=s2.replace('E','@')
print(s3)
#BUT AFTER ALL THESE METHODS THE STRINGS WHICH ARE INITIALIZED EARLIER ARE STILL
#UNALTERED
print(s)
print(s2)
| false |
53d6f8a3a438037857021c5d2264c6817c7406a1 | olgarozhdestvina/pands-problems-2020 | /Labs/Topic09-errors/check_input.py | 417 | 4.28125 | 4 | # Olga Rozhdestvina
# a program that takes in a number as an input and subtracts 10%
# prints the result,
# the program should throw a value error of the input is less than 0
# input number
num = int(input("Please enter a number: "))
# calculate 90%
percent = 0.90 # (1- 0.10)
ans = num * percent
if num < 0:
raise ValueError("input should be greater than 0: {}".format(num))
print("{} minus 10% is {}".format(num, ans)) | true |
ad6d93d3e1a7f72bf3749244698bf8dbaa7b4399 | jrbublitz/Aulas-python | /material/0 Primeiros passos/apoio.py | 998 | 4.28125 | 4 | # Declaração de variável
x = 1
y = "Teste"
_nome = "Gustavo"
Altura = 1.8
# Eclusão de uma variável
del x
del y
del _nome
del Altura
# Declarando várias variaveis com o mesmo valor
x = y = z = "Um valor aí"
# Declarando várias variaveis com o vários valores
x, y, z = "Valor1", 2, True
# ou
x, y, z = ("Valor1", 2, True)
# Indentação
# x = 1
# x = 2
# Isso retornará um erro
# x = 1
# x = 2
# Isso dará certo
# type() retorna o tipo do objeto
type(1) # retorna int
type("Teste") # retorn str
# print() mostra no console a representação de um objeto
print("OIIIIIII") # retorna "OIIIIIIII"
print("Isso", "é", "um", "teste") # retorna "Isso é um teste"
print(2 > 1) # retorna True
# input() pede algo ao usuário e espera que ele digite algo
input() # retorna só o que for digitado
input("Digite algo: ") # retorna só o que for digitado
# input() sempre retornará uma string
# len() retorna o tamanho do iterável
len("Teste") # retorna 5
len(4) # retorna erro | false |
85bb1fe7789199c56764cc8e42c056066c4fbbe2 | hay/codecourse | /solutions/erwin/opdracht06.py | 421 | 4.21875 | 4 | # -*- coding: utf-8 -*-
names = []
for name in range(3):
print name
name = raw_input("Noem een naam: ")
names.append(name)
fruit = raw_input("Vertel me je lievelingsvrucht: ")
for name in names:
if name[0].isupper():
print "Aangenaam, " + name
else:
print "Hoi " + name
print "De lettercombinatie 'te' komt voor:"
for name in names:
print "te" in name
print "%s is een %s" % (name, fruit.upper())
| false |
a142e7901d6517a5f203c3a42783d22fc744fd40 | hay/codecourse | /examples/lists1.py | 559 | 4.21875 | 4 | names = ["Bert", "Ernie", "Pino"]
for name in names:
print "Aangenaam, " + name
print names[1] # "Bert"
print names[-1] # "Pino"
hellos = []
for name in names:
hellos.append("Hallo " + name)
for hello in hellos:
print hello
years = [1983, 1980, 1993]
for year in years:
print year
print 1983 in years
eighties = range(1980, 1989)
for year in years:
is_eighties = year in eighties
print "%s in de jaren tachtig? %s" % (year, is_eighties)
# Een list kan meerdere type variabelen door elkaar hebben
things = [42, True, "Hallo"] | false |
326f824c5da9e3238e310bf849ed90f06c35cf90 | RaOneG/CS106A-Completionist-Files | /Section-5/stringconstruction.py | 1,964 | 4.28125 | 4 |
def only_one_first_char_new(s):
"""This function builds up a new string adding all characters in the input string except those that are
the same as the first char
>>> only_one_first_char_new('abba abba abba')
'abb bb bb'
>>> only_one_first_char_new('Stanford')
'Stanford'
>>> only_one_first_char_new('')
''
"""
if len(s) > 0:
s3 = s[0] + s.replace(s[0], '')
return s3
else:
return s
def only_one_first_char_keep(s):
"""This function removes all occurences of the first character except the first char itself and
returns the udpated string
>>> only_one_first_char_keep('abba abba abba')
'abb bb bb'
>>> only_one_first_char_keep('Stanford')
'Stanford'
>>> only_one_first_char_keep('')
''
>>> only_one_first_char_keep('aaaaa')
'a'
"""
if len(s) > 0:
s = s[0] + s.replace(s[0], '')
return s
else:
return s
def make_gerund(s):
"""This function adds 'ing' to the end of the given string s and returns this new word. If the given word already
ends in 'ing' the function adds an 'ly' to the end of s instead before returning.
>>> make_gerund('ringing')
'ringly'
>>> make_gerund('run')
'runing'
>>> make_gerund('')
'ing'
>>> make_gerund('ing')
'ly'
"""
if s.endswith("ing"): #s.startswith()
s = s[:-3] + "ly"
else:
s = s + "ing"
return s
def put_in_middle(outer, inner):
"""This function inserts the string inner into the middle of the string outer and returns this new value
>>> put_in_middle('Absolutely', 'freaking')
'Absolfreakingutely'
>>> put_in_middle('ss', 'mile')
'smiles'
>>> put_in_middle('hit', 'obb')
'hobbit'
"""
midpnt = len(outer) // 2
outer = outer[:midpnt] + inner + outer[midpnt:]
return outer
| false |
524e98dfa7805b3c42ff0c3c021510afdabeaf0a | SirMatix/Python | /MITx 6.00.1x Introduction to Computer Science using Python/week 1/Problem set 1/Problem 3.py | 1,413 | 4.15625 | 4 | """
Problem 3
15.0/15.0 points (graded)
Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print
Longest substring in alphabetical order is: abc
Note: This problem may be challenging. We encourage you to work smart. If you've spent more than a few hours on this problem, we suggest that you move on to a different part of the course. If you have time, come back to this problem after you've had a break and cleared your head.
"""
# tracking variables initialization
maxLen=0
current=s[0]
longest=s[0]
# program loop
# iterating through letters of string s
for letter in range(len(s) - 1):
#if letter ahead current letter is 'bigger' add to current sequence
if s[letter + 1] >= s[letter]:
current += s[letter + 1]
# if lenght of the current sequence is longer than maxLen update it
# and current becomes longest
if len(current) > maxLen:
maxLen = len(current)
longest = current
else:
current=s[letter + 1]
# prints out the longest substring
print ('Longest substring in alphabetical order is: ' + longest) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.