blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
bccdae6959d7354f0a68014f753b98a6e7075dc0
|
770847573/Python_learn
|
/Hello/抽象类的使用.py
| 400
| 4.125
| 4
|
import abc
class MyClass(metaclass=abc.ABCMeta):
@abc.abstractmethod
def mymethod(self):
pass
class My1(MyClass):
def mymethod(self):
print('Do something!!!')
my = My1()#如果一个类继承自抽象类,而未实现抽象方法,仍然是一个抽象类
my.mymethod()
#my1 = MyClass() TypeError: Can't instantiate abstract class MyClass with abstract methods mymethod
| false
|
d15a8a84b1a7e7ac54f74d47180757109a17782a
|
KurinchiMalar/DataStructures
|
/Medians/FindLargestInArray.py
| 505
| 4.28125
| 4
|
__author__ = 'kurnagar'
import sys
# Time Complexity : O(n)
# Worst Case Comparisons : n-1
# Space Complexity : O(1)
def find_largest_element_in_array(Ar):
max = -sys.maxint - 1 # pythonic way of assigning most minimum value
#print type(max)
#max = -sys.maxint - 2
#print type(max)
for i in range(0,len(Ar)):
if Ar[i] > max:
max = Ar[i]
return max
Ar = [2, 1, 5, 234, 3, 44, 7, 6, 4, 5, 9, 11, 12, 14, 13]
print ""+str(find_largest_element_in_array(Ar))
| false
|
f2640a1412c6ee3414bf47175439aba242d5c81f
|
KurinchiMalar/DataStructures
|
/LinkedLists/SqrtNthNode.py
| 1,645
| 4.1875
| 4
|
'''
Given a singly linked list, write a function to find the sqrt(n) th element, where n is the number of elements in the list.
Assume the value of n is not known in advance.
'''
# Time Complexity : O(n)
# Space Complexity : O(1)
import ListNode
def sqrtNthNode(node):
if node == None:
return None
current = node
count = 1
sqrt_index = 1
crossedthrough = []
result = None
while current != None:
if count == sqrt_index * sqrt_index:
crossedthrough.append(current.get_data())
result = current.get_data()
print "Checking if current count = sq( "+str(sqrt_index)+" )"
sqrt_index = sqrt_index + 1
count = count + 1
current = current.get_next()
print "We have crossed through: (sqrt(n))== 0 for :"+str(crossedthrough)
return result
head = ListNode.ListNode(1)
#print ListNode.ListNode.__str__(head)
n1 = ListNode.ListNode(2)
n2 = ListNode.ListNode(3)
n3 = ListNode.ListNode(4)
n4 = ListNode.ListNode(5)
n5 = ListNode.ListNode(6)
n6 = ListNode.ListNode(7)
n7 = ListNode.ListNode(8)
n8 = ListNode.ListNode(9)
n9 = ListNode.ListNode(10)
n10 = ListNode.ListNode(11)
n11 = ListNode.ListNode(12)
n12 = ListNode.ListNode(13)
n13 = ListNode.ListNode(14)
n14 = ListNode.ListNode(15)
#orig_head = ListNode.ListNode(1)
#orig_head.set_next(n1)
head.set_next(n1)
n1.set_next(n2)
n2.set_next(n3)
n3.set_next(n4)
n4.set_next(n5)
n5.set_next(n6)
n6.set_next(n7)
n7.set_next(n8)
n9.set_next(n10)
n10.set_next(n11)
n11.set_next(n12)
n12.set_next(n13)
n13.set_next(n14)
print "Sqrt node (last from beginning): "+str(sqrtNthNode(head))
| true
|
ec4a2fc2faea5acfea8a352c16b768c79e679104
|
KurinchiMalar/DataStructures
|
/Hashing/RemoveGivenCharacters.py
| 507
| 4.28125
| 4
|
'''
Give an algorithm to remove the specified characters from a given string
'''
def remove_chars(inputstring,charstoremove):
hash_table = {}
result = []
for char in charstoremove:
hash_table[char] = 1
#print hash_table
for char in inputstring:
if char not in hash_table:
result.append(char)
else:
if hash_table[char] != 1:
result.append(char)
result = ''.join(result)
print result
remove_chars("hello","he")
| true
|
82ecc3e32e7940422238046cd7aa788979c51f9c
|
KurinchiMalar/DataStructures
|
/Stacks/Stack.py
| 1,115
| 4.125
| 4
|
from LinkedLists.ListNode import ListNode
class Stack:
def __init__(self,head=None):
self.head = head
self.size = 0
def push(self,data):
newnode = ListNode(data)
newnode.set_next(self.head)
self.head = newnode
self.size = self.size + 1
def pop(self):
if self.head is None:
print "Nothing to pop. Stack is empty!"
return -1
toremove = self.head
self.head = self.head.get_next()
self.size = self.size - 1
return toremove
def peek(self):
if self.head is None:
print "Nothing to peek!. Stack is empty!"
return -1
return self.head.get_data()
def print_stack(self):
current = self.head
while current != None:
print current.get_data(),
current = current.get_next()
print
'''
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
stack.push(6)
stack.print_stack()
stack.pop()
stack.print_stack()
print stack.size
print "top: "+str(stack.peek())
print stack.size
'''
| true
|
98783f5bfd44ae9259f05242baaac5ff796008e5
|
KurinchiMalar/DataStructures
|
/Searching/SeparateOddAndEven.py
| 799
| 4.25
| 4
|
'''
Given an array A[], write a function that segregates even and odd numbers.
The functions should put all even numbers first and then odd numbers.
'''
# Time Complexity : O(n)
def separate_even_odd(Ar):
even_ptr = 0
odd_ptr = len(Ar)-1
while even_ptr < odd_ptr:
while even_ptr < odd_ptr and Ar[even_ptr] % 2 == 0:
even_ptr = even_ptr + 1
while even_ptr < odd_ptr and Ar[odd_ptr] % 2 == 1:
odd_ptr = odd_ptr -1
# now odd and even are positioned appropriately.
#if Ar[odd_ptr] % 2 == 0 and Ar[even_ptr] % 2 == 1:
Ar[odd_ptr],Ar[even_ptr] = Ar[even_ptr],Ar[odd_ptr]
odd_ptr = odd_ptr-1
even_ptr = even_ptr+1
return Ar
Ar = [12,34,45,9,8,90,3]
#Ar = [1,2]
print ""+str(separate_even_odd(Ar))
| false
|
30a81157968dcd8771db16cf6ac48e9cd235d713
|
KurinchiMalar/DataStructures
|
/Stacks/InfixToPostfix.py
| 2,664
| 4.28125
| 4
|
'''
Consider an infix expression : A * B - (C + D) + E
and convert to postfix
the postfix expression : AB * CD + - E +
Algorithm:
1) if operand
just add to result
2) if (
push to stack
3) if )
till a ( is encountered, pop from stack and append to result.
4) if operator
if top of stack has higher precedence
pop from stack and append to result
push the current operator to stack
else
push the current operator to stack
'''
# Time Complexity : O(n)
# Space Complexity : O(n)
import Stack
def get_precedence_map():
prec_map = {}
prec_map["*"] = 3
prec_map["/"] = 3
prec_map["+"] = 2
prec_map["-"] = 2
prec_map["("] = 1
return prec_map
def convert_infix_to_postfix(infix):
if infix is None:
return None
prec_map = get_precedence_map()
#print prec_map
opstack = Stack.Stack()
result_postfix = []
for item in infix:
print "--------------------------item: "+str(item)
# if operand just add it to result
if item in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or item in "0123456789":
print "appending: "+str(item)
result_postfix.append(item)
opstack.print_stack()
# if "(" just push it to stack
elif item == "(":
opstack.push(item)
opstack.print_stack()
# add to result upto open brace
elif item == ")":
top_elem = opstack.pop()
while top_elem.get_data() != "(" and opstack.size > 0:
print "appending: "+str(top_elem.get_data())
result_postfix.append(top_elem.get_data())
top_elem = opstack.pop()
opstack.print_stack()
#result_postfix.append(top_elem) # no need to append paranthesis in result.
else:
# should be an operator
while opstack.size > 0 and prec_map[opstack.peek()] >= prec_map[item]:
temp = opstack.pop()
print "appending: "+str(temp.get_data())
result_postfix.append(temp.get_data())
opstack.push(item) # after popping existing operator , push the current one. (or) without popping just push. based on the precedence check.
opstack.print_stack()
#print result_postfix
while opstack.size != 0:
result_postfix.append(opstack.pop().get_data())
return result_postfix
infixstring = "A*B-(C+D)+E"
infix = list(infixstring)
postfix = convert_infix_to_postfix(infix)
postfix = "".join(postfix)
print "Postfix for :"+str(infixstring)+" is : "+str(postfix)
| true
|
22f1d817b2d292a4b3fae09a77e3013b9d45bd31
|
KurinchiMalar/DataStructures
|
/Sorting/NearlySorted_MergeSort.py
| 1,528
| 4.125
| 4
|
#Complexity O(n/k * klogk) = O(nlogk)
# merging k elements using mergesort = klogk
# every n/k elem group is given to mergesort
# Hence totally O(nlogk)
'''
k = 3
4 5 9 | 7 8 3 | 1 2 6
1st merge sort all blocks
4 5 9 | 3 8 9 | 1 2 6
Time Complexity = O(n * (n/k) log k)
i.e to sort k numbers is k * log k
to sort n/k such blocks = (n/k) * k log k = n log k
2nd start merging two blocks at a time
i.e
to merge k + k elements 2k log k
to merge 2k + k elements 3k log k
similarly it has to proceed until qk + k = n, so it becomes n log k
where q = (n/k) - 1
'''
from MergeSort import mergesort
def split_into_groups_of_size_k(Ar,k):
r = []
for j in range(0,(len(Ar)/k)+1):
start = k * j
end = start + k
if start >= len(Ar):
break
if end >=len(Ar) and start < len(Ar):
r.append(Ar[start:end])
break
#print "start,end = "+str(start)+","+str(end)
r.append( Ar[start:end])
#print r[j]
return r
def merge_two_lists(list1,list2):
list1.extend(list2)
return list1
Ar = [6,9,10,1,2,3,5]
Ar = [8,9,10,1,2,3,6,7]
Ar = [8,9,10,1,2,3]
print Ar
split_blocks = split_into_groups_of_size_k(Ar,3)
print str(split_blocks)
for i in range(0,len(split_blocks)):
mergesort(split_blocks[i])
print "Sorted blocks:" +str(split_blocks)
while len(split_blocks) > 1 :
split_blocks[1] = merge_two_lists(split_blocks[0],split_blocks[1])
split_blocks.pop(0)
mergesort(split_blocks[0])
print str(split_blocks)
| false
|
6d878bd6ab1e0dbecb0c2a5a2803ee41359b51b8
|
KurinchiMalar/DataStructures
|
/LinkedLists/MergeZigZagTwoLists.py
| 2,040
| 4.15625
| 4
|
'''
Given two lists
list1 = [A1,A2,.....,An]
list2 = [B1,B2,....,Bn]
merge these two into a third list
result = [A1 B1 A2 B2 A3 ....]
'''
# Time Complexity : O(n)
# Space Complexity : O(1)
import ListNode
import copy
def merge_zigzag(node1,node2,m,n):
if node1 == None or node2 == None:
return node1 or node2
p = node1
q = p.get_next()
r = node2
s = r.get_next()
while q != None and s != None:
p.set_next(r)
r.set_next(q)
p = q
if q != None:
q = q.get_next()
r = s
if s != None:
s = s.get_next()
if q == None:
p.set_next(r)
if s == None:
p.set_next(r)
r.set_next(q)
return node1
def get_len_of_list(node):
current = node
count = 0
while current != None:
#print current.get_data(),
count = count + 1
current = current.get_next()
#print
return count
def traverse_list(node):
current = node
count = 0
while current != None:
print current.get_data(),
count = count + 1
current = current.get_next()
print
head1 = ListNode.ListNode(1)
#print ListNode.ListNode.__str__(head)
n1 = ListNode.ListNode(3)
n2 = ListNode.ListNode(5)
n3 = ListNode.ListNode(7)
n4 = ListNode.ListNode(9)
n5 = ListNode.ListNode(10)
n6 = ListNode.ListNode(12)
head2 = ListNode.ListNode(2)
m1 = ListNode.ListNode(4)
m2 = ListNode.ListNode(6)
m3 = ListNode.ListNode(8)
m4 = ListNode.ListNode(11)
m5 = ListNode.ListNode(14)
m6 = ListNode.ListNode(19)
head1.set_next(n1)
n1.set_next(n2)
n2.set_next(n3)
n3.set_next(n4)
n4.set_next(n5)
n5.set_next(n6)
head2.set_next(m1)
m1.set_next(m2)
m2.set_next(m3)
m3.set_next(m4)
m4.set_next(m5)
m5.set_next(m6)
orig_head1 = copy.deepcopy(head1)
orig_head2 = copy.deepcopy(head2)
traverse_list(head1)
traverse_list(head2)
m = get_len_of_list(head1)
n = get_len_of_list(head2)
result = merge_zigzag(head1,head2,m,n)
print "RESULT:"
traverse_list(result)
| false
|
4277a08cf47b4f91712841ef2e3757a49090650f
|
IStealYourSkill/python
|
/les3/3_3.py
| 579
| 4.28125
| 4
|
'''3. Проверить, что хотя бы одно из чисел a или b оканчивается на 0.'''
a = int(input('Введите число A: '))
b = int(input('Введите число B: '))
if ((a >= 10) or (b >= 10)) and (a % 10 == 0 or b % 10 == 0):
print("Одно из чисел оканчивается на 0")
else:
print("Числа {}, {} без нулей".format(a, b))
'''
if (10 <= a <= -10) and (a % 10 == 0):
print("ноль, естЬ! {}".format(a))
else:
print("Без нулей {}".format(a))
'''
| false
|
08ef8703147476759e224e66efdc7b5de5addf6e
|
chaoma1988/Coursera_Python_Program_Essentials
|
/days_between.py
| 1,076
| 4.65625
| 5
|
'''
Problem 3: Computing the number of days between two dates
Now that we have a way to check if a given date is valid,
you will write a function called days_between that takes six integers (year1, month1, day1, year2, month2, day2)
and returns the number of days from an earlier date (year1-month1-day1) to a later date (year2-month2-day2).
If either date is invalid, the function should return 0. Notice that you already wrote a
function to determine if a date is valid or not! If the second date is earlier than the first date,
the function should also return 0.
'''
import datetime
from is_valid_date import is_valid_date
def days_between(year1,month1,day1,year2,month2,day2):
if is_valid_date(year1,month1,day1):
date1 = datetime.date(year1,month1,day1)
else:
return 0
if is_valid_date(year2,month2,day2):
date2 = datetime.date(year2,month2,day2)
else:
return 0
delta = date2 - date1
if delta.days <= 0:
return 0
else:
return delta.days
# Testing
#print(days_between(1988,7,19,2018,7,3))
| true
|
562ac5cebcf516d7e40724d3594186209d79c2f4
|
Vyara/First-Python-Programs
|
/quadratic.py
| 695
| 4.3125
| 4
|
# File: quadratic.py
# A program that uses the quadratic formula to find real roots of a quadratic equation.
def main():
print "This program finds real roots of a quadratic equation ax^2+bx+c=0."
a = input("Type in a value for 'a' and press Enter: ")
b = input("Type in a value for 'b' and press Enter: ")
c = input("Type in a value for 'c' and press Enter: ")
d = (b**2.0 - (4.0 * a * c))
if d < 0:
print "No real roots"
else:
root_1 = (-b + d**0.5) / (2.0 * a)
root_2 = (-b - d**0.5) / (2.0 * a)
print "The answers are:", root_1, "and", root_2
raw_input("Press Enter to exit.")
main()
| true
|
852cba828e67b97d2ddd91322a827bfdc3c6a849
|
ridhamaditi/tops
|
/Assignments/Module(1)-function&method/b1.py
| 287
| 4.3125
| 4
|
#Write a Python function to calculate the factorial of a number (a non-negative integer)
def fac(n):
fact=1
for i in range(1,n+1):
fact *= i
print("Fact: ",fact)
try:
n=int(input("Enter non-negative number: "))
if n<0 :
print("Error")
else:
fac(n)
except:
print("Error")
| true
|
287f5f10e5cc7c1e40e545d958c54c8d01586bfb
|
ridhamaditi/tops
|
/Assignments/Module(1)-Exception Handling/a2.py
| 252
| 4.15625
| 4
|
#write program that will ask the user to enter a number until they guess a stored number correctly
a=10
try:
n=int(input("Enter number: "))
while a!=n :
print("Enter again")
n=int(input("Enter number: "))
print("Yay")
except:
print("Error")
| true
|
e3eca8bce227d8d6c6b4526189945c2cd79e0c41
|
ridhamaditi/tops
|
/functions/prime.py
| 234
| 4.1875
| 4
|
def isprime(n,i=2):
if n <= 2:
return True
elif n % i == 0:
return False
elif i*i > n:
return True
else:
return isprime(n,i+1)
n=int(input("Enter No: "))
j=isprime(n)
if j==True:
print("Prime")
else:
print("Not prime")
| false
|
bcc1edf1be77b38dff101b8221497dc5baa3f2ec
|
ridhamaditi/tops
|
/modules/math_sphere.py
| 237
| 4.15625
| 4
|
import math
print("Enter radius: ")
try:
r = float(input())
area = math.pi * math.pow(r, 2)
volume = math.pi * (4.0/3.0) * math.pow(r, 3)
print("\nArea:", area)
print("\nVolume:", volume)
except ValueError:
print("Invalid Input.")
| false
|
1d2389112a628dbf8891f85d6606ec44543fc81d
|
ridhamaditi/tops
|
/Assignments/Module(1)-Exception Handling/a4.py
| 791
| 4.21875
| 4
|
#Write program that except Clause with No Exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
# user guesses a number until he/she gets it right
number = 10
while True:
try:
inum = int(input("Enter a number: "))
if inum < number:
raise ValueTooSmallError
elif inum > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
except ValueTooLargeError:
print("This value is too large, try again!")
print("Congratulations! You guessed it correctly.")
| true
|
609812d3b68a77f35eb116682df3f844ab3a44c9
|
ridhamaditi/tops
|
/Assignments/Module(1)-Exception Handling/a3.py
| 216
| 4.15625
| 4
|
#Write function that converts a temperature from degrees Kelvin to degrees Fahrenheit
try:
k=int(input("Enter temp in Kelvin: "))
f=(k - 273.15) * 9/5 + 32
print("Temp in Fahrenheit: ",f)
except:
print("Error")
| true
|
35c340635b063ecebc478a1ab8d7f527d6fe2f3f
|
Swapnil2095/Python
|
/8.Libraries and Functions/copy in Python (Deep Copy and Shallow Copy)/Shallow copy/shallow copy.py
| 533
| 4.5625
| 5
|
# Python code to demonstrate copy operations
# importing "copy" for copy operations
import copy
# initializing list 1
li1 = [1, 2, [3, 5], 4]
# using copy to shallow copy
li2 = copy.copy(li1)
# original elements of list
print("The original elements before shallow copying")
for i in range(0, len(li1)):
print(li1[i], end=" ")
print("\r")
# adding and element to new list
li2[2][0] = 7
# checking if change is reflected
print("The original elements after shallow copying")
for i in range(0, len(li1)):
print(li1[i], end=" ")
| true
|
b91b8609d687dd362ac271c349fdc3c81ebfe0f3
|
Swapnil2095/Python
|
/8.Libraries and Functions/Regular Expression/findall(d).py
| 621
| 4.3125
| 4
|
import re
# \d is equivalent to [0-9].
p = re.compile('\d')
print(p.findall("I went to him at 11 A.M. on 4th July 1886"))
# \d+ will match a group on [0-9], group of one or greater size
p = re.compile('\d+')
print(p.findall("I went to him at 11 A.M. on 4th July 1886"))
'''
\d Matches any decimal digit, this is equivalent
to the set class [0-9].
\D Matches any non-digit character.
\s Matches any whitespace character.
\S Matches any non-whitespace character
\w Matches any alphanumeric character, this is
equivalent to the class [a-zA-Z0-9_].
\W Matches any non-alphanumeric character.
'''
| true
|
2be154a4143a049477f827c9923ba19198f4a4e3
|
Swapnil2095/Python
|
/8.Libraries and Functions/copyreg — Register pickle support functions/Example.py
| 1,312
| 4.46875
| 4
|
# Python 3 program to illustrate
# use of copyreg module
import copyreg
import copy
import pickle
class C(object):
def __init__(self, a):
self.a = a
def pickle_c(c):
print("pickling a C instance...")
return C, (c.a, )
copyreg.pickle(C, pickle_c)
c = C(1)
d = copy.copy(c)
print(d)
p = pickle.dumps(c)
print(p)
'''
The copyreg module defines functions which are used by pickling specific objects
while pickling or copying. This module provides configuration information
about object constructors(may be factory functions or class instances)
which are not classes.
copyreg.constructor(object)
This function is used for declaring object as a valid constructor.
An object is not considered as a valid constructor if it is not callable.
This function raises TypeError if the object is not callable.
copyreg.pickle(type, function, constructor=None)
This is used to declare function as a “reduction” function for objects of type type.
function should return either a string or a tuple containing two or three elements.
The constructor parameter is optional. It is a callable object which can be used
to reconstruct the object when called with the tuple of arguments returned by
function at pickling time. TypeError is raised if object is a class or
constructor is not callable.
'''
| true
|
3dc8226bfc786cf6bbea43a20a0cf5dbbdeeb72e
|
Swapnil2095/Python
|
/5. Modules/Mathematical Functions/sqrt.py
| 336
| 4.5625
| 5
|
# Python code to demonstrate the working of
# pow() and sqrt()
# importing "math" for mathematical operations
import math
# returning the value of 3**2
print("The value of 3 to the power 2 is : ", end="")
print(math.pow(3, 2))
# returning the square root of 25
print("The value of square root of 25 : ", end="")
print(math.sqrt(25))
| true
|
1ca59efae74f5829e15ced1f428720e696867d9a
|
Swapnil2095/Python
|
/2.Operator/Inplace vs Standard/mutable_target.py
| 849
| 4.28125
| 4
|
# Python code to demonstrate difference between
# Inplace and Normal operators in mutable Targets
# importing operator to handle operator operations
import operator
# Initializing list
a = [1, 2, 4, 5]
# using add() to add the arguments passed
z = operator.add(a,[1, 2, 3])
# printing the modified value
print ("Value after adding using normal operator : ",end="")
print (z)
# printing value of first argument
# value is unchanged
print ("Value of first argument using normal operator : ",end="")
print (a)
# using iadd() to add the arguments passed
# performs a+=[1, 2, 3]
p = operator.iadd(a,[1, 2, 3])
# printing the modified value
print ("Value after adding using Inplace operator : ",end="")
print (p)
# printing value of first argument
# value is changed
print ("Value of first argument using Inplace operator : ",end="")
print (a)
| true
|
7ffe6b1ac7437b0477a969498d66163e4c4e0584
|
Swapnil2095/Python
|
/5. Modules/Time Functions/ctime.py
| 450
| 4.15625
| 4
|
# Python code to demonstrate the working of
# asctime() and ctime()
# importing "time" module for time operations
import time
# initializing time using gmtime()
ti = time.gmtime()
# using asctime() to display time acc. to time mentioned
print ("Time calculated using asctime() is : ",end="")
print (time.asctime(ti))
# using ctime() to diplay time string using seconds
print ("Time calculated using ctime() is : ", end="")
print (time.ctime())
| true
|
9091de76643f812c44e1760f7d73e2a28c19bde6
|
Swapnil2095/Python
|
/8.Libraries and Functions/enum/prop2.py
| 724
| 4.59375
| 5
|
'''
4. Enumerations are iterable. They can be iterated using loops
5. Enumerations support hashing. Enums can be used in dictionaries or sets.
'''
# Python code to demonstrate enumerations
# iterations and hashing
# importing enum for enumerations
import enum
# creating enumerations using class
class Animal(enum.Enum):
dog = 1
cat = 2
lion = 3
# printing all enum members using loop
print("All the enum values are : ")
for Anim in (Animal):
print(Anim)
# Hashing enum member as dictionary
di = {}
di[Animal.dog] = 'bark'
di[Animal.lion] = 'roar'
# checking if enum values are hashed successfully
if di == {Animal.dog: 'bark', Animal.lion: 'roar'}:
print("Enum is hashed")
else:
print("Enum is not hashed")
| true
|
f0a0f758c7e274508da794d35c71c52f7da7e0f9
|
Swapnil2095/Python
|
/5. Modules/Calendar Functions/firstweekday.py
| 486
| 4.25
| 4
|
# Python code to demonstrate the working of
# prmonth() and setfirstweekday()
# importing calendar module for calendar operations
import calendar
# using prmonth() to print calendar of 1997
print("The 4th month of 1997 is : ")
calendar.prmonth(1997, 4, 2, 1)
# using setfirstweekday() to set first week day number
calendar.setfirstweekday(4)
print("\r")
# using firstweekday() to check the changed day
print("The new week day number is : ", end="")
print(calendar.firstweekday())
| true
|
f60dcd5c7b7cc667b9e0155b722fd637570663ef
|
Swapnil2095/Python
|
/8.Libraries and Functions/Decimal Functions/logical.py
| 1,341
| 4.65625
| 5
|
# Python code to demonstrate the working of
# logical_and(), logical_or(), logical_xor()
# and logical_invert()
# importing "decimal" module to use decimal functions
import decimal
# Initializing decimal number
a = decimal.Decimal(1000)
# Initializing decimal number
b = decimal.Decimal(1110)
# printing logical_and of two numbers
print ("The logical_and() of two numbers is : ",end="")
print (a.logical_and(b))
# printing logical_or of two numbers
print ("The logical_or() of two numbers is : ",end="")
print (a.logical_or(b))
# printing exclusive or of two numbers
print ("The exclusive or of two numbers is : ",end="")
print (a.logical_xor(b))
# printing logical inversion of number
print ("The logical inversion of number is : ",end="")
print (a.logical_invert())
'''
1. logical_and() :- This function computes digit-wise logical “and” operation of the number. Digits can only have the values 0 or 1.
2. logical_or() :- This function computes digit-wise logical “or” operation of the number. Digits can only have the values 0 or 1.
3. logical_xor() :- This function computes digit-wise logical “xor” operation of the number. Digits can only have the values 0 or 1.
4. logical_invert() :- This function computes digit-wise logical “invert” operation of the number. Digits can only have the values 0 or 1.
'''
| true
|
95a5a87944d4bff8b2e1b03a939d0277cd150fe1
|
Swapnil2095/Python
|
/3.Control Flow/Using Iterations/unzip.py
| 248
| 4.1875
| 4
|
# Python program to demonstrate unzip (reverse
# of zip)using * with zip function
# Unzip lists
l1,l2 = zip(*[('Aston', 'GPS'),
('Audi', 'Car Repair'),
('McLaren', 'Dolby sound kit')
])
# Printing unzipped lists
print(l1)
print(l2)
| true
|
9aebe2939010ff4b2eca5edf8f25dfc5362828c6
|
Swapnil2095/Python
|
/5. Modules/Complex Numbers/sin.py
| 593
| 4.21875
| 4
|
# Python code to demonstrate the working of
# sin(), cos(), tan()
# importing "cmath" for complex number operations
import cmath
# Initializing real numbers
x = 1.0
y = 1.0
# converting x and y into complex number z
z = complex(x, y)
# printing sine of the complex number
print("The sine value of complex number is : ", end="")
print(cmath.sin(z))
# printing cosine of the complex number
print("The cosine value of complex number is : ", end="")
print(cmath.cos(z))
# printing tangent of the complex number
print("The tangent value of complex number is : ", end="")
print(cmath.tan(z))
| true
|
e7d09d8d38f4df4f2221ba3963b53467cef66cfb
|
bregman-arie/python-exercises
|
/solutions/lists/running_sum/solution.py
| 659
| 4.25
| 4
|
#!/usr/bin/env python
from typing import List
def running_sum(nums_li: List[int]) -> List[int]:
"""Returns the running sum of a given list of numbers
Args:
nums_li (list): a list of numbers.
Returns:
list: The running sum list of the given list
[1, 5, 6, 2] would return [1, 6, 12, 14]
Time Complexity: O(n)
Space Complexity: O(n)
"""
for i in range(1, len(nums_li)):
nums_li[i] += nums_li[i - 1]
return nums_li
if __name__ == '__main__':
nums_str = input("Insert numbers (e.g. 1 5 1 6): ")
nums_li = [int(i) for i in nums_str.split()]
print(running_sum(list(nums_li)))
| true
|
9a3ecfad05a80abe490885249fb761a0ca77afb6
|
milenamonteiro/learning-python
|
/exercises/radiuscircle.py
| 225
| 4.28125
| 4
|
"""Write a Python program which accepts the radius of a circle from the user and compute the area."""
import math
RADIUS = float(input("What's the radius? "))
print("The area is {0}".format(math.pi * math.pow(RADIUS, 2)))
| true
|
4ad91e1cd661f5b7ce3b6c0960cb022136275e0a
|
testergitgitowy/calendar-checker
|
/main.py
| 2,618
| 4.15625
| 4
|
import datetime
import calendar
def name(decision):
print("Type period of time (in years): ", end = "")
while True:
try:
period = abs(int(input()))
except:
print("Must be an integer (number). Try again: ", end = "")
else:
break
period *= 12
print("Type the day you want to check for (1-Monday, 7-Sunday")
while True:
try:
choosed_day = int(input())
if 1 <= choosed_day <= 7:
break
else:
print("Wrong number. Pass an integer in range (1-7): ", end = "")
except:
print("Must be an integer in range (1-7). Type again: ", end = "")
day = datetime.date.today().day
month = datetime.date.today().month
year = datetime.date.today().year
startdate=datetime.datetime(year, month, day)
d = startdate
match_amount = 0
month_amount = 0
control = 0
while(period > 0):
period -= 1
if d.weekday() == choosed_day - 1:
if control == 0 and decision == 1:
print("Month's found: ")
control = 1
if control == 0 and decision == 0:
control = 1
match_amount += 1
if decision == 1:
print(calendar.month(d.year,d.month))
if d.month != 1:
month1 = d.month - 1
d = d.replace (month = month1)
month_amount += 1
else:
year1 = d.year - 1
d = d.replace (month = 12, year = year1)
month_amount += 1
diff = abs(d - startdate)
elif d.month != 1:
month1 = d.month - 1
d = d.replace (month = month1)
month_amount += 1
else:
year1 = d.year - 1
month1 = 12
d = d.replace (month = month1, year = year1)
month_amount += 1
if control == 0:
print("No matching were found.\nProbability: 0\nProbability expected: ", 1/7)
else:
print("Number of months found: ", match_amount)
print("Number of months checked: ", month_amount)
print("Number of days: ", diff.days)
print("Probability found: ", match_amount/month_amount)
print("Probability expected: ", 1/7)
if decision == 1:
print("Range of research:\nStarting month:")
print(calendar.month(startdate.year, startdate.month))
print("Final month:",)
print(calendar.month(d.year, d.month))
print("Do you want to print out all of founded months?: [1/y][n/0]", end = " ")
true = ['1','y','Y','yes','YES','YEs','YeS','Yes','ye','Ye','YE']
false = ['0','no','NO','nO','No','n','N']
while True:
decision = input()
if decision in true:
decision = 1
break
elif decision in false:
decision = 0
break
else:
print("Wrong input. Try again: ")
name(decision)
| true
|
f1579f18820ec92be33bbf194db207d4b8678b89
|
nonelikeanyone/Robotics-Automation-QSTP-2021
|
/Week_1/exercise.py
| 717
| 4.1875
| 4
|
import math
def polar2cart(R,theta):
#function for coonverting polar coordinates to cartesian
print('New Coordinates: ', R*math.cos(theta), R*math.sin(theta))
def cart2polar(x,y):
#function for coonverting cartesian coordinates to polar
print('New Coordinates: ', (x**2+y**2)**(0.5), math.atan(y/x))
print('Convert Coordinates')
print('Polar to Cartesian? Put 1. Cartesian to Polar? Put 2.')
ip=int(input('Your wish: ')) #prompt user for input
if ip==1:
#if user enters 1, execute this block
R=int(input('Enter R= '))
theta=(input('Enter theta in radians= '))
polar2cart(R,theta)
else:
#if user does not enter 1, execute this block
x=int(input('Enter x= '))
y=int(input('Enter y= '))
cart2polar(x,y)
| false
|
07fa76c6a9fcbc33d34229f1e62c27e22ec93365
|
juanperdomolol/Dominio-python
|
/ejercicio15.py
| 595
| 4.1875
| 4
|
#Capitalización compuesta
#Crear una aplicación que trabaje con la ley de capitalización compuesta.
#La capitalización compuesta es una operación financiera que proyecta un capital a un período futuro,
# donde los intereses se van acumulando al capital para los períodos subsiguientes.
capitalInicial= float(input("Cual es el capital dispuesto a Capitalización compuesta "))
interes = float(input("Cual es el interes anual? "))
años = int(input("A cuantos años se proyecta el capital "))
porcentaje= interes/100
resultado = capitalInicial*((1+porcentaje)**años)
print(resultado)
| false
|
a57504d5e5dd34e53a3e30b2e0987ae6314d6077
|
MattCoston/Python
|
/shoppinglist.py
| 298
| 4.15625
| 4
|
shopping_list = []
print ("What do you need to get at the store?")
print ("Enter 'DONE' to end the program")
while True:
new_item = input("> ")
shopping_list.append(new_item)
if new_item == 'DONE':
break
print("Here's the list:")
for item in shopping_list:
print(item)
| true
|
96aa4c549c9a5341a565699832cdbbf30ff406e7
|
liweinan/hands_on_ml
|
/sort_class.py
| 982
| 4.125
| 4
|
from collections import OrderedDict
class Student:
def __init__(self, name, order):
self.name = name
self.order = order
tom = Student("Tom", 0)
jack = Student("Jack", 0)
rose = Student("Rose", 1)
lucy = Student("Lucy", 2)
users = OrderedDict()
users[rose.name] = rose
users[lucy.name] = lucy
users[jack.name] = jack
users[tom.name] = tom
# 接下来是转化users,让order变成key,然后让value是student数组
users2 = OrderedDict()
for k, v in users.items():
if v.order not in users2.keys():
users2[v.order] = []
users2[v.order].append(v)
# 然后是sort这个数组,生成一个新的dict:
sorted_users = OrderedDict()
sorted_keys = sorted(users2)
for k in sorted_keys:
for v in users2[k]:
print(str(v.order) + ", " + v.name)
sorted_users[v.name] = v
# 这样,我们就得到了sorted_users:
print("-=-=-=-=-=-=-=-=-=-=-=-=-=-")
for k, v in sorted_users.items():
print(str(v.order) + ", " + k)
| false
|
4de4ba9a0b6507c01147f52527413bfbf0305982
|
ferdirn/hello-python
|
/ternaryoperator.py
| 231
| 4.1875
| 4
|
#!/usr/bin/env python
a = 1
b = 2
print 'a = ', a
print 'b = ', b
print '\n'
#ternary operator
print 'Ternary operator #1'
print 'a > b' if (a > b) else 'b > a'
print '\nTernary operator #2'
print (a > b) and 'a > b' or 'b > a'
| false
|
c3bc1f9db4fd2ab9b4ba40ce7e8d69b0da87fd42
|
lior20-meet/meet2018y1lab2
|
/MEETinTurtle.py
| 972
| 4.15625
| 4
|
import turtle
turtle.penup() #Pick up the pen so it doesn’t
#draw
turtle.goto(-200,-100) #Move the turtle to the
#position (-200, -100)
#on the screen
turtle.pendown() #Put the pen down to start
#drawing
#Draw the M:
turtle.goto(-200,-100+200)
turtle.goto(-200+50,-100)
turtle.goto(-200+100,-100+200)
turtle.goto(-200+100,-100)
turtle.penup()
turtle.goto (-50,100)
turtle.pendown()
turtle.goto(-50,-100)
turtle.goto(50,-100)
turtle.penup()
turtle.goto(-50,100)
turtle.pendown()
turtle.goto(50,100)
turtle.penup()
turtle.goto(-50,0)
turtle.pendown()
turtle.goto(50,0)
turtle.penup()
turtle.goto(100,100)
turtle.pendown()
turtle.goto(100,-100)
turtle.goto(200,-100)
turtle.penup()
turtle.goto(100,100)
turtle.pendown()
turtle.goto(200,100)
turtle.penup()
turtle.goto(100,0)
turtle.pendown()
turtle.goto(200,0)
turtle.penup()
turtle.goto(250,100)
turtle.pendown()
turtle.goto(350,100)
turtle.goto(300,100)
turtle.goto(300,-100)
| false
|
7235257c51e5a1af67454306e76c5e58ffd2a31c
|
VeronikaA/user-signup
|
/crypto/helpers.py
| 1,345
| 4.28125
| 4
|
import string
# helper function 1, returns numerical key of letter input by user
def alphabet_position(letter):
""" Creates key by receiving a letter and returning the 0-based numerical position of that letter in the alphabet, regardless of case."""
alphabet = string.ascii_lowercase + string.ascii_uppercase
alphabet1 = string.ascii_lowercase
alphabet2 = string.ascii_uppercase
i = 0
for c in alphabet:
key = 0
c = letter
if c in alphabet1:
ascii_value = ord(c)
c = ascii_value
key = (c - 97) % 26
elif c in alphabet2:
ascii_value = ord(c)
c = ascii_value
key = (c - 65) % 26
elif c not in alphabet:
key = ord(c)
return key
# helper funtion 2
def rotate_character(char, rot):
"""Receives a character 'char', and an integer 'rot'.
Returns a new char, the result of rotating char by rot number of places to the right."""
a = char
a = alphabet_position(a)
rotation = (a + rot) % 26
if char in string.ascii_lowercase:
new_char = rotation + 97
rotation = chr(new_char)
elif char in string.ascii_uppercase:
new_char = rotation + 65
rotation = chr(new_char)
elif char == char:
rotation = char
return rotation
| true
|
f7c61b747436cfcd105a925edd695ac3c8d97279
|
ksheetal/python-codes
|
/hanoi.py
| 654
| 4.1875
| 4
|
def hanoi(n,source,spare,target):
'''
objective : To build tower of hanoi using n number of disks and 3 poles
input parameters :
n -> no of disks
source : starting position of disk
spare : auxillary position of the disk
target : end position of the disk
'''
#approach : call hanoi function recursively to move disk from one pole to another
assert n>0
if n==1:
print('Move disk from ',source,' to ',target)
else:
hanoi(n-1,source,target,spare)
print('Move disk from ',source,' to ',target)
hanoi(n-1,spare,source,target)
| true
|
de64db2e733e592558b5459e7fb4fcfd695abd1b
|
moogzy/MIT-6.00.1x-Files
|
/w2-pset1-alphabetic-strings.py
| 1,220
| 4.125
| 4
|
#!/usr/bin/python
"""
Find longest alphabetical order substring in a given string.
Author: Adrian Arumugam (apa@moogzy.net)
Date: 2018-01-27
MIT 6.00.1x
"""
s = 'azcbobobegghakl'
currloc = 0
substr = ''
sublist = []
strend = len(s)
# Process the string while the current slice location is less then the length of the string.
while currloc < strend:
# Append the character from the current location to the substring.
substr += s[currloc]
# Our base case to ensure we don't try to access invalid string slice locations.
# If current location is equal to the actual length of the string then increment
# the current location counter and append the substring to our list.
if currloc == strend - 1:
currloc += 1
sublist.append(substr)
# Continute processing the substring as we've still got slices in alphabetical order.
elif s[currloc+1] >= s[currloc]:
currloc += 1
# Current slice location broken the alphabetical order requirement.
# Append the current substring to our list, reset to an empty substring and increment the current location.
else:
sublist.append(substr)
substr = ''
currloc += 1
print("Longest substring in alphabetical order is: {}".format(max(sublist, key=len)))
| true
|
27ebcf2e51a5a9184d718ad14097aba5fb714d94
|
tanawitpat/python-playground
|
/zhiwehu_programming_exercise/exercise/Q006.py
| 1,421
| 4.28125
| 4
|
import unittest
'''
Question 6
Level 2
Question:
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example
Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24
Hints:
If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26)
In case of input data being supplied to the question, it should be assumed to be a console input.
'''
def logic(input_string):
c = 50
h = 30
input_list = input_string.split(",")
output_list = []
output_string = ""
for d in input_list:
output_list.append(str(int((2*c*int(d)/h)**0.5)))
for i in range(len(output_list)):
if i == 0:
output_string = output_string+output_list[i]
else:
output_string = output_string+","+output_list[i]
return output_string
class TestLogic(unittest.TestCase):
def test_logic(self):
self.assertEqual(
logic("100,150,180"),
"18,22,24",
"Should be `18,22,24`")
if __name__ == '__main__':
unittest.main()
| true
|
cb3fb384955f9767077db0d80a5b1374c82c1674
|
BurnFaithful/KW
|
/Programming_Practice/Python/Base/Bigdata_day1001/Input05.py
| 304
| 4.1875
| 4
|
# 문자열은 인덱스 번호가 부여됨
strTemp = input("아무 문자열이나 입력하세요: ")
print("strTemp : ", strTemp)
print("strTemp : {}".format(strTemp))
print("strTemp[0] : {}".format(strTemp[0]))
print("strTemp[1] : {}".format(strTemp[1]))
print("strTemp[2] : {}".format(strTemp[2]))
| false
|
a5d8b66c92ada51e44ca70d2596a30f0da6f7482
|
jmlippincott/practice_python
|
/src/16_password_generator.py
| 639
| 4.1875
| 4
|
# Write a password generator in Python. Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The passwords should be random, generating a new password every time the user asks for a new password. Include your run-time code in a main method.
import random, string
chars = string.ascii_letters + string.digits + string.punctuation
def generate(length):
psswd = "".join(random.choice(chars) for i in range(length))
return psswd
while True:
num = input("How long would you like your new password? ")
num = int(num)
print(generate(num))
| true
|
9d057f9b4c79e82df90153757e7797f593adb009
|
TasosVellis/Zero
|
/8.Object Oriented Programming/4_OOPHomework.py
| 1,425
| 4.21875
| 4
|
import math
# Problem 1
#
# Fill in the Line class methods to accept coordinates as a
# pair of tuples and return the slope and distance of the line.
class Line:
"""
coordinate1 = (3,2)
coordinate2 = (8,10)
li = Line(coordinate1,coordinate2)
li.distance() = 9.433981132056603
li.slope() = 1.6
distance formula = square((x2-x1)^2 + (y2-y1)^2)
slope formula = y2-y1 / x2-x1
"""
def __init__(self, coor1, coor2):
self.coor1 = coor1
self.coor2 = coor2
def distance(self):
x1, y1 = self.coor1
x2, y2 = self.coor2
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def slope(self):
x1, y1 = self.coor1
x2, y2 = self.coor2
return (y2 - y1) / (x2 - x1)
coordinate1 = (3, 2)
coordinate2 = (8, 10)
li = Line(coordinate1, coordinate2)
print(li.distance())
print(li.slope())
# Problem 2
#
# Fill in the class
class Cylinder:
"""
c = Cylinder(2,3)
c.volume() = 56.52
c.surface_area() = 94.2
"""
pi = 3.14
def __init__(self, height=1, radius=1):
self.height = height
self.radius = radius
def volume(self):
return self.pi * self.radius ** 2 * self.height
def surface_area(self):
top_bottom = 2 * self.pi * self.radius**2
return top_bottom + 2 * self.pi * self.radius * self.height
c = Cylinder(2, 3)
print(c.volume())
print(c.surface_area())
| false
|
71fb6615811b40c8877b34456a98cdc34650dc92
|
arvimal/DataStructures-and-Algorithms-in-Python
|
/04-selection_sort-1.py
| 2,901
| 4.5
| 4
|
#!/usr/bin/env python3
# Selection Sort
# Example 1
# Selection Sort is a sorting algorithm used to sort a data set either in
# incremental or decremental order.
# How does Selection sort work?
# 1. Iterate through the data set one element at a time.
# 2. Find the biggest element in the data set (Append it to another if needed)
# 3. Reduce the sample space to `n - 1` by the biggest element just found.
# 4. Start the iteration over again, on the reduced sample space.
# 5. Continue till we have a sorted data set, either incremental or decremental
# How does the data sample reduces in each iteration?
# [10, 4, 9, 3, 6, 19, 8] - Data set
# [10, 4, 9, 3, 6, 8] - [19] - After Iteration 1
# [4, 9, 3, 6, 8] - [10, 19] - After Iteration 2
# [4, 3, 6, 8] - [9, 10, 19] - After Iteration 3
# [4, 3, 6] - [8, 9, 10, 19] - After Iteration 4
# [4, 3] - [6, 8, 9, 10, 19] - After Iteration 5
# [3] - [4, 6, 8, 9, 10, 19] - After Iteration 6
# [3, 4, 6, 8, 9, 10, 19] - After Iteration 7 - Sorted data set
# Let's check what the Selection Sort algorithm has to go through in each
# iteration
# [10, 4, 9, 3, 6, 19, 8] - Data set
# [10, 4, 9, 3, 6, 8] - After Iteration 1
# [4, 9, 3, 6, 8] - After Iteration 2
# [4, 3, 6, 8] - After Iteration 3
# [4, 3, 6] - After Iteration 4
# [4, 3] - After Iteration 5
# [3] - After Iteration 6
# [3, 4, 6, 8, 9, 10, 19] - After Iteration 7 - Sorted data set
# Observations:
# 1. It takes `n` iterations in each step to find the biggest element.
# 2. The next iteration has to run on a data set of `n - 1` elements.
# 3. Hence the total number of overall iterations would be:
# n + (n - 1) + (n - 2) + (n - 3) + ..... 3 + 2 + 1
# Since `Selection Sort` takes in `n` elements while starting, and goes through
# the data set `n` times (each step reducing the data set size by 1 member),
# the iterations would be:
# n + [ (n - 1) + (n - 2) + (n - 3) + (n - 4) + ... + 2 + 1 ]
# Efficiency:
# We are interested in the worse-case scenario.
# In a very large data set, an `n - 1`, `n - 2` etc.. won't make a difference.
# Hence, we can re-write the above iterations as:
# n + [n + n + n + n ..... n]
# Or also as:
# n x n = n**2
# O(n**2)
# Final thoughts:
# Selection Sort is an algorithm to sort a data set, but it is not particularly
# fast. For `n` elements in a sample space, Selection Sort takes `n x n`
# iterations to sort the data set.
def find_smallest(my_list):
smallest = my_list[0]
smallest_index = 0
for i in range(1, len(my_list)):
if my_list(i) < smallest:
smallest = my_list(i)
smallest_index = i
return smallest_index
def selection_sort(my_list):
new_list = []
for i in range(len(my_list)):
smallest = find_smallest(my_list)
new_list.append(my_list.pop(smallest))
return new_list
print(selection_sort([10, 12, 9, 4, 3, 6, 100]))
| true
|
a287c15b12ed3e3194c5aedac6b2fbb8adeb629b
|
gomgomigom/Exercise_2
|
/w_1-2/201210_4.py
| 2,013
| 4.125
| 4
|
# numbers라는 빈 리스트를 만들고 리스트를 출력한다.
# append를 이용해서 numbers에 1, 7, 3, 6, 5, 2, 13, 14를 순서대로 추가한다. 그 후 리스트를 출력한다.
# numbers 리스트의 원소들 중 홀수는 모두 제거한다. 그 후 다시 리스트를 출력한다.
# numbers 리스트의 인덱스 0 자리에 20이라는 수를 삽입한 후 출력한다.
# numbers 리스트를 정렬한 후 출력한다.
# 빈 리스트 만들기
numbers = []
print(numbers)
numbers.append(1)
numbers.append(7)
numbers.append(3)
numbers.append(6)
numbers.append(5)
numbers.append(2)
numbers.append(13)
numbers.append(14)
print(numbers)
# numbers에서 홀수 제거
i = 0
while i < len(numbers):
if numbers[i] % 2 == 1:
del numbers[i]
i -= 1
i += 1
print(numbers)
# numbers의 인덱스 0 자리에 20이라는 값 삽입
numbers.insert(0, 20)
print(numbers)
# numbers를 정렬해서 출력
numbers.sort()
print(numbers)
print(type(numbers))
for num in numbers:
print(num)
for x in range(2, 10, 2):
print(x)
numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
print(range(len(numbers)))
for num in range(len(numbers)):
print(f"{num} {numbers[num]}")
print(1,2)
print(1, 2)
for i in range(1,11):
print(f'2^{i} = {2 ** i}')
i = 1
while i <= 10:
print(f'2^{i} = {2 ** i}')
i += 1
for i in range(11):
print("2^{} = {}".format(i, 2 ** i))
for i in range(1, 10):
for j in range(1, 10):
print(f"{i} * {j} = {i * j}")
i = 1
while i < 10:
j = 1
while j < 10:
print(f"{i} * {j} = {i * j}")
j += 1
i += 1
for i in range(1,10):
if i < 10 :
a = 1
print("{} * {} = {}".format(a, i, a * i))
print("if문이 실행!")
else :
a += 1
i = 1
print("else문이 실행!")
for a in range(1,1001):
for b in range(a,1001):
c = 1000 - a - b
if a ** 2 + b ** 2 == c ** 2 and a + b + c == 1000 and a < b < c:
print(a * b * c)
print("완료")
| false
|
7d2fe2f51f6759be77661c2037c7eb4de4326375
|
rbrook22/otherOperators.py
|
/otherOperators.py
| 717
| 4.375
| 4
|
#File using other built in functions/operators
print('I will be printing the numbers from range 1-11')
for num in range(11):
print(num)
#Printing using range and start position
print("I will be printing the numbers from range 1-11 starting at 4")
for num in range(4,11):
print(num)
#Printing using range, start, and step position
print("I'll print the numbers in range to 11, starting at 2, with a step size of 2")
for num in range(2,11,2):
print(num)
#Using the min built in function
print('This is the minimum age of someone in my family:')
myList = [30, 33, 60, 62]
print(min(myList))
#Using the max built in function
print('This is the maximum age of someone in my family:')
print(max(myList))
| true
|
b86322bff277a38ee7165c5637c72d781e9f6ee2
|
Bbenard/python_assesment
|
/ceaser/ceaser.py
| 678
| 4.34375
| 4
|
# Using the Python,
# have the function CaesarCipher(str, num) take the str parameter and perform a Caesar Cipher num on it using the num parameter as the numing number.
# A Caesar Cipher works by numing all letters in the string N places down in the alphabetical order (in this case N will be num).
# Punctuation, spaces, and capitalization should remain intact.
# For example if the string is "Caesar Cipher" and num is 2 the output should be "Ecguct Ekrjgt".
# more on cipher visit http://practicalcryptography.com/ciphers/caesar-cipher/
# happy coding :-)
def CaesarCipher(string, num):
# Your code goes here
print "Cipertext:", CaesarCipher("A Crazy fool Z", 1)
| true
|
5165e39c4ff20f645ed4d1d725a3a6becd002778
|
ashishbansal27/DSA-Treehouse
|
/BinarySearch.py
| 740
| 4.125
| 4
|
#primary assumption for this binary search is that the
#list should be sorted already.
def binary_search (list, target):
first = 0
last = len(list)-1
while first <= last:
midpoint = (first + last)//2
if list[midpoint]== target:
return midpoint
elif list[midpoint] < target :
first = midpoint + 1
else :
last = midpoint - 1
return None
#summary of above code :
#two variables named first and last to indicate the starting and ending point
#of the list.
# the while loop would run till the first value is less than or equal to last
# then we update the values of first and last.
a= [x for x in range(1,11)]
print(a)
print(binary_search(a,1))
| true
|
33c960afb411983482d2b30ed9037ee6017fbd34
|
aggy07/Leetcode
|
/600-700q/673.py
| 1,189
| 4.125
| 4
|
'''
Given an unsorted array of integers, find the number of longest increasing subsequence.
Example 1:
Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5.
Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int.
'''
class Solution(object):
def findNumberOfLIS(self, nums):
length = [1]*len(nums)
count = [1]*len(nums)
result = 0
for end, num in enumerate(nums):
for start in range(end):
if num > nums[start]:
if length[start] >= length[end]:
length[end] = 1+length[start]
count[end] = count[start]
elif length[start] + 1 == length[end]:
count[end] += count[start]
for index, max_subs in enumerate(count):
if length[index] == max(length):
result += max_subs
return result
| true
|
9ee533969bbce8aec40f6230d3bc01f1f83b5e96
|
aggy07/Leetcode
|
/1000-1100q/1007.py
| 1,391
| 4.125
| 4
|
'''
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the i-th domino, so that A[i] and B[i] swap values.
Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same.
If it cannot be done, return -1.
Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by A and B: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
'''
class Solution(object):
def minDominoRotations(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
if len(A) != len(B):
return -1
if len(A) == 0:
return 0
for possibility in set([A[0], B[0]]):
top_rotation, bottom_rotation =0, 0
for a_num, b_num in zip(A, B):
if possibility not in [a_num, b_num]:
break
top_rotation += int(b_num != possibility)
bottom_rotation += int(a_num != possibility)
else:
return min(top_rotation, bottom_rotation)
return -1
| true
|
8bdf3154382cf8cc63599d18b20372d16adbe403
|
aggy07/Leetcode
|
/200-300q/210.py
| 1,737
| 4.125
| 4
|
'''
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
Example 1:
Input: 2, [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished
course 0. So the correct course order is [0,1] .
'''
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
graph = [[] for _ in range(numCourses)]
visited = [False for _ in range(numCourses)]
stack = [False for _ in range(numCourses)]
for pair in prerequisites:
x, y = pair
graph[x].append(y)
result = []
for course in range(numCourses):
if visited[course] == False:
if self.dfs(graph, visited, stack, course, result):
return []
return result
def dfs(self, graph, visited, stack, course, result):
visited[course] = True
stack[course] = True
for neigh in graph[course]:
if visited[neigh] == False:
if self.dfs(graph, visited, stack, neigh, result):
return True
elif stack[neigh]:
return True
stack[course] = False
result.append(course)
return False
| true
|
e9d57ebf9fe9beec2deb9654248f77541719e780
|
aggy07/Leetcode
|
/100-200q/150.py
| 1,602
| 4.21875
| 4
|
'''
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example 1:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
'''
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
if not tokens:
return 0
stack = []
for val in tokens:
if val == '+':
val1 = stack.pop()
val2 = stack.pop()
stack.append(val1 + val2)
elif val == '-':
val1 = stack.pop()
val2 = stack.pop()
stack.append(val2-val1)
elif val == '*':
val1 = stack.pop()
val2 = stack.pop()
stack.append(val2*val1)
elif val == '/':
val1 = stack.pop()
val2 = stack.pop()
if val1*val2 < 0:
stack.append(-(-val2/val1))
else:
stack.append(val2/val1)
else:
stack.append(int(val))
return stack[0]
| true
|
8f83262573f48ba2f847993cc9ba7ffeb5fc1b17
|
aggy07/Leetcode
|
/1000-1100q/1035.py
| 1,872
| 4.15625
| 4
|
'''
We write the integers of A and B (in the order they are given) on two separate horizontal lines.
Now, we may draw a straight line connecting two numbers A[i] and B[j] as long as A[i] == B[j], and the line we draw does not intersect any other connecting (non-horizontal) line.
Return the maximum number of connecting lines we can draw in this way.
Example 1:
Input: A = [1,4,2], B = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2.
Example 2:
Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2]
Output: 3
Example 3:
Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1]
Output: 2
Note:
1 <= A.length <= 500
1 <= B.length <= 500
1 <= A[i], B[i] <= 2000
'''
class Solution(object):
def maxUncrossedLines(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
dp = [[0]*len(A) for _ in range(len(B))]
dp[0][0] = 1 if A[0] == B[0] else 0
for index_i in range(1, len(dp)):
dp[index_i][0] = dp[index_i-1][0]
if A[0] == B[index_i]:
dp[index_i][0] = 1
for index_j in range(1, len(dp[0])):
dp[0][index_j] = dp[0][index_j-1]
if B[0] == A[index_j]:
dp[0][index_j] = 1
for index_i in range(1, len(dp)):
for index_j in range(1, len(dp[0])):
if A[index_j] == B[index_i]:
dp[index_i][index_j] = max(dp[index_i-1][index_j-1] + 1, max(dp[index_i-1][index_j], dp[index_i][index_j-1]))
else:
dp[index_i][index_j] = max(dp[index_i-1][index_j-1], max(dp[index_i-1][index_j], dp[index_i][index_j-1]))
return dp[len(B)-1][len(A)-1]
| true
|
fe6681006dca45b41fd2ce1a4715decda8b4ce76
|
IrsalievaN/Homework
|
/homework5.py
| 578
| 4.125
| 4
|
from abc import ABC, abstractmethod
from math import pi
class Figure(ABC):
@abstractmethod
def draw (self):
print("Квадрат нарисован")
class Round(Figure):
def draw(self):
print("Круг нарисован")
def __square(a):
return S = a ** 2 * pi
class Square(Figure):
def draw(self):
super().draw()
@staticmethod
def square(a):
return S = a ** 2
a = int(input("Введите а:\n"))
r = Round()
s = Square()
print()
r.draw()
print()
s.draw()
print()
print(s.square(a))
print(r._Round__square())
| false
|
64f7eb0fbb07236f5420f9005aedcbfefa25a457
|
JATIN-RATHI/7am-nit-python-6thDec2018
|
/variables.py
| 730
| 4.15625
| 4
|
#!/usr/bin/python
'''
Comments :
1. Single Comments : '', "", ''' ''', """ """ and #
2. Multiline Comments : ''' ''', and """ """
'''
# Creating Variables in Python
'Rule of Creating Variables in python'
"""
1. A-Z
2. a-z
3. A-Za-z
4. _
5. 0-9
6. Note : We can not create a variable name with numeric Value as a prefix
"""
'''left operand = right operand
left operand : Name of the Variable
right operand : Value of the Variable'''
"Creating variables in Python"
FIRSTNAME = 'Guido'
middlename = "Van"
LASTname = '''Rossum'''
_python_lang = """Python Programming Language"""
"Accessing Variables in Python"
print(FIRSTNAME)
print("")
print(middlename)
print("")
print(LASTname)
print("")
print(_python_lang)
| true
|
356b0255a23c0a845df9c05b512ca7ccc681aa12
|
JATIN-RATHI/7am-nit-python-6thDec2018
|
/datatypes/list/List_pop.py
| 781
| 4.21875
| 4
|
#!/usr/bin/python
aCoolList = ["superman", "spiderman", 1947,1987,"Spiderman"]
oneMoreList = [22, 34, 56,34, 34, 78, 98]
print(aCoolList,list(enumerate(aCoolList)))
# deleting values
aCoolList.pop(2)
print("")
print(aCoolList,list(enumerate(aCoolList)))
# Without index using pop method:
aCoolList.pop()
print("")
print(aCoolList,list(enumerate(aCoolList)))
'''
5. list.pop([i]) : list.pop()
Remove the item at the given position in the list, and return it.
If no index is specified, a.pop() removes and returns the last item in the list.
(The square brackets around the i in the method signature denote that the
parameter is optional,
not that you should type square brackets at that position.
You will see this notation frequently in the Python Library Reference.)
'''
| true
|
29d770237ec753148074d79ef96ef25287fde94a
|
JATIN-RATHI/7am-nit-python-6thDec2018
|
/loops/for_decisionMaking.py
| 853
| 4.375
| 4
|
"""
for variable_expression operator variable_name suit
statements
for i in technologies:
print(i)
if i == "AI":
print("Welcome to AI World")
for i in range(1,10): #start element and end element-1 : 10-1 = 9
print(i)
# Loop Controls : break and continue
for i in technologies:
print(i)
if i == "Bigdata":
continue
#break
for i in range(6): # start index 0 1 2 3 4 5 range(6) end-1 = 5
print(i)
else:
print("Completed")
"""
# Neasted For Loop:
"""
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop"
"""
technologies = ['Cloud','Bigdata','AI','DevOps']
cloud_vendors = ['AWS','Azure','GCP']
for i in technologies: # Outer loop
for var in cloud_vendors: # Inner Loop
print(i,var)
| false
|
e23ca223aef575db942920729a53e52b1df2ed4d
|
JATIN-RATHI/7am-nit-python-6thDec2018
|
/DecisionMaking/ConditionalStatements.py
| 516
| 4.21875
| 4
|
"""
Decision Making
1. if
2. if else
3. elif
4. neasted elif
# Simple if statement
if "expression" :
statements
"""
course_name = "Python"
if course_name:
print("1 - Got a True Expression Value")
print("Course Name : Python")
print(course_name,type(course_name),id(course_name))
print("I am outside of if condition")
var = 100
var1 = 50
if var == var1:
print("Yes, Condition is met")
print("Goodbye!")
if (var == var1):
print("Yes, Condition is met")
print("Goodbye!")
| true
|
71fb2e89c852750f33e2512e2f83ab1f9a021b68
|
JATIN-RATHI/7am-nit-python-6thDec2018
|
/datatypes/basics/built-in-functions.py
| 2,190
| 4.375
| 4
|
# Creating Variables in Python :
#firstname = 'Guido'
middlename = 'Van'
lastname = "Rossum"
# Accesing Variables in Python :
#print(firstname)
#print("Calling a Variable i.e. FirstName : ", firstname)
#print(firstname,"We have called a Variable call Firstname")
#print("Calling Variable",firstname,"Using Print Function")
# String Special Operators :
'''
1. + : Concatenation
2. * : Repetition
3. []: Slice
4. [:]: Range Slice
5. [::] : Zero Based Indexing
6. % : Format
7. .format()
'''
#names = firstname + lastname
#print(names)
'''
Indexing
Left to Right
0 1 2 3 4 5 nth
Right to Left
-nth -5 -4 -3 -2 -1
'''
# 0 1 2 3 4 Left to Right Indexing
# -5 -4 -3 -2 -1 Right to Left Indexing
#firstname=' G u i d o'
firstname = 'Guido Van Rossum'
print('Left to Right Indexing : ',firstname[0])
print('Right to Left Indexing : ',firstname[-5])
# print('Range Slice[:]',firstname[Start index: end index]) end index -1 :
print('Range Slice[:]',firstname[2:5])
print('Range Slice[:]',firstname[1:]) # endindex-1 = 3 (0123)
# 012121212121212121
numValues = '102030405060708090'
print("Zero Based Indexing",numValues[2::4])
"""
Below are the list of complete set of symbols which can be used along with % :
Format Symbol Conversion
%c character
%s string conversion via str()
prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E
"""
print("FirstName : %s MiddleName : %s LastName: %s " %(firstname,middlename,lastname))
print("FirstName :",firstname,"MiddleName : ",middlename,"LastName:",lastname)
print("FirstName : {} MiddleName : {} LastName: {} ".format(firstname,middlename,lastname))
# raw sring : r/R r'expression' or R'expression'
print(r'c:\\users\\keshavkummari\\')
print(R'c:\\users\\keshavkummari\\')
| false
|
47d9ba9ec790f0b9fde1a350cf8b240e5b8c886a
|
JATIN-RATHI/7am-nit-python-6thDec2018
|
/OOPS/Encapsulation.py
| 1,035
| 4.65625
| 5
|
# Encapsulation :
"""
Using OOP in Python, we can restrict access to methods and variables.
This prevent data from direct modification which is called encapsulation.
In Python, we denote private attribute using underscore as prefix i.e single
“ _ “ or double “ __“.
"""
# Example-4: Data Encapsulation in Python
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
"""
In the above program, we defined a class Computer.
We use __init__() method to store the maximum selling price of computer.
We tried to modify the price.
However, we can’t change it because Python treats the __maxprice as private attributes.
To change the value, we used a setter function i.e setMaxPrice() which takes price as parameter.
"""
| true
|
9f6536e8d1970c519e84be0e7256f5b415e0cf3e
|
JATIN-RATHI/7am-nit-python-6thDec2018
|
/loops/Password.py
| 406
| 4.1875
| 4
|
passWord = ""
while passWord != "redhat":
passWord = input("Please enter the password: ")
if passWord == "redhat":
print("Correct password!")
elif passWord == "admin@123":
print("It was previously used password")
elif passWord == "Redhat@123":
print(f"{passWord} is your recent changed password")
else:
print("Incorrect Password- try again!")
| true
|
436120f034d541d70e2373de9c3a0c968b47f7ad
|
idubey-code/Data-Structures-and-Algorithms
|
/InsertionSort.py
| 489
| 4.125
| 4
|
def insertionSort(array):
for i in range(0,len(array)):
if array[i] < array[0]:
temp=array[i]
array.remove(array[i])
array.insert(0,temp)
else:
if array[i] < array[i-1]:
for j in range(1,i):
if array[i]>=array[j-1] and array[i]<array[j]:
temp=array[i]
array.remove(array[i])
array.insert(j,temp)
return array
| true
|
9441cb892e44c9edd6371914b227a48f00f5d169
|
hospogh/exam
|
/source_code.py
| 1,956
| 4.21875
| 4
|
#An alternade is a word in which its letters, taken alternatively in a strict sequence, and used in the same order as the original word, make up at least two other words. All letters must be used, but the smaller words are not necessarily of the same length. For example, a word with seven letters where every second letter is used will produce a four-letter word and a three-letter word. Here are two examples:
# "board": makes "bad" and "or".
# "waists": makes "wit" and "ass".
#
#
#Using the word list at unixdict.txt, write a program that goes through each word in the list and tries to make two smaller words using every second letter. The smaller words must also be members of the list. Print the words to the screen in the above fashion.
#max_leng_of_word = 14
with open("unixdict.txt", "r") as f:
words = f.readlines()
f.closed
words = [s.strip("\n") for s in words]
#creating a dict with a member after each word which contains an empty list
potential_words = {str(word): ["evennumberword", "oddnumberword"] for word in words}
#adding to the dict member of each word it's even number and odd number chars made words, in total: 2 words as
for word in words:
even_number_word = ""
odd_number_word = ""
try:
for i in range(14):
if i % 2 == 0:
even_number_word = "".join([even_number_word, word[i]])
elif not i % 2 == 0:
odd_number_word = "".join([odd_number_word, word[i]])
except IndexError:
potential_words[str(word)][0] = even_number_word
potential_words[str(word)][0] = odd_number_word
print(word, "evennumber is", even_number_word, "and oddnumber is", odd_number_word)
if even_number_word in set(words) and odd_number_word in set(words):
print(word, "is an alternade")
else:
print(word, "is not an alternade")
#didn't take out dict creation part cause it might be used to write this info in another file
| true
|
fb745ae55b2759660a882d00b345ae0db70e60d2
|
irfan-ansari-au28/Python-Pre
|
/Interview/DI _ALGO_CONCEPT/stack.py
| 542
| 4.28125
| 4
|
"""
It's a list when it's follow stacks convention it becomes a stack.
"""
stack = list()
#stack = bottom[8,5,6,3,9]top
def isEmpty():
return len(stack) == 0
def peek():
if isEmpty():
return None
return stack[-1]
def push(x):
return stack.append(x)
def pop():
if isEmpty():
return None
else:
return stack.pop()
if __name__ == '__main__':
push(8)
push(5)
push(6)
push(3)
push(9)
print(isEmpty())
print(peek())
x = pop()
print(x,'pop')
print(stack)
| true
|
511b43f80a63e424aa9403ac3a9d21529eca3082
|
Vanderson10/Codigos-Python-UFCG
|
/4simulado/tabelaquadrados/Chavesegura/chavesegura.py
| 1,009
| 4.125
| 4
|
#analisar se a chave é segura
#se não tiver mais que cinco vogais na chave
#não tem tre caracteres consecultivos iguais
#quando detectar que a chave não é segura é para o programa parar e avisar ao usuario
#criar um while e analisar se tem tres letras igual em sequencia
#analisar se tem mais que cinco vogais, analisar com uma lista cada letra.
#entrada
chave = input()
pri = chave[0]
seg = chave[1]
i = 2
soma = 0
vogais = ['A','E','I','O','U','a','e','i','o','u']
e = 0
while True:
if pri == seg and pri == chave[i]:
print("Chave insegura. 3 caracteres consecutivos iguais.")
break
else:
pri = seg
seg = chave[i]
i=i+1
for v in vogais:
if v==chave[e]:
soma = soma+1
break
e=e+1
if soma>5:
print("Chave insegura. 6 vogais.")
break
if i==len(chave):
print("Chave segura!")
break
if e>len(chave):
print("Chave segura!")
| false
|
6a34496d114bc6e67187e4bc12c8ff874d575de0
|
BrightAdeGodson/submissions
|
/CS1101/bool.py
| 1,767
| 4.28125
| 4
|
#!/usr/bin/python3
'''
Simple compare script
'''
def validate(number: str) -> bool:
'''Validate entered number string is valid number'''
if number == '':
print('Error: number is empty')
return False
try:
int(number)
except ValueError as exp:
print('Error: ', exp)
return False
return True
def read_number(prefix: str) -> int:
'''Read number from the prompt'''
while True:
prompt = 'Enter ' + prefix + ' > '
resp = input(prompt)
if not validate(resp):
continue
number = int(resp)
break
return number
def compare(a, b: int) -> (str, int):
'''
Compare two numbers
It returns 1 if a > b,
returns 0 if a == b,
returns -1 if a < b,
returns 255 if unknown error
'''
if a > b:
return '>', 1
elif a == b:
return '==', 0
elif a < b:
return '<', -1
return 'Unknown error', 255
def introduction():
'''Display introduction with example'''
_, example1 = compare(5, 2)
_, example2 = compare(2, 5)
_, example3 = compare(3, 3)
print('''
Please input two numbers. They will be compared and return a number.
Example:
a > b is {}
a < b is {}
a == b is {}
'''.format(example1, example2, example3))
def main():
'''Read numbers from user input, then compare them, and return result'''
introduction()
first = read_number('a')
second = read_number('b')
result_str, result_int = compare(first, second)
if result_int == 255:
print(result_str)
return
print('Result: {} {} {} is {}'.format(first, result_str, second,
result_int))
if __name__ == "__main__":
main()
| true
|
49b854f0322357dd2ff9f588fc8fb9c6f62fd360
|
BowieSmith/project_euler
|
/python/p_004.py
| 352
| 4.125
| 4
|
# Find the largest palindrome made from the product of two 3-digit numbers.
def is_palindrome(n):
s = str(n)
for i in range(len(s) // 2):
if s[i] != s[-i - 1]:
return False
return True
if __name__ == "__main__":
ans = max(a*b for a in range(100,1000) for b in range(100,1000) if is_palindrome(a*b))
print(ans)
| true
|
eed8d54cb38af8b0bb62927b9dadfdf0aa69d378
|
debargham14/bcse-lab
|
/Sem 4/Adv OOP/python_assignments_set1/sol10.py
| 444
| 4.125
| 4
|
import math
def check_square (x) :
"Function to check if the number is a odd square"
y = int (math.sqrt(x))
return y * y == x
# input the list of numbers
print ("Enter list of numbers: ", end = " ")
nums = list (map (int, input().split()))
# filter out the odd numbers
odd_nums = filter (lambda x: x%2 == 1, nums)
# filter out the odd squares
odd_squares = list (filter (check_square, odd_nums))
print ("Odd squares are: ", odd_squares)
| true
|
6b2736e3ef5bd2b374367750d21d8af3e9ca2e0a
|
debargham14/bcse-lab
|
/Sem 4/Adv OOP/python_assignments_set1/sol11.py
| 434
| 4.28125
| 4
|
print ("Pythagorean Triplets with smaller side upto 10 -->")
# form : (m^2 - n^2, 2*m*n, m^2 + n^2)
# generate all (m, n) pairs such that m^2 - n^2 <= 10
# if we take (m > n), for m >= 6, m^2 - n^2 will always be greater than 10
# so m ranges from 1 to 5 and n ranges from 1 to m-1
pythTriplets = [(m*m - n*n, 2*m*n, m*m + n*n) for (m,n) in [(x, y) for x in range (1, 6) for y in range (1, x)] if m*m - n*n <= 10]
print (pythTriplets)
| false
|
669f4bbca09f2d6062be01a30fdfd0f7a0367394
|
mckinleyfox/cmpt120fox
|
/pi.py
| 487
| 4.15625
| 4
|
#this program is used to approximate the value of pi
import math
def main():
print("n is the number of terms in the pi approximation.")
n = int(input("Enter a value of n: "))
approx = 0.0
signchange = 1.0
for i in range(1, n+1, 2):
approx = approx + signchange * 4.0/i # JA
signchange = -signchange
print("The aprroximate value of pi is: ", approx)
print("The difference between the approximation and real pi is: ", math.pi - approx)
main()
| true
|
4c538d0eccedfa427845be1ca803cdb6cc2ef867
|
jorgeromeromg2/Python
|
/mundo2/ex008_D41.py
| 787
| 4.25
| 4
|
#--------CATEGORIA NATAÇÃO--------#
print(10 * '--=--')
print('CADASTRO PARA CONFEDERAÇÃO NACIONAL DE NATAÇÃO')
print(10 * '--=--')
nome = str(input('Qual é o seu nome: ')).capitalize()
idade = int(input('Qual é a sua idade: '))
if idade <= 9:
print('{}, você tem {} anos e está cadastrado na categoria MIRIM.'.format(nome, idade))
elif idade <= 14:
print('{}, você tem {} anos e está cadastrado na categoria INFANTIL.'.format(nome, idade))
elif idade <= 19:
print('{}, você tem {} anos e está cadastrado na categoria JUNIOR.'.format(nome, idade))
elif idade <= 20:
print('{}, você tem {} anos e está cadastrado na categoria SENIOR.'.format(nome, idade))
else:
print('{}, você tem {} anos e está cadastrado na categoria MASTER.'.format(nome, idade))
| false
|
fd614fdd36b34645dd4afc125153dc09493841c2
|
jorgeromeromg2/Python
|
/mundo1/ex005.py
| 648
| 4.15625
| 4
|
#--------SOMA ENTRE NÚMEROS------
#n1 = int(input('Digite o primeiro número: '))
#n2 = int(input('Digite o segundo número: '))
#soma = n1 + n2
#print('A soma entre {} e {} é igual a {}!'.format(n1, n2, soma))
#--------SUCESSOR E ANTECESSOR-----
n = int(input('Digite um número e verifique o sucessor e antecessor:'))
a = n-1
s = n+1
print('Analisando o valor {} podemos perceber que o antecessor é {} e o sucessor é {}.'.format(n, a, s))
#-----OU-----
n = int(input('Digite um número e verifique o sucessor e antecessor:'))
print('Analisando o valor {} podemos perceber que o antecessor é {} e o sucessor é {}.'.format(n, (n-1), (n+1)))
| false
|
0b1c100231c6dbe5d970655a92f4baed0cbe1221
|
firoj1705/git_Python
|
/V2-4.py
| 1,745
| 4.3125
| 4
|
'''
1. PRINT FUNCTION IN PYTHON:
print('hello', 'welcome')
print('to', 'python', 'class')
#here by default it will take space between two values and new line between two print function
print('hello', 'welcome', end=' ')
print('to', 'python', 'class')
# here we can change end as per our requirement, by addind end=' '
print('hello', 'welcome', end=' ')
print('to', 'python', 'class', sep=',')
# here you can change sep as per our requirement by writing it. By default sep as SPACE is present.
2. KEYWORDS IN PYTHON: RESERVED WORDS
import keyword
print(keyword.kwlist) #you will get list of keyword in Python
print(len(keyword.kwlist))
print(dir(keyword.kwlist))
print(len(dir(keyword.kwlist)))
3. BASIC CONCEPTS IN PYTHON:
A. INDEXING:
+indexing: strats from 0
-indexing: starts from -1
0 1 2 3 4 5
s= 'P y t h o n'
-6-5-4-3-2-1
B. HASHING:
s='Pyhton'
print(s[0])
print(s[-6])
print(s[4])
print(s[7])
C. SLICING:
s='Python'
print(s[0:4])
print(s[3:])
print(s[:])
print(s[:-3])
print(s[5:4])
D. STRIDING/STEPPING:
s='Python'
print(s[0:5:2])
print(s[0:7:3])
print(s[5:0:-2])
print(s[::-1])
#E. MEMBERSHIP:
s='Python'
print('o' in s)
print('p' in s)
#F. CONCATENATION:
s1='Hi'
s2='Hello'
s3='303'
print(s1+s2)
print(s1+' '+s2)
print(s1+s2+s3)
print(s1+s2+100) # error will occur, As datatype should be same.
#G. REPLICATION:
s1='Firoj'
print(s1*3)
print(s1*s1) # multiplier should be integer
#H. TYPECASTING:
s='100'
print(int(s))
n=200
s1=str(n)
print(s1)
s='Hello'
print(list(s))
#I. CHARACTER TO ASCII NUMBER:
print(ord('a'))
print(ord('D'))
#J. ASCII TO CHARACTER NUMBER:
print(chr(97))
print(chr(22))
'''
| true
|
c5db4886b9e216f7da109bcfdd190a2267d7258b
|
BMHArchives/ProjectEuler
|
/Problem_1/Problem_1.py
| 1,128
| 4.21875
| 4
|
# Multiples of 3 and 5
#---------------------
#If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
numberCount = 1000 # Use this number to find all multiples under the numberCount
total = 0 # summerize the total count of multiples under 1000
# loop between 1 and 1000
for count in range(1,numberCount):
if count != 0: # can't divide by 0
# if the % value is equal to 0 for 3 or 5, then add it to the total.
if (count % 3) == 0 or (count % 5) == 0:
total += count
#def FindAllMultiplesOfTragetNumber(TargetNumber):
# sumTotal = 0
# for a in range(1,numberCount):
# if(a % TargetNumber) == 0:
# sumTotal += a
# return sumTotal
# We're using 3, 5 and 15 here because 15 is the lowest common denominator between 3 and 5, so we will add 3 + 5 to 8 and then subtract from 15 to get the value.
#print(FindAllMultiplesOfTragetNumber(3) + FindAllMultiplesOfTragetNumber(5) - FindAllMultiplesOfTragetNumber(15))
print("Answer: {}".format(total))
| true
|
c0d728b393c1b9184357b51442f0f3ee96e0db3d
|
edvalvitor/projetos
|
/python/media2.py
| 1,215
| 4.15625
| 4
|
#Programa para calcular a média e quanto falta para passar
#Centro Universitário Tiradentes
#Edval Vitor
#Versão 1.0.1
while True:
print("Programa para calcular média da UNIT")
print("Se você quer calcular a sua média digite 1")
print("Se quer calcular quanto precisa para passar digite 2")
opcao = int(input("Digite sua opção: "))
#Função para calcular a média final
def func1():
uni1 = float(input("Digite a nota da Primeira unidade: "))
uni2 = float(input("Digite a nota da Segunda unidade: "))
total = ((uni1 * 4) + (uni2 * 6))
if (total >= 60):
print("Você passou, sua nota é igual a: ", (total/10))
elif (total < 60):
print("Você não passou, sua nota é igual a: ", (total/10))
#Função para calcular quanto precisa para passar
def func2():
uni1 = float(input("Digite a nota da primeira unidade: "))
falta =(60 - (uni1*4))
mediaf = falta /6
print("Você precisa de", mediaf, "para passar")
if (opcao == 1):
func1()
elif (opcao == 2):
func2()
else:
print("Opção incorreta, saindo do programa!")
break
| false
|
c219b35384dcc23574658cfcbae883f4223f8709
|
LRG84/python_assignments
|
/average7.5.py
| 538
| 4.28125
| 4
|
# calculate average set of numbers
# Write a small python program that does the following:
# Calculates the average of a set of numbers.
# Ask the user how many numbers they would like to input.
# Display each number and the average of all the numbers as the output.
def calc_average ():
counter = int (input('How many numbers would you like to input?_'))
total = 0
for a in range (0, counter):
total = total + int(input('Enter number_ '))
print('The average of your input is ', total/counter)
calc_average ()
| true
|
833bd691452513944dabb2af51272c90c70c8eaf
|
lucasrwv/python-p-zumbis
|
/lista III/questao04.py
| 273
| 4.125
| 4
|
#programa fibonacci
num = int(input("digite um numero "))
anterior = 0
atual = 1
proximo = 1
cont = 0
while cont != num :
seun = proximo
proximo = atual + anterior
anterior = atual
atual = proximo
cont += 1
print("o seu numero fibonacci é %d" %seun)
| false
|
a085d9ff5c97264c048a0f265806c906647d90df
|
shyam-de/py-developer
|
/d2exer1.py
| 1,091
| 4.1875
| 4
|
# program to check wether input number is odd/even , prime ,palindrome ,armstrong.
def odd_even(num):
if num%2==0:
print("number is even")
else:
print( 'number is odd')
def is_prime(num):
if num>1:
for i in range(2,num//2):
if (num%i)==0:
print('number is not prime')
# print(i,"times",num//i,'is'num)
break
else:
print("number is prime")
else:
print("number is not prime")
def is_arm(num):
sum=0
temp=num
while temp>0:
digit=temp%10
sum+=digit**3
temp//=10
if num==sum:
print("number is armstrong")
else :
print("number is not armstrong")
def is_pal(num):
temp=num
rev=0
while num>0:
dig=num%10
rev=rev*10+dig
num=num//10
if temp==rev:
print("number is palindrome")
else:
print(" numer is not palindrome")
num=int(input("Enter a number "))
print(odd_even(num),is_prime(num),is_arm(num),is_pal(num))
| false
|
f179a86035e710a59300a467e2f3cd4e9f8f0b15
|
tweatherford/COP1000-Homework
|
/Weatherford_Timothy_A3_Gross_Pay.py
| 1,299
| 4.34375
| 4
|
##-----------------------------------------------------------
##Programmed by: Tim Weatherford
##Assignment 3 - Calculates a payroll report
##Created 11/10/16 - v1.0
##-----------------------------------------------------------
##Declare Variables##
grossPay = 0.00
overtimeHours = 0
overtimePay = 0
regularPay = 0
#For Presentation
print("Payroll System")
print("=-"*30)
##Input Section##
empName = str(input("Enter the Employee's Full Name:"))
hoursWorked = float(input("Enter Hours Worked:"))
payRate = float(input("Enter " + empName + "'s hourly rate of pay:$"))
print("-"*60)
##Logic Functions##
if hoursWorked > 40:
overtimeHours = hoursWorked - 40
regularPay = 40 * payRate
overtimePay = (payRate*1.5) * overtimeHours
grossPay = regularPay + overtimePay
else:
regularPay = hoursWorked * payRate
grossPay = regularPay
#Output
print("=-"*30)
print("Payroll Report for " + empName)
print("=-"*30)
print("--Hours Worked--")
print("Total Hours Worked:" + str(hoursWorked))
print("Overtime Hours:" + str(overtimeHours))
print("--Pay Information--")
print("Regular Pay:$" + str(format(regularPay, "9,.2f")))
print("Overtime Pay:$" + str(format(overtimePay, "9,.2f")))
print("Total Gross Pay:$" + str(format(grossPay, "9,.2f")))
print("=-"*30)
print("End Payroll Report")
| true
|
046ecafc48914b85956a7badd6b8500232a57db4
|
lathika12/PythonExampleProgrammes
|
/areaofcircle.py
| 208
| 4.28125
| 4
|
#Control Statements
#Program to calculate area of a circle.
import math
r=float(input('Enter radius: '))
area=math.pi*r**2
print('Area of circle = ', area)
print('Area of circle = {:0.2f}'.format(area))
| true
|
362eb0297bbb144719be1c76dc4696c141b72017
|
lathika12/PythonExampleProgrammes
|
/sumeven.py
| 225
| 4.125
| 4
|
#To find sum of even numbers
import sys
#Read CL args except the pgm name
args = sys.argv[1:]
print(args)
sum=0
#find sum of even args
for a in args:
x=int(a)
if x%2==0:
sum+=x
print("Sum of evens: " , sum)
| true
|
a1fe59470da2ee519283240483f8fa24917891b3
|
lathika12/PythonExampleProgrammes
|
/ifelsestmt.py
| 316
| 4.375
| 4
|
#Program for if else statement
#to test if a number is even or odd
x=10
if x%2==0:
print("Even Number" ,x )
else:
print("Odd Number" , x )
#Program to test if a number is between 1 to 10
x=19
if x>=1 and x<=10:
print(x , " is in between 1 to 10. " )
else:
print(x , " is not in between 1 to 10. " )
| false
|
99ef2163869fda04dbe4f1c23b46e56c14af7a17
|
TredonA/PalindromeChecker
|
/PalindromeChecker.py
| 1,822
| 4.25
| 4
|
from math import floor
# One definition program to check if an user-inputted word
# or phrase is a palindrome. Most of the program is fairly self-explanatory.
# First, check if the word/phrase in question only contains alphabetic
# characters. Then, based on if the word has an even or odd number of letters,
# begin comparing each letter near the beginning to the corresponding word
# near the end.
def palindromeChecker():
word = input("Please enter a word: ")
if not word.isalpha():
print("Word is invalid, exiting program.")
elif len(word) % 2 == 0:
leftIndex = 0
rightIndex = len(word) - 1
while leftIndex != (len(word) / 2):
if word[leftIndex] == word[rightIndex]:
leftIndex += 1
rightIndex -= 1
else:
print("\'" + word + "\' is not a palindrome.")
leftIndex = -1
break
if leftIndex != -1:
print("\'" + word + "\' is a palindrome!")
else:
leftIndex = 0
rightIndex = len(word) - 1
while leftIndex != floor(len(word) / 2):
if word[leftIndex] == word[rightIndex]:
leftIndex += 1
rightIndex -= 1
else:
print("\'" + word + "\' is not a palindrome.")
leftIndex = -1
break
if leftIndex != -1:
print("\'" + word + "\' is a palindrome!")
answer = input("Would you like to use this program again? Type in " +\
"\'Yes\' if you would or \'No\' if not: ")
if(answer == 'Yes'):
palindromeChecker()
elif(answer == 'No'):
print("Thank you for using my program. Have a great day!")
else:
print("Invalid input. Ending program...")
return
palindromeChecker()
| true
|
a113879ec0112ff4c269fb2173ed845c29a3b5e5
|
ravenclaw-10/Python_basics
|
/lists_prog/max_occur_elem.py
| 708
| 4.25
| 4
|
# Element with maximum occurence in a list=[2, 3, 8, 4, 7, 9, 8, 2, 6, 5, 1, 6, 1, 2, 3, 4, 6, 9, 1, 2] .
#Python program to check if the elements of a given list are unique or not.
n=int(input("Enter the no. of element in the list(size):"))
list1=[]
count=0
max=0
print("Enter the elements of the lists:")
for i in range(0,n):
elem=input()
list1.append(elem)
max_elem=list1[0]
for i in range(0,n):
count=0
for j in range(0,n):
if list1[i]==list1[j]:
count+=1
if max<=count:
max=count
max_elem=list1[i]
if max==1:
print("The given list have unique elements")
else:
print("Maximum occered element:",max_elem)
| true
|
6094c69f6d4fa7a0bb59fc8da0eb7fb379832514
|
Boukos/AlgorithmPractice
|
/recursion/rec_len.py
| 328
| 4.1875
| 4
|
def rec_len(L):
"""(nested list) -> int
Return the total number of non-list elements within nested list L.
For example, rec_len([1,'two',[[],[[3]]]]) == 3
"""
if not L:
return 0
elif isinstance(L[0],list):
return rec_len(L[0]) + rec_len(L[1:])
else:
return 1 + rec_len(L[1:])
print rec_len([1,'two',[[],[[3]]]])
| true
|
15f68fe0b019bb466d2d7bcfbd83c6baabf2efc4
|
eyeCube/Softly-Into-the-Night-OLD
|
/searchFiles.py
| 925
| 4.125
| 4
|
#search a directory's files looking for a particular string
import os
#get str and directory
print('''Welcome. This script allows you to search a directory's
readable files for a particular string.''')
while(True):
print("Current directory:\n\n", os.path.dirname(__file__), sep="")
searchdir=input("\nEnter directory to search in.\n>>")
find=input("Enter string to search for.\n>>")
#search each (readable) file in directory for string
for filename in os.listdir(searchdir):
try:
with open( os.path.join(searchdir,filename)) as file:
lineNum = 1
for line in file.readlines():
if find in line:
print(filename, "| Line", lineNum)
lineNum +=1
except Exception as err:
pass
print("End of report.\n------------------------------------------")
| true
|
8097283ba70a2e1ee33c31217e4b9170a45f2dd1
|
NagarajuSaripally/PythonCourse
|
/StatementsAndLoops/loops.py
| 2,014
| 4.75
| 5
|
'''
Loops: iterate through the dataypes that are iterable, iterable datatypes in python or in any language
string, lists, tuples, dictionaries
keywords to iterate through these iterables:
#for
syntax
for list_item in list_items:
print(list_item)
'''
# lists:
my_list_items = [1,2,3,4,5,6]
for my_list_item in my_list_items:
print(my_list_item)
# strings
mystring = 'Hello World!'
for eachChar in mystring:
print(eachChar)
#without assigning varibles
for variable in 'Good Morning':
print(variable)
# here instead of each character, we can print what ever the string that we want many times as string length
# so instead of putting a variable name we can use _ there
for _ in 'Hello World!':
print('cool!')
# tuples:
tup = (1,2,3)
for eachTup in tup:
print(eachTup)
# Tuple unpacking, sequence contain another tuples itself then for will upack them
my_tuples = [(1,2),(3,4),(5,6),(7,8),(9,0)]
print("length of my_tuples: {}".format(len(my_tuples)))
for item in my_tuples:
print(item)
# this is called tuple unpacking. techincally we don't need paranthesis like (a,b) it can be just like a,b
for (a,b) in my_tuples:
print(a)
print(b)
#dictionaries:
d = {'k1': 1, 'K2': 2, 'K3': 3}
for item in d:
print(item)
for value in d.values():
print(value)
'''
While loop, it continues to iterate till the condition satisfy
syntax:
while conition:
# do something
while condition:
# do something:
else:
# do something else:
'''
x = 0
while x < 5:
print(f'The current value of x is {x}')
x += 1
while x < 10:
print(f'The current value of x is {x}')
x += 1
else:
print('X is not should not greater than 10')
'''
useful keywords in loops
break, continue, pass
pass: do nothing at all
'''
p = [1,2,3]
for item in p:
#comment
pass # it just passes, in pythong for loops we need at least on statement in loop
print("Passed");
letter = 'something here'
for let in letter:
if let == 'e':
continue
print(let)
for let in letter:
if let == 'e':
break
print(let)
| true
|
30cf7566ca858b10b86bf6ffc72826de02134db2
|
NagarajuSaripally/PythonCourse
|
/Methods/lambdaExpressionFiltersandMaps.py
| 1,141
| 4.5
| 4
|
'''
Lambda expressions are quick way of creating the anonymous functions:
'''
#function without lamda expression:
def square(num):
return num ** 2
print(square(5))
#converting it into lambda expression:
lambda num : num ** 2
#if we want we can assign this to variable like
square2 = lambda num : num ** 2. # we are not going to use this very often, cause lamda function are anonymous
print(square2(5))
print(list(map(lambda num : num **2, [1,2,3,4])))
'''
Map: map() --> map(func, *iterables) --> map object
'''
def square(num):
return num ** 2
my_nums = [1,2,3,4,5]
#if I wanna get sqaure for all the list items, we can use map function, instead of for loop, for loop is costly
#Method 1:
for item in map(square, my_nums):
print(item)
#method 2:
list(map(square, my_nums))
def splicer(mystring):
if len(mystring) % 2 == 0:
return 'EVEN'
else:
return mystring[0]
names = ['andy', 'sally', 'eve']
print(list(map(splicer, names)))
'''
Filter: iterate function that returns either true or false
'''
def check_even(num):
return num % 2 == 0
my_numbers = [1,2,3,4,5,6]
print(list(filter(check_even, my_numbers)))
| true
|
3f947479dbb78664c2f12fc93b926e26d16d2c34
|
ankurkhetan2015/CS50-IntroToCS
|
/Week6/Python/mario.py
| 832
| 4.15625
| 4
|
from cs50 import get_int
def main():
while True:
print("Enter a positive number between 1 and 8 only.")
height = get_int("Height: ")
# checks for correct input condition
if height >= 1 and height <= 8:
break
# call the function to implement the pyramid structure
pyramid(height)
def pyramid(n):
for i in range(n):
# the loop that controls the blank spaces
for j in range(n - 1 - i):
print(" ", end="")
# the loop that controls and prints the bricks
for k in range(i + 1):
print("#", end="")
print(" ", end="")
for l in range(i + 1):
# the loop that control the second provided pyramid
print("#", end="")
# goes to the next pyramid level
print()
main()
| true
|
49d3fbe78c86ab600767198110c6022be77fefe9
|
SagarikaNagpal/Python-Practice
|
/QuesOnOops/F-9.py
| 507
| 4.1875
| 4
|
# : Write a function that has one character argument and displays that it’s a small letter, capital letter, a digit or a special symbol.
# 97-122 65-90 48-57 33-47
def ch(a):
if(a.isupper()):
print("upper letter")
elif(a.islower()):
print("lower letter")
elif (a.isdigit()):
print("is digit")
else:
print("Special")
a=input("ch is: ")
print(ch(a))
| true
|
43462ac259650bcea0c4433ff1d27d90bbc7a09e
|
SagarikaNagpal/Python-Practice
|
/QuesOnOops/C-4.py
| 321
| 4.40625
| 4
|
# input a multi word string and produce a string in which first letter of each word is capitalized.
# s = input()
# for x in s[:].split():
# s = s.replace(x, x.capitalize())
# print(s)
a1 = input("word1: ")
a2 = input("word2: ")
a3 = input("word3: ")
print(a1.capitalize(),""+a2.capitalize(),""+a3.capitalize())
| true
|
c56fecfa02ec9637180348dd990cf646ad00f77f
|
SagarikaNagpal/Python-Practice
|
/QuesOnOops/B-78.py
| 730
| 4.375
| 4
|
# Write a menu driven program which has following options:
# 1. Factorial of a number.
# 2. Prime or Not
# 3. Odd or even
# 4. Exit.
n = int(input("n: "))
menu = int(input("menu is: "))
factorial = 1
if(menu==1):
for i in range(1,n+1):
factorial= factorial*i
print("factorial of ",n,"is",factorial)
elif(menu==2):
if(n>1):
for i in range (2,n):
if(n%i)==0:
print("num ",n,"is not prime")
break
else:
print("num", n ,"is prime")
break
else:
print("num is not prime")
elif(menu==3):
if(n%2 ==0):
print(n,"is even")
else:
print(n, "is odd")
else:
print("exit!")
| true
|
7b8acefe0e74bdd25c9e90f869009c2e3a24a4fc
|
SagarikaNagpal/Python-Practice
|
/QuesOnOops/C-13.py
| 213
| 4.40625
| 4
|
# to input two strings and print which one is lengthier.
s1 = input("String1: ")
s2 = input("String2: ")
if(len(s1)>len(s2)):
print("String -",s1,"-is greater than-", s2,"-")
else:
print(s2,"is greater")
| true
|
e09aad9458b0eceb8a8acfc23db8a78637e3ebfe
|
SagarikaNagpal/Python-Practice
|
/tiny_progress/list/Python program to swap two elements in a list.py
| 809
| 4.25
| 4
|
# Python program to swap two elements in a list
def appendList():
user_lst = []
no_of_items = int(input("How many numbers in a list: "))
for i in range(no_of_items):
user_lst.append(int(input("enter item: ")))
return user_lst
def swapPos(swap_list):
swap_index_1 = int(input("Enter First Index for swapping: "))
swap_index_2 = int(input("Enter Second Index for swapping: "))
swap_list[swap_index_1], swap_list[swap_index_2] = swap_list[swap_index_2], swap_list[swap_index_1]
return swap_list
def main():
saga_list = appendList()
print("List Before Swapping: ", saga_list)
print("List Sorted: ", sorted(saga_list))
swapped_list = swapPos(swap_list=saga_list)
print("List After Swapping: ", swapped_list)
if __name__ == '__main__':
main()
| false
|
a33e791b4fc099c4e607294004888f145071e6ff
|
SagarikaNagpal/Python-Practice
|
/QuesOnOops/A22.py
| 254
| 4.34375
| 4
|
#Question A22: WAP to input a number. If the number is even, print its square otherwise print its cube.
import math
a=int(input("num: "))
sq = int(math.pow(a,2))
cube =int (math.pow(a,3))
if a%2==0:
print("sq of a num is ",sq)
else:
print(cube)
| true
|
169945565fd5ffb9c590d7a38715b3a08a8280ff
|
SagarikaNagpal/Python-Practice
|
/QuesOnOops/A-10.py
| 248
| 4.34375
| 4
|
# to input the number the days from the user and convert it into years, weeks and days.
days = int(input("days: "))
year = days/365
days = days%365
week = days/7
days = days%7
day = days
print("year",year)
print("week",week)
print("day",day)
| true
|
832c6af00dcabd3682df2be233f20bc677e8718a
|
SagarikaNagpal/Python-Practice
|
/QuesOnOops/B25.py
| 385
| 4.125
| 4
|
# Question B25: WAP to input two numbers and an operator and calculate the result according to the following conditions:
# Operator Result
# ‘+’ Add
# ‘-‘ Subtract
# ‘*’ Multiply
n1= int(input("n1"))
n2 = int(input("n2"))
opr = input("choice")
if(opr== '+'):
print(n1+n2)
elif(opr== '-'):
print(n1-n2)
elif (opr == '*'):
print(n1*n2)
| false
|
e5944d3d25b846e0ba00b84150eff7620517e608
|
juthy1/Python-
|
/e16-1.py
| 1,673
| 4.28125
| 4
|
# -*- coding: utf-8 -*-
#将变量传递给脚本
#from sys import argv
from sys import argv
#脚本、文件名为参数变量
#script, filename = argv
script, filename = argv
#打印“我们将建立filename的文件”%格式化字符,%r。字符串是你想要展示给别人或者从
#从程序里“导出”的一小段字符。
#print ("We're going to erase %r." % filename)
print ("We're going to erase %r." % filename)
#打印提示,如何退出,确定回车
#print ("If you don't want that, hit CTRL-C (^C).")
print ("If you don't want that, hit CTRL-C (^C).")
#print ("If you do want that, hit RETURN.")
print ("If you do want that, hit RETURN.")
#输入,用?来提示
input("?")
#print ("Opening the file...")
print ("Opening the file...")
#打开文件,‘W’目前还不懂
#target = open(filename, 'w')
target = open(filename, 'w')
#清空文件
#print ("Truncating the file. Goodbye!")
print ("Truncating the file. Goodbye!")
#清空文件的命令truncate()
#target.truncate()
target.truncate()
#打印,现在我将请求你回答这三行
#print ("Now I'm going to ask you for three lines.")
print ("Now I'm going to ask you for three lines.")
#第一行输入
#line1 = input("line 1: ")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
#打印,我把这些写入文件
print ("I'm going to write these to the file.")
#target.write(line1, "\n" line2, "\n" line3, "\n")这个是错的
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print ("I'm going to write these to the file.")
print ("And finally, we close it.")
target.close()
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.