blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
5e6b4f430be14482e14ebc597a3fb8101d7ee5f1 | amitarvindpatil/Python-Study-Material | /Conditional Statements/forloop.py | 885 | 4.5625 | 5 | # For looping statements
# Example-1 Odd Even Programs
list_data = [10, 11, 12, 13, 14, 15, 16]
for data in list_data:
if data % 2 == 0:
print("even Numbers:-", data)
else:
print("odd Numbers:-", data)
# Example -2 For Loop with Nested List
x = ['x', 'y', 'z']
a = ['a', 'b', 'c']
for xy in x:
for sb in a:
print(xy, sb)
# Example -3 For loop list of tuples
list1 = [(1, 2), (3, 4), (5, 6)]
for ls in list1:
print(ls)
# unpacking the List of Tuples
for l1, l2 in list1:
print(l1, l2)
# ForLoop with Dictionaries
dict_data = {
'id': 10,
'Name': 'Amit',
'city': ['Sangli', 'Pune'],
'isActive': True
}
for k1 in dict_data.items():
print("show all items:-", k1)
for k2 in dict_data.values():
print("show all values:-", k2)
for k3 in dict_data.keys():
print("show all values:-", k3)
# For loop with Function
| false |
7d5910267203ae26aee141d1d2af0ef7942f6a01 | amitarvindpatil/Python-Study-Material | /oops/inheritance.py | 2,203 | 4.3125 | 4 | # Inheritance
# Inheritance allow us to define a class that inherits all properties and method from anather class
# Parent class is the class being inherited from,also called as Base Class
# child class is that inherits from another class, also called derived class
# parent class
class Person:
def __init__(self, name, age, div):
self.name = name
self.age = age
self.div = div
def printdata(self):
print(self.name, self.age, self.div)
# CHILD class
class Student(Person):
def printdatas(self):
print(self.div)
op = Student("Amit", 25, "A")
print(op.printdata())
print(op.printdatas())
# use init() method
class Student(Person):
def __init__(self, name, age, div):
Person.__init__(name, age, div)
# op = Student("sallu", 25, "B")
# print(op.printdata())
# super() function that child class inherit all properties and methods from parent class
# add properties in base class
class Student(Person):
def __init__(self, name, age, div, rollno):
super().__init__(name, age, div)
self.rollno = rollno
def printdatas(self):
print(self.name, self.age, self.div, self.rollno)
# Multilevel Inheritance
class Subject(Student):
def __init__(self, name, age, div, rollno, marks):
super().__init__(name, age, div, rollno)
self.marks = marks
def printdatas(self):
print(self.name, self.age, self.div, self.rollno, self.marks)
op = Subject("rahul", 28, "B", 50, 64)
print(op.printdatas())
# # Multiple Inheritance
class Arvind:
def __init__(self, asset, sqft, price):
self.asset = asset
self.sqft = sqft
self.price = price
class Anita:
def __init__(self, Metal, kg):
self.Metal = Metal
self.kg = kg
class Amit(Arvind, Anita):
def __init__(self, asset, sqft, price, Metal, kg, flat):
Arvind.__init__(self, asset, sqft, price)
Anita.__init__(self, Metal, kg)
self.flat = flat
def showproperty(self):
print(self.asset, self.sqft, self.price,
self.Metal, self.kg, self.flat)
output = Amit('Land', 30000, '5CR', 'Gold', '5', '2BHK')
print(output.showproperty())
| true |
51b2e3e5e9c9a8cd72ddf852e598ba79ce284807 | amitarvindpatil/Python-Study-Material | /iterators/iterator.py | 2,210 | 4.4375 | 4 | # Iterator
# An Iterator is an object that contains a countable number of values
# An Iterator is an object that can be iterated upon,meaning that you can traverse throught all the value
# Technically in python, an Iterator is an object which implements the Iterator protocal, which consists of the methods
# __iter__() and __next__()
# iterator vs iterable
# List, tuples, dictionaries and sets all are iterable object.They are iterable containers
# which you can get an iterator from
# iter() method
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
mytuple = ("apple", "banana", "cherry")
for x in mytuple:
print(x)
# Create an iterator
# To Create an object/class as an iterator you have to implements the methods __iter__() and __next__() to your object
# As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__(), which allows
# you do some initializing when the object is being created.
# The __iter__() method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself.
# The __next__() method also allows you to do operations, and must return the next item in the sequence.
# Create an iterator that returns numbers, starting with 1, and each sequence will increase by one (returning 1,2,3,4,5 etc.):s
class Mynumber:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = Mynumber()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
# StopIteration
# The example above would continue forever if you had enough next() statements, or if it was used in a for loop.
# To prevent the iteration to go on forever, we can use the StopIteration statement.
class Mynumber:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = Mynumber()
itrrs = iter(myclass)
for x in itrrs:
print(x)
| true |
69a9fdc3719c0a57c6a1fa34158abadf98207785 | gselva28/100_days_of_code | /DAY 09/dictionary_basics.py | 833 | 4.46875 | 4 | programming_dictionary = {
"Bug": "An error in a program that prevents the program from running as expected.",
"Function": "A piece of code that you can easily call over and over again."
}
#retrieving items from dictionary
print(programming_dictionary["Function"])
#adding new items to dictionary
programming_dictionary["Loop"] = "The action of doing something over and over again."
print(programming_dictionary["Function"])
#create an empty dictionary
empty_dictionary = {}
#delete an existing dictionary
#programming_dictionary = {}
#Edit an item in an dictonary
programming_dictionary["Bug"] = "A moth in your computer."
print(programming_dictionary)
#loop through a dictionary
for key in programming_dictionary:
print(key) # prints the keys
print(programming_dictionary[key]) # prints the values
| true |
d1ea659d46a4db3bf07c7c28afb35c500f5dcc86 | HackerCJC/py-study | /basis/AdvancedFeatures_iterator.py | 2,579 | 4.21875 | 4 | #!/usr/bin/env python3
# ! __*__ coding=utf-8 __*__
'''python 高级特性之迭代器:与普通迭代不同
python 凡是可以用for循环迭代的都是可迭代对象即Iterable,
但iterable并非iterator,凡是可以用next()方法获取下一个元素的就是iterator
list tuple dict set str 都是iterable不是iterator
iterator 表示一个无限大的数据流,通过next方法可以不断获取其下一个元素直至没有元素抛出StopIteration
iterator可以存储无限大自然数,list是永远不可能存储全体自然数的。计算是惰性的,只有需要返回下一个数据时才会计算
iterable对象可以通过iter()方法转换为iterator对象
python中for循环的本质就是iterator 通过不断调用next对象实现的
'''
if __name__ == '__main__':
from collections import Iterable
# 使用 isinstance可以判断对象是否是可迭代的
print(isinstance([], Iterable))
print(isinstance((), Iterable))
print(isinstance({}, Iterable))
print(isinstance(set(), Iterable))
print(isinstance('A,B,C', Iterable))
print(isinstance(100, Iterable))
# 判断一个对象是否是 Iterator
from collections import Iterator
print((x for x in range(10)))
print(isinstance((x for x in range(10)), Iterator))
print(isinstance([], Iterator))
print(isinstance({}, Iterator))
print(isinstance(set(), Iterator))
print(isinstance((), Iterator))
print(isinstance('abc', Iterator))
print(isinstance(100, Iterator))
# 使用iter()方法可以把iterable对象转换为iterator
print(isinstance(iter('abc'), Iterator))
# print(isinstance(iter(123), Iterator)) # TypeError: 'int' object is not iterable
'''
Python的for循环本质上就是通过不断调用next()函数实现的,例如:
'''
for x in [1, 2, 3, 4, 5]:
pass
it = iter([1, 2, 3, 4, 5])
while True:
try:
# 获得下一个值:
x = next(it)
except StopIteration as e:
# 遇到StopIteration就退出循环
break
'''
小结
凡是可作用于for循环的对象都是Iterable类型;
凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
Python的for循环本质上就是通过不断调用next()函数实现的,例如:
'''
| false |
621544797419139451bcc25a1ce8a0c8b7620e84 | S-SANTHI25/Python-A-Z-Coding-Q-A-Preparation | /fibonacci series upto given limit.py | 365 | 4.15625 | 4 | #FIBONACCI SERIES UPTO GIVEN LIMIT
limit = int(input("Enter a limit to stop the series:"))
pos1 = 0
pos2 = 1
limit_track = 2
print(pos1)
print(pos2)
for i in range(2,limit):
#fibonacci series means current number and previous number added to give the next number
pos3 = pos1 + pos2
pos1 = pos2
pos2 = pos3
print(pos3)
#fibonacci series found
| true |
3975f814207ed6223624d4f3d4f877e9c2339ef7 | max-belichenko/Palindrome | /palindrome.py | 1,287 | 4.5625 | 5 | def is_palindrome(text):
"""
Returns True if text is a palindrome, or False otherwise.
Takes any text as an argument. Removes all symbols except letters, and leads text to lowercase before check.
Example of palindromes:
"Rotor"
"Racecar"
"Radar"
"Red rum, sir, is murder"
"Eva, can I see bees in a cave?"
"No lemon, no melon"
"""
clear_text = ''.join([symbol for symbol in text if symbol.isalpha()])
clear_text = clear_text.lower()
return clear_text == clear_text[::-1]
if __name__ == '__main__':
assert(is_palindrome('А роза упала на лапу Азора') == True)
assert(is_palindrome('Я иду с мечем, судия!') == True)
assert(is_palindrome('') == True)
assert(is_palindrome('A') == True)
assert(is_palindrome('123') == True)
assert(is_palindrome('Муза! Ранясь шилом опыта, ты помолишься на разум') == True)
assert(is_palindrome('AsDf.,mm/.,m/..,#$(@#*&$Fd SA') == True)
assert(is_palindrome('AsdfdsE') == False)
text = input('Enter text to check if it is a palindrome:')
if is_palindrome(text):
print('Yes! This is a palindrome.')
else:
print('No. It is not a palindrome.') | false |
d64f5af98873b1866dbf1e2cd226be85c7708a20 | ghkdwl1203/python-ml | /Algorithm/chap4/example1.py | 701 | 4.125 | 4 | class Node: # 틀
def __init__(self,data, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
def init_list():
global node_A
node_A = Node("A")
node_B = Node("B")
node_D = Node("D")
node_E = Node("E")
node_A.next = node_B
node_B.next = node_D
node_B.prev = node_A
node_D.next = node_E
node_D.prev = node_B
def print_list():
global node_A
node = node_A
while node:
print(node.data)
node= node.next
print
if __name__=='__main__': # 해당 파이썬 파일을 실행했을때만 동작하는 if문
print("연결리스크초기화후")
init_list()
print_list()
| false |
aea47119e7e2e0abb81e193b57ed9d80d46268d1 | Ghanashyam-Bhat/Engineering-Sem-1 | /Modules/password_strength_check.py | 1,410 | 4.125 | 4 |
def password_var(given):
print("""
The strong password must meet the following conditions :
1. Atleast eight charecters
2. Atleast one Uppercase and one Lowercase letter
3. Atleast one special symbols or a space
4. Atleast one numerical charecter
""")
numbers = "1234567890"
alph_l = "abcdefghijklmnopqrstuvwxyz"
alph_h = alph_l.upper()
spcl_char = r"""`~!@#$%^&*()_-+=|\}{][';":/.,<>? """
w = 0 # Numerical charecters
x = 0 # Lowercase alphabet
y = 0 # Uppercase alphabet
z = 0 # Special charecter
for i in given:
if i in alph_l:
x += 1
if i in numbers:
w += 1
if i in alph_h:
y += 1
if i in spcl_char:
z += 1
if len(given) <= 8 or x == 0 or z == 0 or w == 0:
print("Your password must meet the following conditions to be classfied as strong")
print("Your password must have:")
if len(given) < 8:
print("Lenghth must be atleast 8")
if x == 0:
print("Atleast one lowercase charecter")
if y == 0:
print("Atleast one uppercase charecter")
if z == 0:
print("Atleast one special charecter")
if w == 0:
print("Atleast one numerical charecter.")
if len(given) >= 8 and x != 0 and z != 0 and w != 0:
print("Your password is strong")
| false |
bcfd44be15fc6a3601ed59edf8dcb725ce4818bf | Ghanashyam-Bhat/Engineering-Sem-1 | /Word_guess.py | 1,266 | 4.125 | 4 | #Word guessing game
print("Guess the word.")
print(" 5 wrong attempts are allowed")
new_word = ('unkown').lower()
given = new_word
word_space = ""
for x in new_word :
word_space += x
word_space += " "
word_list = word_space.split(" ")
word_list.pop()
code_together = "*"*len(new_word)
code = ""
for g in code_together :
code += g
code += " "
code_list = code.split(" ")
code_list.pop()
print(code)
r = 0
p = 0
while r <= 5 :
entered = input("> ").lower()
if entered in new_word:
place = new_word.find(entered)
code_list.pop(place)
code_list.insert(place , entered)
code = ""
for i in code_list :
code += i
print(code)
word_list.pop(place)
word_list.insert( place , "+")
new_word = ""
for y in word_list :
new_word += y
p += 1
if p == len(given) :
print("You won")
break
elif entered not in new_word :
if 5-r > 0 :
print("Wrong")
r += 1
print(f" {5 - r} more wrong guesses are allowed")
else :
print("You lose")
print(f"The secret word is '{given}'")
break | true |
e2fc9efe69b16835f6a26fe0788d267cfd506d7e | Ghanashyam-Bhat/Engineering-Sem-1 | /Lab/Week3/Clear_RightMost_SetBit.py | 371 | 4.28125 | 4 |
#To clear right most set bit
n = int(input("Enter an number: "))
#Convert the entered value into binary
print(f"Binary value of the entered number {bin(n)}")
if n%2 == 0 :
print("The last bit of a even number is always a set")
else :
#Clearing the last set bit and printing the binary value
print("After clearing last set bit")
z = n&(n-1)
print(bin(z))
| true |
ca56ce5f7096daa97d95c993acd3f5c251cf7986 | rubengr16/BeginnersGuidePython3 | /4_strings/1_single_vs_double_quotes.py | 415 | 4.375 | 4 | # Single quotes and double quotes are the same for the python interpreter
print("Hello World")
print('Hello World') # Although for convention we will use single quotes
# Using quotes inside the string
print('He said "to be or not to be"')
print("And ended that's the question")
# Multiline strings with """
print("""
Hi
World
Bye
""")
# Also saving the string on a variable
x = """Goodbye
Earth
Hello"""
print(x) | true |
52d3b1909b9c3c4badd823105e6fb52e7f649a73 | rubengr16/BeginnersGuidePython3 | /6_if/4_else.py | 382 | 4.3125 | 4 | # The else part is optional and will be run if the conditional part of the if statement returns False,
# if an else is present, it is guaranteed that at least the if or the else will be executed
num = int(input('Enter a number: '))
if num <= 0:
if num == 0: # Nested if
print('It is zero')
else:
print('It is negative')
else:
print('It is possitive') | true |
a6e4464923043feedadbafe709a246f60eec06cb | rubengr16/BeginnersGuidePython3 | /4_strings/4_length.py | 326 | 4.59375 | 5 | # len(string_name) function reveals us the number of characters of a string
my_string = 'Good'
my_string2 = 'Day'
my_string3 = 'Hello world'
# Length of my_string, my_string2 and new_string
print('my_string length: ', len(my_string))
print('my_string2 length: ', len(my_string2))
print('my_string3 length: ', len(my_string3)) | true |
3c4c028b8cdc9d4e3bbd71dec171b8fd9dfacb43 | esecuritynet/ElioSession1 | /Week 7 -Q1.py | 955 | 4.3125 | 4 | #WEEK 7 - QUESTION 1
a = [ 66.25, 333, 333, 1, 1234.5 ]
a.insert(2, -1)#The method insert()does not return any value but it inserts
#the given element at the given index.
a.append(333)#The method append()does not return any value but updates
# existing list,add at the end of the list the item/s given.
print (" The new list is : ", a )
print (" The lowest index in list for the item 333: ", a.index(333))
a.remove(333)#This method remove()does not return any value but removes
#the given object from the list.
print (" The new list after removed the item 333 is : ", a)
a.reverse()#The method reverse()does not return any value but reverse
#the given object from the list.
print (" The new reverse list is : ", a)
a.sort()#The method sort()does not return any value but it changes from
#the original list.
print (" The new list with changed order of the items is : ", a )
| true |
440bf92bb12b3cdc3357e52cb13f39c590e92518 | makeTaller/Python | /wlength.py | 291 | 4.25 | 4 |
# This program counts the number of words in a sentence
# by: Kirk Tolliver
def main():
sentence = input("Enter the sentence: ")
word = sentence.split()
for w in word:
w = len(w)
avg_word = w
result = avg_word + w //w
print(len(word))
main()
| true |
f09afaf13858479e2d32002869c61c5df7ba1e91 | jailukanna/Python-tuts | /decorators.py | 1,736 | 4.84375 | 5 | # decorators
# Following are important facts about functions in python that are useful to understand decorator
# functions
# In python we can define a function inside a function
# In python a function can be passed as parameter to another function
# Adds a welcome message to the string
def messagewithwelcome(str):
#Nsted function
def welcome():
return 'welcome to '
# Return cancatenation of welcome
# and str
return welcome() + str
# to get site name which welcome is added
def site(site_name):
return site_name
print(messagewithwelcome('geeksforgeeks'))
# function decorator
# A decorator is a function that takes a function as its only parameter and returns a function.
# this is helpful to wrap functionality with the same code over and over again
# the above code can be written as follow
# we use @func_name to specify decorator to be applied on another function
# Adds welcoome message to the string
# returned by fun(). takes fun() as
# parameter and returns welcome()
def decorate_message(fun):
# nested function
def addWelcome(site_name):
return 'welcome to' + fun(site_name)
# Decorator return the function
return addWelcome
@decorate_message
def site(site_name):
return site_name
# Driver code
# this call is equivalent to call to
# decorate_message () with function
# site('geeksforgeeks) as parameter
print(site('geeks for geeks'))
# Decorator can also be useful to attach data to functions
# A python example to demonstrate that
# Decorators can be useful to attach data to functions
# data to func
def attach_data(func):
func.data = 3
return func
@attach_data
def add(x, y):
return x + y
print(add(2, 3))
print(add.data) | true |
b18e1c96f21978bd9b74b492531c1d74b07193bc | Piyushsrii/Python_Data_Structure_Program | /Basic_core_Programing/Tuple/CheckTuple.py | 653 | 4.3125 | 4 | '''Write a Python program to convert a list to a tuple.'''
class ListToTuple:
#Create method checkTuple
def toTuple(self,ListOfNum):
"""
:param ListOfNum: element the value
:return: tuple value
"""
tupleOfNum = tuple(ListOfNum)
print("Tuple Data : ",tupleOfNum)
listData = ListToTuple()
rangeVal = int(input("Enter The range of value you want to enter : "))
ListOfNum = [ ]
for i in range(1,rangeVal+1):
val = int(input("Enter The value for tuple : "))
ListOfNum.append(val)
print("List Data :- ",ListOfNum)
listData.toTuple(ListOfNum) | true |
01dd28a44a0c7a899537711466ddd617c1a182f0 | Piyushsrii/Python_Data_Structure_Program | /Basic_core_Programing/Tuple/Removed.py | 1,202 | 4.28125 | 4 | '''Write a Python program to remove an item from a tuple.'''
class RemoveItem:
#Create methos to remove value
def toRemoveItem(self,tupleValue,remVal,indexVal):
'''
:param:tupleValue: tuple value
:param:remVal: remove value
:param:index: index value
:return : return after the remove
'''
tupleValue = tupleValue[:indexVal] + tupleValue[indexVal+1:]
print("Using Merging Removed Value : ",tupleValue)
listTuple = list(tupleValue)
listTuple.remove(remVal)
tupleValue = tuple(listTuple)
print("Using Conversion Removed Value : ",tupleValue)
try :
tupleData = RemoveItem()
rangeVal = int(input("Enter The range of value you want to enter : "))
tupleValue = ( )
for j in range(rangeVal):
val = input("Enter The Int value for tuple : ")
tupleValue = tupleValue[ : j] + (val,) + tupleValue[ j : ]
print("Tuple Data :- ", tupleValue)
indexVal = int(input("Enter index value you want to Remove : "))
remVal = input("Enter value you want to Remove : ")
except RemoveItem:
tupleData.toRemoveItem(tupleValue,remVal,indexVal) | false |
dfeeae4fe03d2e434ac74f108fd6187801e9aba6 | Piyushsrii/Python_Data_Structure_Program | /Basic_core_Programing/Dictionary/IterateDict.py | 628 | 4.28125 | 4 | '''Write a Python program to iterate over dictionaries using for loops'''
class IterateDictionary:
#create a method for iteration
def iterate(self, dictOfNum):
print("Dictionary : ", dictOfNum)
for key, value in dictOfNum.items():
print(key, " is the key belongs to " , dictOfNum[key])
dictionary = IterateDictionary()
rangeVal = int(input("Enter The range of value you want to enter : "))
dictOfNum = { }
for i in range(1,rangeVal+1):
key = input("Enter The Key : ")
val = input("Enter The value for dictionary : ")
dictOfNum.setdefault(key, val)
dictionary.iterate(dictOfNum) | false |
f3d669a4bb63e52de4d420c7da9c3867b9a9f078 | Piyushsrii/Python_Data_Structure_Program | /Basic_core_Programing/Set/RemoveItem.py | 719 | 4.25 | 4 | '''Write a Python program to remove item(s) from set'''
class RemoveItems:
#create method to remove element
def toremove(self,setValue,rmVal):
for i in range(rmVal):
setValue.pop()
print(setValue)
try:
setValue = set()
rangeVal = int(input("Enter The Range Of Values You Want To Enter : "))
for i in range(1, rangeVal + 1):
valAdd = input("Enter The String Or Value : ")
setValue.add(valAdd)
print(setValue)
rmVal = int(input("How Many Items You Want To Remove From List : "))
except setValue:
print("enter the correct value")
if __name__=="__main__":
setMembers = RemoveItems()
setMembers.toremove(setValue,rmVal) | true |
a51360172ece2e43af26774ed243ef2d4420be4e | Environmental-Informatics/building-more-complex-programs-with-python-mboodagh | /program_5.2.py | 1,142 | 4.71875 | 5 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 31 10:05:34 2020
@author: mboodagh
"""
""" The goal of this program is to check whether
the Fermant's principle holds for a set of values provided by the user"""
# Define a function to check Fermant's theorem and prints the results
def check_fermat ():
# Ask for the inputs and turn them into integers
a=float(input ('please enter the first number>1 ')) # The number must be >1 to be turned into a positive integer
b=float(input ('please enter the second number>1 ')) # The number must be >1 to be turned into a positive integer
c=float(input ('please enter the third number>1 ')) # The number must be >1 to be turned into a positive integer
n=float(input ('please enter the power >3 = ')) # The number must be >3 to be turned into a an integer>2
# turning the inputs into integers
a=int(a)
b=int(b)
c=int(c)
n=int(n)
# Print the outcome
if a**n+b**n != c**n:
print ('N0, that doesnt work')
else:
print('Holy smokes, Fermat was wrong')
# run the function
check_fermat ()
| true |
a596d636bcf6f1263ac16ebda90c822e4c49ddd5 | rritec/Trainings | /01 DS ML DL NLP and AI With Python Lab Copy/02 Lab Data/Python/Py21_2_Create_Simple_Dictionary.py | 274 | 4.28125 | 4 | #Create dictionary
world = {"China":1.38,"India":1.34,"USA":0.32}
#print data type
print(type(world))
# Print out the keys in world
print(world.keys())
# Print out the values in world
print(world.values())
#Get values using keys: Print India population
print(world["India"]) | true |
7f53e538e3245e10358396dc64b3308161af3511 | rritec/Trainings | /01 DS ML DL NLP and AI With Python Lab Copy/02 Lab Data/Python/Py29_2_list_comprehension_with_range.py | 285 | 4.28125 | 4 | print("01. nested loops ")
pairs_1 = []
for num1 in range(0, 2):
for num2 in range(6, 8):
pairs_1.append((num1, num2))
print(pairs_1)
print("02. nested loops using list comprehension ")
pairs_2 = [(num1, num2) for num1 in range(0, 2) for num2
in range(6, 8)]
print(pairs_2) | true |
f4caaa7fa0102e1cee12ba8836e40c0348327e75 | rritec/Trainings | /01 DS ML DL NLP and AI With Python Lab Copy/02 Lab Data/Python/Py3_datatype_conversion.py | 426 | 4.21875 | 4 | # calculating simple interest
savings = 100
interest=12
total_amount = savings + 100 * interest * 2/100
# convert total amount as string and print user friendly info
print("I started with $" + str(savings) + " and now have $" + str(total_amount) + ". Awesome!")
# Definition of pi_string
pi_string = "3.1415926"
print(type(pi_string))
# Convert pi_string into float: pi_float
pi_float = float(pi_string)
print(type(pi_float))
| true |
97a7e33e2d76531d512751ba7a492a6e7c71d2b4 | dodevs/Ernani_prog2 | /revisao/exercicio1-2.py | 840 | 4.15625 | 4 | '''
Exercicio de revisao 1 (uniao)
Criar um algoritmo para retornar a uniao de duas listas
Exercicio de revisao 2 (intersecao)
Criar um algoritmo para retornar a intersecao de duas listas
'''
def intersecao(listaA, listaB):
listaAIB = []
#somente adiciona a listaA os termos que se repetem
listaAIB.extend([item for item in listaA if(item in listaB)])
return listaAIB
def uniao(listaA, listaB):
listaAUB = []
for i in range(len(listaA)):
listaAUB.append(listaA[i])
#somente adiciona a listaA os termos que nao se repetem
listaAUB.extend( [item for item in listaB if not(item in(listaAUB))])
return listaAUB
def main():
listaA = [1,3,5,7]
listaB = [2,1,3,5]
print(uniao(listaA, listaB))
print(intersecao(listaA, listaB))
if __name__ == '__main__':
main()
| false |
dae4ebcfc10e71273c640b21618c54d0122bc59a | Chris-Lenz/Python_Learning | /quiz13.py | 377 | 4.40625 | 4 | # 1) Complete the function to return the result of the conversion
def convert_distance(miles):
km = miles*1.6
return(km)
my_trip_miles = 55
# 2) Convert my_trip_miles to kilometers by calling the function above
my_trip_km = convert_distance (my_trip_miles)
print ("the distance in kilometers is: " + str(my_trip_km ))
print (my_trip_km * 2)
| true |
5512c8ee7d36ae69db00e87dacf2f0641b0871fa | yashpupneja/Coding-Problems | /Leetcode Problems/12. Move Zeroes.py | 742 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
"""
def moveZeroes(nums):
count=0
for i in range(len(nums)):
if nums[i]!=0:
nums[count]=nums[i]
count+=1
while count<len(nums):
nums[count]=0
count+=1
return nums
def main():
num1=list(map(int,input().split()))
print(moveZeroes(num1))
if __name__=='__main__':
main() | true |
869f7b756925b9bad6b30e202e507ad870a72939 | yashpupneja/Coding-Problems | /Leetcode Problems/05. Duplicate Zeros.py | 1,105 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note that elements beyond the length of the original array are not written.
Do the above modifications to the input array in place, do not return anything from your function.
Example 1:
Input: [1,0,2,3,0,4,5,0]
Output: null
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]
Example 2:
Input: [1,2,3]
Output: null
Explanation: After calling your function, the input array is modified to: [1,2,3]
Note:
1 <= arr.length <= 10000
0 <= arr[i] <= 9
"""
def duplicateZeros(arr):
"""
Do not return anything, modify arr in-place instead.
"""
n=len(arr)
i=0
while i<n:
if arr[i]==0:
arr.pop()
arr.insert(i+1,0)
i+=1
i+=1
return arr
def main():
num=list(map(int,input().split()))
print(duplicateZeros(num))
if __name__=='__main__':
main() | true |
9badc088041585be80f938999c8adc4457eecedb | adnan-alam/Algorithms-implemented-in-Python | /Algorithms/is-prime.py | 368 | 4.21875 | 4 |
# algorithm to find if a number is Prime or not
from math import sqrt
for _ in range(int(input())):
n = int(input())
sq = sqrt(n)
i = 2
if n == 1:
print("Not prime")
else:
while i <= sq:
if n%i == 0:
print("Not prime")
break
i += 1
else:
print("Prime")
| false |
8975e618849599b3065ede62f34aeb9c633b9c1e | jglowacz/hello_world | /lottery_numbers.py | 1,661 | 4.1875 | 4 | '''
This program generates 6 random numbers for Polish Lotto Lottery.
The aim is to draw 6 unique numbers out of 49.
'''
# Module needed for drawing random numbers and for simulating draw.
import random, time
# Module needed to exit the program.
from sys import exit
MIN_RANDOM = 1
MAX_RANDOM = 49
results = []
def main():
welcome_user()
draw_numbers()
continue_or_exit()
def welcome_user():
ask_user_name = input('Please enter your name to start: ')
user_name = str(ask_user_name)
greeting = f'Hello {user_name}!\nWelcome to the Lottery Numbers Generator!'
print(greeting)
def draw_numbers():
load_results()
for i in range(6):
generate_numbers()
show_results()
def load_results():
waiting_prompt = 'Please wait while your numbers are being drawn.'
print(waiting_prompt)
time.sleep(5)
def generate_numbers():
draw = random.randint(MIN_RANDOM, MAX_RANDOM)
if draw in results:
generate_numbers()
else:
results.append(draw)
def show_results():
results.sort()
final_numbers = ', '.join(str(r) for r in results)
display_final_numbers = f'Your lucky numbers are: {final_numbers}.'
print(display_final_numbers)
time.sleep(5)
def continue_or_exit():
user_input = input('Do you want to try once again? (y/n): ')
answer_yes = user_input.lower().startswith('y')
answer_no = user_input.lower().startswith('n')
if answer_yes:
repeat_code()
elif answer_no:
exit(0)
else:
continue_or_exit()
def repeat_code():
results.clear()
draw_numbers()
continue_or_exit()
if __name__ == '__main__':
main() | true |
0c9f8fdf5e359ecac8e3ea309a18032683c16ad7 | evanwangxx/leetcode | /python/21_Merge_Two_Sorted_Lists.py | 1,246 | 4.21875 | 4 | # Merge two sorted linked lists and return it as a new list.
# The new list should be made by splicing together the nodes of the first two lists.
#
# Example:
# Input: 1->2->4, 1->3->4
# Output: 1->1->2->3->4->4
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1:
return l2
if not l2:
return l1
if l1.val <= l2.val:
result = ListNode(l1.val)
result.next = self.mergeTwoLists(l1.next, l2)
return result
else:
result = ListNode(l2.val)
result.next = self.mergeTwoLists(l1, l2.next)
return result
def show(self, x: ListNode):
print(x.val)
if x.next:
self.show(x.next)
if __name__ == "__main__":
n1_1 = ListNode(1)
n1_2 = ListNode(2)
n1_4 = ListNode(4)
n2_1 = ListNode(1)
n2_3 = ListNode(3)
n2_4 = ListNode(4)
n1_2.next = n1_4
n1_1.next = n1_2
n2_3.next = n2_4
n2_1.next = n2_3
s = Solution()
result = s.mergeTwoLists(n1_1, n2_1)
print(s.show(result))
| true |
7e825804f23c5ac27be2ce1a54af95a1a8fb96bf | tcjiang9/Spirograph | /spiro.py | 257 | 4.125 | 4 | import math
import turtle
def draw_circle(x, y, r):
turtle.up()
turtle.setpos(x + r, y)
turtle.down()
for i in xrange(0, 365, 5):
a = math.radians(i)
turtle.setpos(x + r*math.cos(a), y + r*math.sin(a))
draw_circle(100, 100, 50)
turtle.mainloop()
| false |
82c9eb9432a12e6b6dc5e2d78e2d8532fda6786e | Juleraty/Programacao-com-Interfaces-Graficas-AP2X | /main.py | 1,511 | 4.1875 | 4 | '''
Encontre as duas linhas que, juntas com o eixo-x, formam um recipiente que contem a
maior quantidade de agua, conforme pode ser visto na figura 1.
Note que não é permitido inclinar o recipiente.
'''
class Solution(object):
'''
Estamos criando um subconjunto de cada contêiner possível a partir da
lista de alturas fornecida a nós. Portanto, a complexidade do tempo é O(N²)
'''
def maxArea(self, height):
max_water = 0
for left in range(len(height) - 1):
for right in range(left + 1, len(height)):
max_water = max(max_water, min(height[left], height[right]) * (right - left))
return max_water
def maxAreaOnePass(self, height):
''' Estamos analisando a lista apenas uma vez.
Portanto, a complexidade do tempo é O(N)'''
left = 0
right = len(height) - 1
max_water = 0
while (left < right):
max_water = max(max_water, min(height[left], height[right]) * (right - left))
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_water
def main():
test = [[1, 1],
[1, 8, 6, 2, 5, 4, 8, 3, 7],
[4, 3, 2, 1, 4],
[],
[1, 2, 1],
[1, 2, 3, 4, 5, 6, 7, 8, 9]
]
s = Solution()
for t in test:
r1 = s.maxArea(t)
r2 = s.maxAreaOnePass(t)
print("{} = {} = {}".format(t, r1, r2))
main()
| false |
b84c1868d371ea03d78e453d85bd1781add91d38 | RichardYoung5/savy | /proj02/proj02_01.py | 960 | 4.3125 | 4 | # Name:
# Date:
# proj02: sum
# Write a program that prompts the user to enter numbers, one per line,
# ending with a line containing 0, and keep a running sum of the numbers.
# Only print out the sum after all the numbers are entered
# (at least in your final version). Each time you read in a number,
# you can immediately use it for your sum,
# and then be done with the number just entered.
#Example:
# Enter a number to sum, or 0 to indicate you are finished: 4
# Enter a number to sum, or 0 to indicate you are finished: 5
# Enter a number to sum, or 0 to indicate you are finished: 2
# Enter a number to sum, or 0 to indicate you are finished: 10
# Enter a number to sum, or 0 t
loop_control = True
solve = 0
while loop_control ==True:
Number = raw_input("Enter a number to add to the Equation, or a 0 to show you are finished: ")
if (Number) == "0":
loop_control = False
solve = int(Number) + solve
print solve,'is your sum.'
| true |
db5325d33de235778ce676fcaf267a67a9134656 | jonbleiberg88/deep_path | /utils/file_utils.py | 1,314 | 4.46875 | 4 | import pickle
import sys
def load_pickle_from_disk(file_path):
"""
Helper function that loads a pickle and returns
the resulting python object. Raises an exception
if the provided file does not exist.
Args:
file_path (String): Path to the pickle we want to load
Returns:
pickle_contents (Type depends on what pickle contains)
"""
try:
pickle_contents = pickle.load(open(file_path, "rb"))
return pickle_contents
except Exception as error:
print("Couldn't open " + file_path + ". Did you run the helper scripts first?")
print("Exitting...")
sys.exit()
def write_pickle_to_disk(file_name, python_object):
"""
Helper function to write python_object to disk
as a pickle file with name file_name. Used to
make other code easier to read
Args:
file_name (String): File name of new pickle file
python_object (Any): Python object to be pickled
Returns:
None (output saved to disk)
"""
try:
file_pointer = open(file_name, "wb")
pickle.dump(python_object, file_pointer)
except Exception as error:
print("Unable to write pickle " + file_name + " to disk. Do you have sufficient permissions?")
print("Exitting...")
sys.exit()
| true |
34643802d2d70b9fc3a39a1b3df061511e0434ea | gaurBrijesh/Python | /PycharmProjects/aerology/__format__function__.py | 243 | 4.1875 | 4 | name = "Brijesh"
age = 29
#printing values using formating
print ("The name is %s and the age is %d"%(name,age))
#printing values using .format function (this function is a list)
print ("The name is {} and the age is {}".format(name,age))
| true |
4b639423282f12473f79934bf8bfc8d007ce392b | gaurBrijesh/Python | /PycharmProjects/aerology/vowelFinder.py | 206 | 4.15625 | 4 | c = raw_input("Enter the alphabet:")
if((c=='a')|(c=='e')|(c=='i')|(c=='o')|(c=='u')):
print (c, 'is a vowel.')
if c=='a':
print (c,'is an vowel')
else:
print (c, 'is a consotant')
| false |
94775507bc5a0163861f074e28ead051c8d45642 | anmoltaneja78/assignment | /assignment7.py | 547 | 4.15625 | 4 | # q-1 Get Keys Corresponding to a Value in User Defined Dictionary
dict={}
for i in range(1,5):
key = input("Enter key: ")
value = input("Enter value: ")
dict[key] = value
print(dict)
# q-2 Nested Dictionary
dict1={}
dict2={}
for i in range(1,4):
dict2={}
name = input("Enter name ")
for j in range(1,4):
sub=input("enter subject")
marks=int(input("enter marks"))
dict2[sub]=marks
dict1[name]=dict2
print(dict1)
student=input("Enter the student's name")
print(dict1[student])
| true |
05d39980e82c44f980d8b07ee44711f8b7b8c2af | lwd2451/Algorithm_case | /求平方根.py | 376 | 4.125 | 4 | # -*- coding: utf-8 -*-
#方法一
num=float(input('请输入一个数字:'))
num_sqrt=num**0.5
print('%0.3f的平方根是%0.3f' %(num,num_sqrt))
#方法二
'''计算复数(负数)的平方根
import cmath
num=int(input("请输入一个数字:"))
num_sqrt=cmath.sqrt(num)
print('{0}的平方根是{1:0.3f}+{2:0.3f}i'.format(num,num_sqrt.real,num_sqrt.imag))
'''
| false |
5fab724186be263332278ded9c715bf63346b3c9 | Yasir77788/Simple-Binary-Search | /binary.py | 1,448 | 4.1875 | 4 |
"""
This algorithm uses three index variables: first , last , and middle . The first and last
variables mark the boundaries of the portion of the array currently being searched. They
are initialized with the subscripts of the list’s first and last elements. The subscript of the
element halfway between first and last is calculated and stored in the middle variable.
If the element in the middle of the array does not contain the search value, the first or
last variables are adjusted so that only the top or bottom half of the list is searched
during the next iteration. This cuts the portion of the array being searched in half each time
the loop fails to locate the search value.
"""
originalList = [7, 2, 9, 4, 6, 5, 1, 8, 3,10]
myList = sorted(originalList)
print("\nThe original list is {}".format(originalList))
print("\nThe sorted list is {}".format(myList))
first = 0
last = len(myList) - 1
position = -1
found = False
num = int(input("\nEnter the number you want to search: "))
while (not found and first <= last):
middle = (first + last)//2
if(myList[middle] == num):
found = True
position = middle
elif (myList[middle] > num):
last = middle - 1
else:
first = middle + 1
if position == -1:
print("\nNot found.")
else:
print("\nThe number u entered, {} , has been found".format(myList[position]) )
| true |
62e078afbfd02e8b518b9198caef70b39a1617ff | pranjaldarekar/Pranjal-Python | /Assignment1_6.py | 258 | 4.125 | 4 | #program to check +ve,-ve,zero number
def checknum():
no = int(input("Enter a number: "));
if no > 0:
print(" Number is Positive number")
elif no == 0:
print("Number is Zero")
elif no < 0:
print("Number is Negative number")
checknum() | true |
3596fdd088fa42857632ae4dbb6741b096f62762 | venkatajetty/Python | /Fibonaci_sequence.py | 617 | 4.125 | 4 | #Printing of fibonaci sequence in a certain range
Last_number = int(input("Enter the last number : "))
num_of_fib = int(input("how many number should be generated between the range 1 and " + str(Last_number) + " : "))
Sum = [0, 1]
i = 1
a = 0
b = 1
c = 1
for i in range(1,num_of_fib):
if i < num_of_fib:
i = i+1
a = b
b = c
c = a + b
if c < Last_number:
Sum.append(c)
else:
break
print("fibonaci sequence ")
print(Sum)
| true |
bb2b73f8305f2d4c8859339d1363cfa0378ee2ab | another-godel/6.0001 | /test/test.py | 2,088 | 4.40625 | 4 | import string
VOWELS_LOWER = 'aeiou'
CONSONANTS_LOWER = 'bcdfghjklmnpqrstvwxyz'
def build_transpose_dict(vowels_permutation):
'''
vowels_permutation (string): a string containing a permutation of vowels (a, e, i, o, u)
Creates a dictionary that can be used to apply a cipher to a letter.
The dictionary maps every uppercase and lowercase letter to an
uppercase and lowercase letter, respectively. Vowels are shuffled
according to vowels_permutation. The first letter in vowels_permutation
corresponds to a, the second to e, and so on in the order a, e, i, o, u.
The consonants remain the same. The dictionary should have 52
keys of all the uppercase letters and all the lowercase letters.
Example: When input "eaiuo":
Mapping is a->e, e->a, i->i, o->u, u->o
and "Hello World!" maps to "Hallu Wurld!"
Returns: a dictionary mapping a letter (string) to
another letter (string).
'''
transpose_dict = {}
for char in VOWELS_LOWER:
transpose_dict[char] = vowels_permutation[VOWELS_LOWER.index(char)]
transpose_dict[char.upper()] = transpose_dict[char].upper()
for char in CONSONANTS_LOWER:
transpose_dict[char] = char
transpose_dict[char.upper()] = char.upper()
return transpose_dict
#print(build_transpose_dict("eaiuo"))
def apply_transpose(text, transpose_dict):
'''
transpose_dict (dict): a transpose dictionary
Returns: an encrypted version of the message text, based
on the dictionary
'''
transposed = ''
for char in text:
if char in ' .,!':
transposed += char
elif (char in string.ascii_lowercase) or (char in string.ascii_uppercase):
transposed += transpose_dict[char]
else:
raise ValueError('Not a valid string')
return transposed
print(apply_transpose('con cho nay', build_transpose_dict("eaiuo"))) | true |
6347f7f7816feadb3b2bb3ad14bbea2240e623fc | mtmcIntosh/languages | /make-tutorial/tutorial-materials/testing-materials/count_records.py | 558 | 4.125 | 4 | import sys
# Given a file name, count the number of records
# in the file. Lines starting with "D" or "#"
# are ignored.
def count_records(filename):
source = open(filename, 'r')
count = 0
# Count number of data records.
for line in source:
if line.startswith('#'): # Skip comments.
pass
elif line.startswith('D'): # Skip title line.
pass
else:
count += 1
source.close()
return count
if (len(sys.argv) < 2):
sys.exit("Missing file name")
filename = sys.argv[1]
print count_records(filename)
| true |
b89d009e9abc2abbaf59a6078bc7d0e161ba3265 | subhajitsaha1903/PythonTutorial | /time-till-deadline.py | 1,028 | 4.15625 | 4 | # Youtibe link: https://www.youtube.com/watch?v=t8pPdKYpowI&t=30s&ab_channel=TechWorldwithNana
import datetime
user_input = input("Enter the goal deadline with date, separated by colon: \n")
# input format : learn python:20.03.2021
# here, 'learn python' is the goal & '20.03.2021' is the deadline. Both are separated by :
input_list = user_input.split(":")
goal = input_list[0]
deadline = input_list[1]
# print(input_list)
# print(datetime.datetime.strptime(deadline, "%d.%m.%Y"))
# print(type(datetime.datetime.strptime(deadline, "%d.%m.%Y")))
deadline_date = datetime.datetime.strptime(deadline, "%d.%m.%Y")
today_date = datetime.datetime.today()
# print(today_date)
days_remaining = deadline_date-today_date
# print("Time remaining for My Goal", goal, "is", days_remaining)
print("Dear User, \nTime remaining for My Goal",
goal, "is", days_remaining.days, "days")
print("Dear User, \nTime remaining for My Goal",
goal, "is", int((days_remaining.total_seconds())/3600), "hours")
| false |
042c7516ac960c557428de0ba9a537fd158a6126 | kshitijkorde/Python_Misc | /Rotate_1DList_Round_Robin.py | 371 | 4.34375 | 4 | #!/usr/bin/python
mylist = [1,2,3,4,5,6,7,8,9]
# Logic
# mylist[-pos:] will print elements from pos (counting from the end) upto end
# Ex: mylist[-2:] will print [8,9]
# mylist[:-pos] will print elements from pos (counting from the end) upto beg
print mylist
while 1:
print "Rotate by:"
pos = int(raw_input())
mylist = mylist[-pos:] + mylist[:-pos]
print mylist
| true |
fb5af5723dbe736eba40c58e396aa4053fa9a831 | MGS-SBHG/PythonTKinter | /Ch05/08_scrollbar.py | 2,264 | 4.40625 | 4 | #!/usr/bin/python3
# scrollbar.py by Barron Stone
# This is an exercise file from Python GUI Development with Tkinter on lynda.com
# imported the Tk intro package
from tkinter import *
# import Ttk module,
from tkinter import ttk
# created my root top level window.
root = Tk()
# create the canvas,
# rather then defining the width and height of the canvas,
# define the scroll region.
# a rectangular area, seen and unseen, over which the canvas will scroll.
# create the x and y scroll bars as usual by using the scroll bar
# constructor method and I configure the command property
# to use the canvas.xview and canvas.yview accordingly.
canvas = Canvas(root, scrollregion = (0, 0, 640, 480), bg = 'white')
# configure the canvases
# xscroll command to use my xscroll bars set command
# yscroll command to execute the yscroll.set method from the y scroll bar.
xscroll = ttk.Scrollbar(root, orient = HORIZONTAL, command = canvas.xview)
yscroll = ttk.Scrollbar(root, orient = VERTICAL, command = canvas.yview)
canvas.config(xscrollcommand = xscroll.set, yscrollcommand = yscroll.set)
# use the grid geometry manager to place the canvas
# place my x scroll bar below it
# place the y scroll bar to the right of it.
canvas.grid(row = 1, column = 0)
xscroll.grid(row = 2, column = 0, sticky = 'ew')
yscroll.grid(row = 1, column = 1, sticky = 'ns')
def canvas_click(event):
# call canvas.canvasx and canvas.canvasy methods
# will translate those x and y coordinates
# to where they actually appear on the canvas.
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
# code which breaks out those x and y values and
# uses the canvas.create_oval method to draw an oval
# on that point of the canvas.
canvas.create_oval((x-5, y-5, x+5, y+5), fill = 'green')
# call the bind method on the canvas widget to bind it
# to whenever the user clicks their mouse button.
# if the user clicks on the canvas,
# it will execute the canvas click method and pass in event information,
# contains the x and y location on the canvas where that click occurred.
canvas.bind('<1>', canvas_click)
root.mainloop()
| true |
214acb18fb4a2d34f4748678a898f355c6f57edc | MGS-SBHG/PythonTKinter | /Ch04/01_frame.py | 2,676 | 4.21875 | 4 | #!/usr/bin/python3
# frame.py by Barron Stone
# This is an exercise file from Python GUI Development with Tkinter on lynda.com
# import the TkInter package
from tkinter import *
# the TkInter module
from tkinter import ttk
# created my root top level Tk window.
root = Tk()
# create a frame,
# use the frame constructor found in the Ttk module, spelled with F,
# 1st paramenter of top level root window to use as the parent for this frame.
frame = ttk.Frame(root)
# use the pack geometry manager within that top level window
# to place the frame inside of it.
frame.pack()
# manually configure the width and height of the frame:
# 100 pixels high by 200 pixel wide frame.
frame.config(height = 100, width = 200)
# the frame border
# six different types of frame relief:
# the FLAT relief No border; default
# RAISED frame appear either elevated
# SUNKEN relief: frame appear depressed,
# SOLID
# RIDGE
# GROOVE border different styles of lines around your frame.
# configure the type of relief for our frame,
frame.config(relief = RIDGE)
# create a button widget using the Ttk button constructor.
# make its parent the frame created.
# configure the text of the button to say "click me"
# use the grid geometry manager here instead of the pack manager.
# configured the top level root window to use the pack manager
# by using it on the frame,
# By using the grid geometry manager on this widget
# I'm adding to the frame, any other widgets I add to the frame later
# will also need to be done so by using the grid geometry manager.
ttk.Button(frame, text = 'Click Me').grid()
# add padding to my frame to create a buffer around the button on the inside of the frame by configuring the padding property.
# Padding accepts a list of two values:
# the number of pixels in the X direction and
# the number of pixels in the Y direction of padding to add around that frame.
# a frame with
# 30 pixels padding on the inside in the X direction
# 15 pixels of padding in the Y direction.
frame.config(padding = (30, 15))
# the label frame.
# create a label frame using the Ttk label frame constructor method
# both the L and F are capitalized in label frame.
# make the top level root window the parent for this frame.
# properties
# height and width
# text property
ttk.LabelFrame(root, height = 100, width = 200, text = 'My Frame').pack()
root.mainloop()
| true |
bf491f54a6385b7c4548cba2cf84d7144339cff8 | sendess/Python_training_class | /class10/Assignment/final/Task_1.py | 739 | 4.34375 | 4 | # Task 1
# Create a class named 'Circle' with an attribute 'radius' and two
# methods that returns area and perimeter of the circle respectively.
# defining class
class Circle:
radius = None
def __init__(self, radius):
self.radius = radius
def calc_area(self):
return ((22 / 7) * self.radius * self.radius)
def calc_circumference(self):
return (2 * (22 / 7) * self.radius)
circle_1 = int(input("Enter the radius of your object circle : "))
# creating object
circle_object_1 = Circle(circle_1)
print("The circumference of circle 1 is : ",circle_object_1.calc_circumference())
print("The area of circle 1 is : ", circle_object_1.calc_area())
| true |
9eb4b24013ef376bb542fcf965321cd5f498ae7f | sendess/Python_training_class | /class5/Assignments/task_3.py | 901 | 4.3125 | 4 | # Task 3
# Replace prime numbers with 'prime' string in a given list of integers using lambda function. (you can use separate function to check for prime)
entered_list=[]
replaced_list=[]
def prime(iter_number, list_given):
count = 1
changing_function = lambda n : list_given.append('Prime') if (n==1) else list_given.append(iter_number)
for i in range(1,iter_number):
if iter_number % i == 0:
count += 1
if count == 2 :
changing_function(1)
else:
changing_function(0)
num_entered = int(input("Enter how many numbers do you want to enter: "))
for i in range(num_entered):
entered_list.append(int(input()))
for j in entered_list:
prime(j, replaced_list)
print("You entered numbers: ")
print(entered_list)
print("Replacing prime numbers in the list with 'Prime' : ")
print(replaced_list)
| true |
d18fb917c16439b2387f9deec86110fb12a34de5 | sendess/Python_training_class | /class10/Assignment/final/Task_2.py | 2,019 | 4.21875 | 4 | # Task 2
# Create a class name 'Vehicle' with attributes 'name', 'speed' and 'manufacturer'
# and a method to get the speed. Further extend this class into two other classes
# named 'Car' and 'Plane' with car having attributes 'horsepower' for 'Car' and
# 'engines' for 'Plane'. Use constructors to initialize the initial values
# defining class
class Vehicle:
name = None
speed = None
manufacturer = None
def __init__(self, name, speed, manufacturer):
self.name = name
self.speed = speed
self.manufacturer = manufacturer
def get_speed(self):
return self.speed
def get_name(self):
return self.name
def get_manufacturer(self):
return self.manufacturer
def display(self):
print(f'Name: {self.name},\n Top speed: {self.speed},\n Manufactured by: {self.manufacturer}')
# derived class
class Car(Vehicle):
horsepower = None
def __init__(self, name, speed, manufacturer, horsepower):
super().__init__(name, speed, manufacturer)
self.horsepower = horsepower
def display(self):
print(f'Name: {self.name},\n Top speed: {self.speed} kmph ,\n Manufactured by: {self.manufacturer},\n Horsepower: {self.horsepower} hp.')
# derived class
class Plane(Vehicle):
engine = None
def __init__(self, name, speed, manufacturer, engine):
super().__init__(name, speed, manufacturer)
self.engine = engine
def display(self):
print(f'Name: {self.name},\n Top speed: {self.speed} kmph,\n Manufactured by: {self.manufacturer},\n Engine: {self.engine}.')
# creatng objects
object_car_1 = Car('Aventador', 352, 'Lamborghini', 730)
object_plane_1 = Plane('Wide-body jet airliner', 914, 'Airbus', 'Rolls-Royce Trent 500')
print('\n\n')
print('Detail of car_1 :')
object_car_1.display()
print('\n\n')
print('Details of plane_1 :')
object_plane_1.display()
| true |
830c5065c45ae2ff3ff547a87caec7775e12cfb8 | radmarion/theselftaughtdev | /Python/Chapter 4/exceptionHandlingProblem.py | 355 | 4.15625 | 4 | #Error / Exception Handling
a = input('type a number ')
b = input('type another number ')
a = int(a)
b = int(b)
print (a/b,'\n') # What is \n used for?
print(int(a/b)) # What will this line of code print out?
#--- What will happen if a or b recieves an input of a string(Word, sentence e.t.c)
# try entering 0 as the second input of the program
| true |
33ef66976a96dd1150539473cbcc78dab815094b | vamsi-bulusu/Mission-RND-PYTHON-COURSE | /unit7_assignment_02.py | 2,382 | 4.25 | 4 | __author__ = 'Kalyan'
problem = """
Pig latin is an amusing game. The goal is to conceal the meaning of a sentence by a simple encryption.
Rules for converting a word to pig latin are as follows:
1. If word starts with a consonant, move all continuous consonants at the beginning to the end
and add "ay" at the end. e.g happy becomes appyhay, trash becomes ashtray, dog becomes ogday etc.
2. If word starts with a vowel, you just add an ay. e.g. egg become eggay, eight becomes eightay etc.
You job is to write a program that takes a sentence from command line and convert that to pig latin and
print it back to console in a loop (till you hit Ctrl+C).
e.g "There is, however, no need for fear." should get converted to "Erethay isay, oweverhay, onay eednay orfay earfay."
Note that punctuation and capitalization has to be preserved
You must write helper sub routines to make your code easy to read and write.
Constraints: only punctuation allowed is , and . and they will come immediately after a word and will be followed
by a space if there is a next word. Acronyms are not allowed in sentences. Some words may be capitalized
(first letter is capital like "There" in the above example) and you have to preserve its capitalization in the
final word too (Erethay)
"""
import re
import sys
def vowel(wrd):
xd = ['a', 'e', 'i', 'o', 'u']
wrd = list(wrd)
for i in wrd:
if i in xd:
return wrd.index(i)
else:
return 0
def wrd_cons(word):
flag = 0
c = word[0:1]
if ord(c) >= 65 and ord(c) < 91:
flag = 1
word = word.lower()
index = vowel(word)
word = word[index:len(word)] + word[0:index] + 'ay'
if word.find(',') != -1:
y = word.find(',')
word = word[:y] + word[y + 1:len(word)] + ','
if word.find('.') != -1:
z = word.find('.')
word = word[:z] + word[z + 1:len(word)] + '.'
if flag == 1:
word = word.capitalize()
return word
def piggy_game(sentance):
res = []
sentance = sentance.split()
print(sentance)
for i in sentance:
x = wrd_cons(i)
res.append(x)
print(res)
res = " ".join(res)
return res
if __name__ == '__main__':
xd = sys.argv[1]
result = piggy_game(xd)
print(result)
#sys.exit(main()) | true |
451991d52e07588c441254d1ee6441f209caa683 | CesarBlvD/PythonProyectos | /Python/Tuplas.py | 546 | 4.25 | 4 | #Sintaxis de las tuplas
"""NombreTupla=(elem1, elem2, elem3....) parentesis tupla corchetes lista
"""
#Ejemplo=("Hola", 10, 11)
tupla=("Hola", 10, 1, 1234)
nombre, dia, mes, ano = tupla #asignar las variables a la tupla
print (nombre)
print (ano)
lista=list(tupla) #Convertir una tupla en una lista
print(tupla[:])
print(tupla.count(10)) #cuantas veces hay un dato en la tupla
print(len(tupla)) #La longitud de la tupla
#Convertir la lista en una tupla
"""lista1=[10, 21, "hola"]
tupla2=tuple(lista1)
print(tupla2)
""" | false |
136ad717d85163a0aeb9157dfb44e520791464b3 | CesarBlvD/PythonProyectos | /Python/Excepciones.py | 1,321 | 4.40625 | 4 | #Que son las excepciones?
"""
Las excepciones son errores que ocurren durante la ejecucion del programa. La sintaxis del codigo es correcta pero durante la ejecucion ha ocurrido algo inesperado
"""
"""
Captura o control de excepcion
"""
def suma(num1, num2):
return num1+num2
def resta(num1, num2):
return num1-num2
def multiplica(num1, num2):
return num1*num2
def divide(num1, num2):
try: #Similar a un if else con un error en el except
return num1/num2
except ZeroDivisionError:
print("No se puede dividir entre 0")
return "operacion erronea"
while True:
try:
op1=(int(input("Introduce el primer numero: ")))
op2=(int(input("Introduce el segundo numero: ")))
break
except ValueError:
print("Los valores introducidos no son correctos")
operacion= input("Introduce la operacion a realizar (suma, resta, multiplica, divide): ")
if operacion=="suma":
print(suma(op1,op2))
elif operacion=="resta":
print(resta(op1, op2))
elif operacion=="multiplica":
print(multiplica(op1,op2))
elif operacion=="divide":
print(divide(op1, op2))
else:
print("Operacion no contemplada")
print("Operacion ejecutada. Continuacion de ejecucion del programa")
| false |
4a36314070857dd4f843f430e7fb480eee170f0c | troyallen618/PythonGame | /FinalProject.py | 2,116 | 4.1875 | 4 | print('Welcome to my game.')
print('Overview: \nYou have been captured and put in a room by kidnappers. \nYou must escape the room without alerting your abductors.\n\n')
game_running=True
round1= True
round2= True
round3= True
def End():
exit()
def Third():
while round3:
print('1' ' - Run out together')
print('2' ' - Climb out window')
print('3' ' - Leave room and try to find other captives')
t = int(input('Select 1-3 to Proceed '))
if t == 1:
print('// You escape. \nCONGRATULATIONS! \nYOU ARE FREE!')
End()
elif t == 2:
print('// Window is locked. \nMake another choice.')
elif t == 3:
print('// The kidnappers are in the next room. \nGAME OVER')
End()
else:
print('// PLEASE MAKE A VALID CHOICE')
def Second():
while round2:
print('1' ' - Wake them up')
print('2' ' - Walk back outside')
z = int(input('Select 1-2 to Proceed '))
if z == 1:
print('// They are now awake and stand up')
Third()
elif z == 2:
print('// Kidnappers see you. \nGAME OVER')
End()
else:
print('// PLEASE MAKE A VALID CHOICE')
def First():
while round1:
print('1' ' - Run to bathroom')
print('2' ' - Run through front door')
print('3' ' - Go to next room')
y = int(input('Select 1-3 to Proceed '))
if y == 1:
print('// Theres a kidnapper there. \nGAME OVER')
End()
elif y == 2:
print('// They saw you. \nGAME OVER')
End()
elif y == 3:
print('// Theres another captive in the room sleeping')
Second()
else:
print('// PLEASE MAKE A VALID CHOICE')
def thestart():
while game_running:
input('Press Enter to Begin ')
print('1' ' - Escape through window')
print('2' ' - Escape through door')
print('3' ' - Try to communicate with someone outside for help')
x = int(input('Make your move ''(Select 1-3)'' '))
if x == 1:
print('// You alerted the kidnapper. \nGAME OVER')
End()
elif x == 2:
print('// You are now in the hallway')
First()
elif x == 3:
print('// Your phone made a sound when it turned on. \nGAME OVER')
End()
else:
print('// PLEASE MAKE A VALID CHOICE')
thestart()
| true |
a0a2ed68d553f9bdc9a57b850358049c03671247 | ataabi/listadeexercicios | /estrutura_sequencial/EstruturaSequencial3.py | 563 | 4.34375 | 4 | # Faça um Programa que converta metros para centímetros.
print('Transformando Metros em Centimetros')
m = float(input('Quantos Metros : '))
c = m*100
print('%.0f Metros equivale a %.0f Centimetros '% (m, c))
print('Calcuro da Area de um circulo com base no raio')
r = float(input('Raio do circulo : '))
p = 3.14
a = p*r**2
print('A aréa do circulo é : %.3f ' %a)
print('Calculo da area de um quadrado e o seu dobro')
q = float(input('Are do quadrado : '))
respq = q**2
respq2 = respq*2
print('A Area do quadrado é %.0f e o dobro é %.0f' %(respq, respq2))
| false |
7daa4cb69f5d76b01905593dd3831f4c1bfca741 | alejanbreu/TC1014_Alejandro | /WSQ03.py | 490 | 4.25 | 4 |
print ("Fun with numbers!")
num1 = int(input("First Number"))
num2 = int(input("Second Number"))
sum = num1+num2
diference = num1-num2
product = num1*num2
division = num1//num2
remainder = num1%num2
print ("The sum of the two numbers:", sum)
print ("The differene of the two numbers:", diference)
print ("The product of the two numbers:", product)
print ("The integer based division of the two numbers", division)
print ("The remainder of integer division of the two numbers", remainder)
| true |
a309baf3bbd650123e59277f88e83f1104664352 | adwaithkj/module4-solution | /test.py | 1,285 | 4.125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'climbingLeaderboard' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
# 1. INTEGER_ARRAY ranked
# 2. INTEGER_ARRAY player
#
def playersort(player):
for i in range(len(player)):
for j in range(i+1, len(player)):
if player[i] < player[j]:
temp = player[i]
player[j] = player[i]
player[i] = temp
return player
def ranking(q, ranked):
count = 0
for i in range(len(ranked)):
# print("count:" + str(count))
if (ranked[i] != ranked[i-1]):
count += 1
if q >= ranked[i]:
return count
return count+1
def climbingLeaderboard(ranked, player):
arr = []
for i in range(len(player)):
arr.append(ranking(player[i], ranked))
return arr
# Write your code here
if __name__ == '__main__':
ranked_count = int(input().strip())
ranked = list(map(int, input().rstrip().split()))
player_count = int(input().strip())
player = list(map(int, input().rstrip().split()))
result = climbingLeaderboard(ranked, player)
print('\n'.join(map(str, result)))
| true |
8bbed7888bf02bbf415d2c7fd308e649b1bff873 | Archanaaarya/if-else | /calculate_electricity_bills.py | 889 | 4.1875 | 4 | # Question 5. Write a program to calculate the electricity bill (accept number of unit from user) according to the following criteria :
# Unit Price
# First 100 units no charge
# Next 100 units Rs 5 per unit
# After 200 units Rs 10 per unit
# (For example if input unit is 350 than total bill amount is Rs2000)
units = int(input("enter the units of electricity used"))
if units <= 100:
print("no charge because units used is too law")
elif units <=200:
print("you have to pay Rs",units*5)
elif units >= 200:
print("you have to pay Rs",units*10)
else:
print("Ab office me aana saara bill ache se pay karva lenge bahoot pesa aa ra he office me de ke ja chup chap")
| false |
e180573cdb6c328881a9f8f6a42c2219dbb56855 | famavott/codewars-katas | /src/simple_consecutive_pairs.py | 351 | 4.21875 | 4 | """Return count of pairs that have consecutive numbers in array."""
def pairs(arr):
"""Return count of pairs with consecutive nums."""
count = 0
pairs = [arr[i:i + 2] for i in range(0, len(arr), 2)]
for pair in pairs:
if len(pair) == 2:
if abs(pair[0] - pair[1]) == 1:
count += 1
return count
| true |
3ca45bfb3f2b186b08ea34235f60e6b09ce31d52 | egarcia410/digitalCraft | /Week1/5-stringExercises/stringExercises.py | 2,145 | 4.5625 | 5 | # 1 Uppercase a String
# Given a string, print the string uppercased.
string = 'lorem ipsum dolor sit amet, consectetur adipisicing elit.'
# print(string.upper())
# #############################################################################
# 2 Capitalize a String
# Given a string, print the string capitalized.
# print(string.capitalize())
# #############################################################################
# 3 Reverse a String
# Given a string, print the string reversed.
# print(" ".join(string.split(" ")[::-1]))
# #############################################################################
# 4 Leetspeak
# Given a paragraph of text as a string, print the paragraph in leetspeak.
# leetSpeak = {
# 'A': 4,
# 'E': 3,
# 'G': 6,
# 'I': 1,
# 'O': 0,
# 'S': 5,
# 'T': 7
# }
# for letter in leetSpeak:
# string = string.upper().replace(letter, str(leetSpeak[letter]))
#
# print(string.lower())
# #############################################################################
# 5 Long-long Vowels
# Given a word as a string, print the result of extending any long vowels to the length of 5
# string = 'Good'
# count = {
# 'a': 0,
# 'e': 0,
# 'i': 0,
# 'o': 0,
# 'u': 0
# }
#
# for letter in string.lower():
# if letter in count:
# count[letter] += 1
#
# print(count)
# for letter in count:
# if count[letter] >= 2:
# string = string.replace(letter, letter*4, 1)
#
# print(string)
# #############################################################################
# 6 Caesar Cipher
# Given a string, print the Caesar Cipher (or ROT13) of that string.
# What is Caesar Cipher? http://practicalcryptography.com/ciphers/caesar-cipher/
# Use your solution to decipher the following text: "lbh zhfg hayrnea jung lbh unir yrnearq"
string = "lbh zhfg hayrnea jung lbh unir yrnearq"
strList = []
# 'z' == 122
for letter in string:
if (ord(letter)) == 32:
strList.append(chr(ord(letter)))
continue
if (ord(letter)+1) > 122:
strList.append('a')
else:
strList.append(chr(ord(letter)+1))
print("".join(strList))
| false |
68f0592b3d95218bd2e09238615a2231443c8132 | egarcia410/digitalCraft | /Week2/3-phoneBookApp/index.py | 2,637 | 4.15625 | 4 | """Phone Book App"""
import json
def phoneBook():
"""Phone Book App - Using JSON as a simple database for CRUD operation"""
with open('temp.json', 'w') as f:
json.dump({}, f)
while True:
print('\n')
print('Electronic Phone Book')
print('=====================')
print('1. Look up an entry')
print('2. Set an entry')
print('3. Delete an entry')
print('4. List all entries')
print('5. Save entries')
print('6. Restore saved entries')
print('7. Quit')
num = input('What do you want to do (1-5)? ')
fname = 'temp.json'
with open(fname, 'r') as f:
data = json.load(f)
if num == '1':
searchEntry(data)
elif num == '2':
createEntry(data, fname)
elif num == '3':
deleteEntry(data, fname)
elif num == '4':
listEntries(data)
elif num == '5':
saveEntries(data)
elif num == '6':
restoreEntries(fname)
elif num == '7':
print('Bye')
break
def searchEntry(data):
"""Search phone book for person by name"""
name = input('Name: ')
if name in data:
print('Found entry for ' + name + ": " + data[name])
else:
print('Entry does not exist')
def createEntry(data, fname):
"""Create entry in phone book"""
name = input('Name: ')
phone = input('Phone Number: ')
data[name] = phone
with open(fname, 'w') as f:
json.dump(data, f)
print('Entry stored for ' + name)
def deleteEntry(data, fname):
"""Delete entry from phone book"""
name = input('Name: ')
if name in data:
del data[name]
with open(fname, 'w') as f:
json.dump(data, f)
print(name + " was deleted!")
else:
print('Name does not exist')
def listEntries(data):
"""Displays all entries in phone book"""
if data:
for name in data:
print('\n')
print('Name: ', name)
print('Phone Number: ', data[name])
else:
print('No entries to display')
def saveEntries(data):
"""Save entries into data.json file"""
with open('data.json', 'w') as f:
json.dump(data, f)
print('Entries saved to data.json')
def restoreEntries(fname):
"""Restore saved files from data.json"""
with open('data.json', 'r') as f:
with open(fname, 'w') as f1:
for line in f:
f1.write(line)
print('Restored saved entries')
phoneBook()
| true |
16c9bd64379aaf6de0995dc150932e6b80442e33 | linuslin/leetcode | /leetcode94.py | 1,020 | 4.1875 | 4 | #!/bin/python
# coding=UTF-8
import unittest
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
result=self.inorderTraversal(root.left)+ [root.val] + self.inorderTraversal(root.right)
return result
class TestMethods(unittest.TestCase):
def test_upper(self):
s=Solution()
n3=TreeNode(3)
n2=TreeNode(2)
n1=TreeNode(1)
self.assertEqual(s.inorderTraversal(n3),[3])
self.assertEqual(s.inorderTraversal(None),[])
n3.left=n2
self.assertEqual(s.inorderTraversal(n3),[2,3])
n2.right=n1
self.assertEqual(s.inorderTraversal(n3),[2,1,3])
if __name__ == '__main__':
# creates an instance of the class
unittest.main()
| true |
74852875debfa8b878ad9b2bd6d7fc5f9f46abc2 | jerryfane/dictionaries-implementation | /NHashTable.py | 1,438 | 4.1875 | 4 | from HashTable import HashTable
class NHashTable(HashTable):
def append(self, keyvalue):
# address: where we want to store the information
# through the _hash function
key, value = keyvalue
address = self._hash(key)
# insted of a python list, use a Nested Default HT for collisions
if not self.data[address]:
if len(self.data) != 1:
self.data[address] = DefaultNHashTable(int(len(self.data) / 10)+1)
self.data[address].append((key, value))
else:
self.data[address] = [(key, value)]
else:
self.data[address].append((key, value))
def get(self, key):
# find the address of the given key, through the _hash function
address = self._hash(key)
#return the key in the address HT
return self.data[address].get(key)
class DefaultNHashTable(NHashTable):
def _hash(self, key):
"""
Return the hash value of the object (if it has one). Hash values are integers.
They are used to quickly compare dictionary keys during a dictionary lookup.
Numeric values that compare equal have the same hash value
(even if they are of different types, as is the case for 1 and 1.0).
https://docs.python.org/2/library/functions.html#hash
"""
return hash(key) % len(self.data) | true |
15053aa07aaaca51752e77f6e0f0e98eb203db76 | martinestanga1/bucles_python | /3.bucles_python/ejercicios_profunidzacion/profundizacion_2.py | 2,828 | 4.21875 | 4 | # Bucles [Python]
# Ejercicios de profundización
# Autor: Inove Coding School
# Version: 2.0
# NOTA:
# Estos ejercicios son de mayor dificultad que los de clase y práctica.
# Están pensados para aquellos con conocimientos previo o que dispongan
# de mucho más tiempo para abordar estos temas por su cuenta.
# Requiere mayor tiempo de dedicación e investigación autodidacta.
# IMPORTANTE: NO borrar los comentarios en VERDE o NARANJA
'''
Enunciado:
Realice una calculadora:
Dentro de un bucle se debe ingresar por línea de comando dos números
Luego se ingresará como tercera entrada al programa el símbolo de la operación
que se desea ejecutar:
- Suma (+)
- Resta (-)
- Multiplicación (*)
- División (/)
- Exponente/Potencia (**)
Se debe efectuar el cálculo correcto según la operación ingresada por consola
Imprimir en pantalla la operación realizada y el resultado
El programa se debe repetir dentro del bucle hasta que como operador
se ingrese la palabra "FIN", en ese momento debe terminar el programa
Se debe debe imprimir un cartel de error si el operador ingresado no es
alguno de lo soportados o no es la palabra "FIN".
'''
print("Mi Calculadora (^_^)")
# Empezar aquí la resolución del ejercicio
numero_1 = int(input("Número 1:\n"))
numero_2 = int(input("Número 2:\n"))
operador = str(input("Operador:\n"))
operadores = ("+", "-", "*", "/", "**", "FIN")
# Prueba con condicional
'''if operador == operadores[0]:
print("La suma es:", numero_1 + numero_2)
elif operador == operadores[1]:
print("La resta es:", numero_1 - numero_2)
elif operador == operadores[2]:
print("La multiplicación es:", numero_1 * numero_2)
elif operador == operadores[3]:
print("La división es:", numero_1 / numero_2)
elif operador == operadores[4]:
print("El exponente es:", numero_1 ** numero_2)
elif operador == operadores[5]:
print("Fin de la operación.")
else:
print("ERROR! Ingrese un dato válido.")'''
# Bucle
while operador == operadores[0]:
print("La suma es:", numero_1 + numero_2)
break
while operador == operadores[1]:
print("La resta es:", numero_1 - numero_2)
break
while operador == operadores[2]:
print("La multiplicación es:", numero_1 * numero_2)
break
while operador == operadores[3]:
print("La división es:", numero_1 / numero_2)
break
while operador == operadores[4]:
print("El exponente es:", numero_1 ** numero_2)
break
fin = str(input("Ingresar la finalización de la operación:\n"))
while fin == operadores[5]:
print("Fin de la operación.")
break
if operador != operadores[0:5]:
print("ERROR! Ingrese un operador válido.")
| false |
a7d21d70e137caa9aef1241ea1698e142e98ec3b | SuhelMehta9/Project-Euler | /Problem 7.py | 997 | 4.1875 | 4 | # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10001st prime number?
usr_input = int(input('Enter the number: '))
primeNumber = [2,3,5,7]
number = 9
value = len(primeNumber)
# Store prime numbers
while value!=usr_input:
if value==usr_input: # If length of list is equal to user input means the nth prime number that user wants is the last element.
break
else:
for dividor in primeNumber: # dividor is the element in list of prime number
if number%dividor==0:
break
elif dividor == primeNumber[-1]: # To check if we have reached at the end of list where prime numbers are stored then
# it would mean that the number is not divisible by any number hence it is a prime number.
primeNumber.append(number)
number = number+2
#print(number)
value = len(primeNumber)
print(primeNumber) # Take the last element
| true |
d16b6445e125a55ef0a6da4fe4fcef05d29f0d0e | sawisharma905/Python_programming | /hello.py | 1,240 | 4.25 | 4 | print("hello world")
#this is comment
'''this is multiline
comment'''
'''a=7
print(a, end=" done")
b=10
print(type(a))
print(type(b))
b="hello"
print(type(b))
#string manipulation-different methods
#print(b[1:3])
#print(b[:])
print(b[3:5])
print(b[2:-1])
#print(b[2:-4]) index shoul not trespass the starting value
a=input("a=")
b=input("b=")
print(type(a), type(b))
a=input("a=")
b=input("b=")
a=int(a)
b=int(b)
print(type(a), type(b))
'''
#creating lists-we can put a ny type of values into it
list1=[1,2,"hello" ,2.5]
print(type(list1))
print(list1[0])
print(list1[1:5])
print(list1[:3])
print(list1[:])
#to change the value ina list
list1[2]="sawa"
print(list1[:])
#length of the list
print(len(list1))
list1.append("bhoot")
print(list1[:])
print(len(list1))
list1.insert(0,"lalala")
print(list1[:])
print(len(list1))
list1.remove("bhoot")
print(list1[:])
print(len(list1))
list1.remove(1)
print(list1[:])
print(len(list1))
list1.clear()
print(list1[:])
print(len(list1))
del(list1)
#creating tuples- immutable
t1=(1,2,34,5)
print(len(t1))
#t1.remove(t1[1])
print(t1)
#creatin' dictionary
d1={ 'two':2 ,'one':[1,2,3], 'three':3}
print(d1)
print(d1['one'])
d1['four']=[4,5,6]
print(d1)
d1.pop('two')
d1.pop('three')
print(d1)
| false |
e2e4fa0e25899a43a8d0b421fbb5cc53b65da19a | darkerego/solutions | /mumbling.py | 752 | 4.125 | 4 | """
This time no story, no theory. The examples below show you how to write function accum:
Examples:
accum("abcd") -> "A-Bb-Ccc-Dddd"
accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") -> "C-Ww-Aaa-Tttt"
The parameter of accum is a string which includes only letters from a..z and A..Z.
"""
def accum(s):
""" Input a string like "abc"
and return a string like "A-Bb-Ccc"
"""
count2 = 0
count = 0
k = len(s)
final_str = ""
for i in range(len(s)):
final_str += (s[count].upper())
for z in range(count2):
final_str +=(s[count].lower())
count2 += 1
count += 1
if k > 1:
final_str += ("-")
k -= 1
return str(final_str)
| false |
fb3027e932f3d46c8c6da7fbf550037174b18f24 | darkerego/solutions | /triple_double.py | 949 | 4.1875 | 4 | """
triple_double(num1, num2)
which takes numbers num1 and num2 and returns 1 if there is a straight triple of a number at any place in num1 and also a straight double of the same number in num2.
If this isn't the case, return 0
Examples
triple_double(451999277, 41177722899) == 1
# num1 has straight triple 999s and num2 has straight double 99s
triple_double(1222345, 12345) == 0
# num1 has straight triple 2s but num2 has only a single 2
triple_double(12345, 12345) == 0
triple_double(666789, 12345667) == 1
"""
def triple_double(num1, num2):
from collections import Counter
check_1 = Counter(str(num1))
check_2 = Counter(str(num2))
num1 = str(num1)
num2 = str(num2)
for i in num1:
print('check 1', i)
if check_1[i] >= 3:
for x in num2:
print(x, i)
if int(x) == int(i):
if check_2[x] >= 2:
return 1
return 0
| true |
8a1980e574ac338bca53313b7c977599168215e0 | samkorn/python-ev3dev | /python-tutorials/functions.py | 359 | 4.25 | 4 | #!/usr/bin/env python3
def my_function(x, y):
return x + y
def my_print_function(name):
print("Hello, my name is " + name)
# creates a new variable with the output of the function my_function
# then prints the result
x_plus_y = my_function(x, y)
print(x_plus_y)
# calls the function my_print_function for the name "Sam"
my_print_function("Sam")
| true |
20b3165f580df46c5621df0957dd2180f93d0646 | SethM-SDE/mycode | /advlist/complex01.py | 834 | 4.34375 | 4 | #!/usr/bin/env python3
# create a list called list1
list1 = ["cisco_nxos", "arista_eos", "cisco_iso"]
# display list1
print(list1)
# display list1[1] which should only display arista_eos
print(list1[1])
# create a new list containing a single item
list2 = ["juniper"]
# extend list1 by list2 (combine both lists together into a single list)
list1.extend(list2)
print(list1)
# create lsit3
list3 = ["10.1.0.1", "10.2.0.1", "10.3.0.1"]
# use the append operation to append list1 and list3
list1.append(list3)
print(list1)
# display the list of IP addresses
print(list1[4])
# display the first item of the list(0th item) - first IP address
print(list1[4][0])
icecream = ["flavors", "salty"]
icecream.append(99)
user_name = input("What is your name?")
print(f"{icecream[2]} {icecream[0]}, and {user_name} chooses to be {icecream[1]}")
| true |
8393abbdfb9a921092d2ad67087bb7ff12038dc0 | robpotter-jcu/cp1404practical | /prac_05/hex_colours.py | 531 | 4.125 | 4 | """
CP1404 Practical
Hexadecimal colour lookup
"""
COLOUR_CODES = {"blue1": "#0000ff", "brown1": "#ff4040", "DarkOrange1": "#ff7f00", "DarkOrchid1": "#bf3eff",
"DeepPink1": "#ff1493", "gold1": "#ffd700", "gray1": "#030303", "green1": "#00ff00",
"maroon1": "#ff34b3", "yellow1": "#ffff00"}
colour_name = input("Enter a colour name: ")
while colour_name != "":
print("The code for \"{}\" is {}".format(colour_name, COLOUR_CODES.get(colour_name)))
colour_name = input("Enter a colour name: ")
| false |
720c0145836104e92a7d6967fdbebb813cd73f71 | songjiyang/Mypython | /PythonIntroduction/chapter3.py | 1,204 | 4.28125 | 4 | def before():
def invite(list):
#3-9
print('i invited '+str(len(list))+' people')
for people in list:
print(people + ' Welcome to my home to have dinner')
#3-4
guests = ['My Mom','My Dad','My Grandpa','My Brother']
invite(guests)
#3-5
print(guests[2])
guests[2]='My Aunt'
invite(guests)
#3-6
print('big dinnerTable')
guests.insert(0,'Bob')
guests.insert(3,'Jim')
guests.append('Lily')
invite(guests)
#3-7
print('sorry my new dinnerTable dont arrial in time,now only two people i can invite to')
while len(guests)>2:
pop_guest = guests.pop()
print('sorry '+pop_guest+" i can't invite you")
invite(guests)
print(guests)
del guests[0]
del guests[0]
invite(guests)
print(guests)
def after():
#3-8
place = ['scotland','roman','paris','afghan','tokyo']
print(place)
print(sorted(place))
print(place)
print(sorted(place,reverse=True))
print(place)
place.reverse()
print(place)
place.reverse()
print(place)
place.sort()
print(place)
place.sort(reverse=True)
print(place)
#
# before()
motor = []
print(motor[-1]) | true |
d0c7b7aa1237c0aca38c7f68cf399954e40106fd | JorgeLTM-cob/LearningPython | /basics/conditions.py | 584 | 4.125 | 4 | x = 2
print (x == 2)
print (x == 3)
print (x < 3)
name = "John"
age = 23
if name == "John" and age == 23:
print ("Your name is John, and you are also 23 years old.")
if name == "John" or name == "Rick":
print ("Your name is either John or Rick.")
if name in ["John", "Rick"]:
print ("Your name is either John or Rick.")
if x == 2:
print ("x equals two!")
else:
print ("x does not equal to two")
#The following return false:
#Empty String ("")
#Empty list ([])
#The number zero
#The false boolean variable
y = [1,2,3]
z = [1,2,3]
print (z == y)
print (y is z)
| true |
0aeaa9db4aca040e8a9dfad3c76837aa569596ca | JorgeLTM-cob/LearningPython | /basics/strings.py | 353 | 4.34375 | 4 | name = "John"
print("Hello, %s" % name)
name2 = "John"
age = 23
print("%s is %d years old." % (name,age))
#Any object which is not a string can be formatted using the %s operator as well
mylist = [1,2,3]
print("A list: %s" % mylist)
# %s string
# %d integer
# %f floating point numbers
# %.<number of digits>f
# %x/%X Integers in hex representation
| true |
714135aa3b8ea8db5570dbfa5d39aee37ecc307f | buyi823/learn_python | /python_exmple/two_ele_switch2.py | 349 | 4.15625 | 4 | #!/usr/bin/python3
#将列表中的指定位置的两个元素对调
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))
| false |
5d2a6b222a375f68b08c1b8e7edd74bc576a3736 | buyi823/learn_python | /python_exmple/two_ele_switch.py | 282 | 4.1875 | 4 | #!/usr/bin/python3
#将列表中的指定位置的两个元素对调
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 |
3bcbfa2dbb4da7e7de8a8eba6e3f920dbf4b481c | buyi823/learn_python | /Python Crash Course/dictionary_job_practice7.py | 801 | 4.25 | 4 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
# By Blaine 2021-09-02-22:50:50
# dictionary job practice 6
cities = {
'New York': {
'country': 'USA',
'population': 15000000,
'fact': '如果你爱一个人,送他去纽约;如果你恨一个人,送他去纽约。',
},
'Paris': {
'country': 'France',
'population': 10000000,
'fact': 'City of romance',
},
'Tokyo': {
'country': 'Janpan',
'population': 20000000,
'fact': 'Don\'t know much',
}
}
for city_name, info in cities.items():
city_country = f"{info['country']}"
population = f"{info['population']}"
facts = f"{info['fact']}"
print(f"This is {city_name}. There are about {population} people. It's in {city_country}. It's a {facts}") | false |
32301cc01e6107c2b010fa1d375640fc50d96cec | buyi823/learn_python | /python_exmple/dictionary_sort.py | 551 | 4.125 | 4 | #!/usr/bin/python3
# 按键(key)或值(value)对字典进行排序
def dictionary():
#声明字典
key_value = {}
# 初始化
key_value[2] = 56
key_value[1] = 2
key_value[5] = 12
key_value[4] = 24
key_value[6] = 18
key_value[3] = 323
print("按键(key)排序:")
# sorted(key_value)返回一个迭代器
# 字典按键排序
for i in sorted(key_value):
print((i, key_value[i]), end=" ")
def main():
# 调用主函数
dictionary()
if __name__=="__main__":
main() | false |
1d7a6d523975ef4245a1ea0a348f52b262d67f7e | buyi823/learn_python | /Python_100/python_79_string_order.py | 825 | 4.28125 | 4 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
# By Blaine 2021-08-04 16:43
# string order
if __name__ == '__main__':
str1 = input('input string:\n')
str2 = input('input string:\n')
str3 = input('input string:\n')
print(str1, str2, str3)
if str1 > str2:
str1, str2 = str2, str1
if str1 > str3:
str1, str3 = str3, str1
if str2 > str3:
str2, str3 = str3, str2
print('after being sorted.')
print(str1, str2, str3)
'''
在python中,默认是按照ascii的大小比较的; 字符串按位比较,
两个字符串第一位字符的ascii码谁大,字符串就大,不再比较后面的;
第一个字符相同就比第二个字符串,以此类推。
注意:空格的ascii码是32,空(null)的ascii码是0,大写字母和小写字母的ascii不同
''' | false |
be65108755a1d6cbfe8d1086ea73505de42f0ba0 | VladimirKorzun/DataRoot_ML | /linear_regression.py | 2,570 | 4.15625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def linear_regression():
# Step # 1 - Extract data
points = np.genfromtxt('data.csv', delimiter=',')
# Step # 2 - Define hyperparameters
# Learning rate
learning_rate = 0.00001
# Coefficients y = a * x + b
init_a = 10
init_b = 10
# number of iterations
num_iterations = 10000
# Step 3 - model training
print(
'Start learning at a = {0}, b = {1}, error = {2}'.format(
init_a,
init_b,
compute_error(init_a, init_b, points)
)
)
a, b = gradient_descent(init_a, init_b, points, learning_rate, num_iterations)
print(
'End learning at a = {0}, b = {1}, error = {2}'.format(
a,
b,
compute_error(a, b, points)
)
)
return a, b
def compute_error(a, b, points):
'''
Computes Error = 1/N * sum((y - (ax + b))^2)
'''
error = 0
N = len(points)
for i in range(N):
x = points[i, 0]
y = points[i, 1]
error += (y - (a * x + b)) ** 2
return error / N
def gradient_descent(starting_a, starting_b, points, learning_rate, num_iterations):
'''
Performs gradient step num_iterations times
in order to find optimal a, b values
'''
a = starting_a
b = starting_b
for i in range(num_iterations):
a, b = gradient_step(a, b, points, learning_rate)
return a, b
def gradient_step(current_a, current_b, points, learning_rate):
'''
Updates a and b in antigradient direction
with given learning_rate
'''
a = current_a
b = current_b
N = len(points)
a_gradient = -(2 / N) * np.array(points[:, 0] * (points[:, 1] - (a * points[:, 0] + b))).sum()
b_gradient = -(2 / N) * np.array(points[:, 1] - (a * points[:, 0] + b)).sum()
a = current_a - learning_rate * a_gradient
b = current_b - learning_rate * b_gradient
return a, b
a, b = linear_regression()
# Plot Cost funstion
def plot_decorator(f):
points = np.genfromtxt('data.csv', delimiter=',')
return lambda a, b: f(a, b, points)
cost = plot_decorator(compute_error)
A = np.linspace(-10, 12, 40)
B = np.linspace(-10, 12, 40)
A, B = np.meshgrid(A, B)
E = cost(A, B)
# Plot data and learned function
# In[38]:
points = np.genfromtxt('data.csv', delimiter=',')
X = points[:, 0]
Y = points[:, 1]
plt.xlim(0, 80)
plt.ylim(0, 150)
plt.scatter(X, Y)
params = np.linspace(0, 150, 10)
plt.plot(params, a * params + b)
plt.show()
| false |
9b6814eed93efad1149459917efbbeefe3412508 | Burn09/Python | /Stack/Stack_initialization.py | 1,505 | 4.34375 | 4 | class Element(object):
"""Initializing an Element for a Linked List"""
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
"""Initializing a Linked List object"""
def __init__(self, head=None):
self.head = head
def append(self, new_element):
"""Appending new elements to the Linked List"""
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
def insert_first(self, new_element):
"""Insert a new element as the head of the list"""
new_element.next = self.head
self.head = new_element
def delete_first(self):
"""Delete the element at the head of the list
and return it"""
if self.head:
deleted_element = self.head
temp = deleted_element.next
self.head = temp
return deleted_element
else:
return None
class Stack(object):
"""Initializing a stack object using a Linked List"""
def __init__(self, top=None):
self.ll = LinkedList(top)
def push(self, new_element):
"""Pushing an element to the top of the Stack"""
self.ll.insert_first(new_element)
def pop(self):
"""Deleting an element at the top of the Stack
and returning it"""
return self.ll.delete_first()
| true |
92bae44e84cba12d89cba78a824dc6b548eb9ccf | xiaomijimu/sandbox | /myPython/test.py | 241 | 4.15625 | 4 | import random,sys
def collatz(n):
if (n%2 ==0):
return n//2
else:
return 3*n+1
print("Enter number:")
try:
n = int(input())
while (n!=1):
n = collatz(n)
print (n)
except ValueError:
print("please enter number, not string!")
| true |
bd9ea7b3a82c3a54a63bfa039463a81a878c3eef | wangleiliugang/data | /aid1805/pbase/89_inheritance.py | 785 | 4.15625 | 4 | # 此示例示意继承和派生
class Human(object):
'''此类用于描述人类的共性行为'''
def say(self, that):
print("说:", that)
def walk(self, distance):
print("走了", distance, "公里")
class Student(Human):
# def say(self, that):
# print("说:", that)
# def walk(self, distance):
# print("走了", distance, "公里")
def study(self, subject):
print("正在学习:", subject)
class Teacher(Student):
def teach(self, subject):
print("正在教:", subject)
h1 = Human()
h1.say("今天真冷!")
h1.walk(5)
s1 = Student()
s1.say("学习有点累")
s1.walk(3)
s1.study('python')
t1 = Teacher()
t1.say("明天周五了")
t1.walk(6)
t1.teach('面向对象oop')
t1.study('python3')
| false |
50a78a5a60b8aa92acc33d9b5a24570f5fed5933 | wangleiliugang/data | /aid1805/pbase/38_closure.py | 693 | 4.15625 | 4 | # 此示例示意闭包的创建和调用过程
def make_power(y):
def fx(arg):
return arg ** y
return fx
pow2 = make_power(2)
print('3的平方是:', pow2(3))
pow3 = make_power(3)
print('3的立方是:', pow3(3))
# 求1 ** 2 + 2 ** 2 + 3 ** 2 + ... + 9 ** 2 的和
print(sum(map(lambda x: x ** 2, range(1, 10))))
print(sum(map(make_power(2), range(1, 10))))
# 用参数返回相应的数学函数的示例
# y = a * x ** 2 + b * x + c
def make_function(a, b, c):
def fx(x):
return a * x ** 2 + b * x + c
return fx
# 创建一个y = 4 * x ** 2 + 5 * x + 6 的函数用fx1绑定
fx1 = make_function(4, 5, 6)
print(fx1(2)) # 求在x等于2时,y的值
| false |
e8145732b8e620b6c893d2715e3d88c5ef6ba8c3 | shetty019/Python | /factorialofnum.py | 310 | 4.28125 | 4 | inp=raw_input('enter a number: ')
num=int (inp)
factorial=1
if num<0:
print('sorry factorial does not exist for negative numbers')
elif num==0:
print('the factorial of 0 is 1')
else:
for i in range (1,num+1):
factorial=factorial*i
print ('the factorial of',num,'is',factorial) | true |
c08f7dccfefe3ef3de81cbeca0c51688223ea506 | zhh-3/python_study | /Python_code/demo2/demo2.py | 1,069 | 4.125 | 4 | """
testlist = [1, "test"]
print(type(testlist[0]))
print(type(testlist[1]))
print(testlist[0])
print(testlist[1])
namelist = ["张", "王", "李"]
print("--"*10)
for name in namelist:
print(name)
# 增加
# append 在末尾添加数据
nametemp = input("新的姓:")
namelist.append(nametemp)
print("--"*10)
for name in namelist:
print(name)
a = [1, 2]
b = [3, [4, 5]]
a.append(b)
print(a) # [1, 2, [3, [4, 5]]]
a.extend(b) # [1, 2, [3, [4, 5]], 3, [4, 5]]
print(a)
"""
a = [1, 2, 3, 4]
index = 1
value = 5
a.insert(index, value) # [1, 5, 2, 3, 4]
print(a)
# 删除 del .pop .remove
movies = ["a", "b", "c", "d", "a", "e"]
for movie in movies:
print(movie, end=" ")
print("\n"+"--"*15)
# 指定下标删除
del movies[1]
for movie in movies:
print(movie, end=" ")
print("\n"+"--"*15)
# 最后一个元素
movies.pop()
for movie in movies:
print(movie, end=" ")
print("\n"+"--"*15)
# 第一个“a”
movies.remove("a")
for movie in movies:
print(movie, end=" ")
print("\n"+"--"*15) | false |
d0b37e4d192604b256b2b98176d20e3eac3a61f4 | LocksleyLK/gwc2018 | /guessTheNumberForLoop.py | 843 | 4.40625 | 4 | #imports the ability to get a random number (we will learn more about this later!)
from random import *
#Generates a random integer.
aRandomNumber = randint(1, 20)
# For Testing: print(aRandomNumber)
for guesses in range(3):
guess = input("Guess a number between 1 and 20 (inclusive): ")
if not guess.isnumeric(): # checks if a string is only digits 0 to 9
print("That's not a positive whole number, try again!")
else:
guess = int(guess) # converts a string to an integer
if guesses == 3 & guess != aRandomNumber:
print("You ran out of guesses!")
break
if guess == aRandomNumber:
print("Great guess! You have guessed my number!")
break
if guess < aRandomNumber:
print("My secret number is greater than your guess")
elif guess > aRandomNumber:
print("My secret number is less than your guess")
| true |
b8e3ff1c79c8254978e7306218995c7599cdcc61 | Balideli/dividendcalculator | /dividend.py | 547 | 4.15625 | 4 | #python
#store user input dividend information in array
dividend_array = []
count = 0
user_input = input("Enter the dividend: ")
count +=
dividend_array.append(user_input)
#Now add together and divide for average
total = 0
for dividend in range len(dividend_array) :
total += dividend
average = total/len(dividend_array)
print(f"Total average dividend is: {average}.")
function calculateDividend{
for(i=0; i<stockArray.length; i++){
totalDividend += stockArray[i].dividend;
}
return totalDividend;
}
| true |
7473abff0a0d8a3f219959a9a123a609757916a0 | AnvilOfDoom/PythonKursus2019 | /Bogopgaver/Kap 8/8-8.py | 1,180 | 4.625 | 5 | """8-8. User ALbums
Start with your program from Exercise 8-7. Write a while loop that allows users to enter an album’s artist and title.
Once you have that information, call make_album() with the user’s input and print the dictionary that’s created.
Be sure to include a quit value in the while loop."""
#function from 8-7:
def make_album(artist_name, album_title, tracks = ""):
if tracks:
album = {"artist name": artist_name, "title": album_title, "number of tracks": tracks}
else:
album = {"artist name": artist_name, "title": album_title}
return album
#while loop for a user to enter artists and titles for albums.
while True:
#introducing the option to quit program
print("Please note you can quit any time by entering 'q'")
#prompting for name of artist
artist = input("Please enter the artist's name: ")
#checking if the user chose to quit
if artist.lower() == "q":
break
title = input("Please enter the album's name: ")
# checking if the user chose to quitNo i
if title.lower() == "q":
break
#making the album and printing it
album = make_album(artist, title)
print(album) | true |
49f5070a7595ac10c5303bb6a5805eadc871e695 | AnvilOfDoom/PythonKursus2019 | /Bogopgaver/Kap 10/exercise_10_8.py | 1,167 | 4.375 | 4 | """10-8. Silent Cats and Dogs
Make two files, cats.txt and dogs.txt.
Store at least three names of cats in the first file and three names of dogs in the second file.
Write a program that tries to read these files and print the contents of the file to the screen.
Wrap your code ina try-except block to catch the FileNotFound error,
and print a friendly message if a file is missing.
Move one of the files to a different location on your system,
and make sure the code in the except block executes properly."""
#NB: En bedre løsning ville komme filerne i en liste og bruge et for-loop. Dette ville betyde at programmet ikke
#stopper ved den første fil, der mangler.
try:
# opening the cats.txt file
with open("cats.txt") as cats:
print("The list of cats contains:")
for cat in cats: #printing the contents
print(cat.strip().title())
print("")
#opening the dogs.txt file
with open("dogs.txt") as dogs:
print("The list of dogs contains:")
for dog in dogs: #printing the contents
print(dog.strip().title())
except FileNotFoundError:
print("One or more of your files are missing.") | true |
bbb4d8bb445aad2c49f6842b85ca4342edff3eb5 | AnvilOfDoom/PythonKursus2019 | /Bogopgaver/Kap 10/exercise_10_7.py | 1,116 | 4.28125 | 4 | """10-7.
Wrap your code from Exercise 10-6 in a while loop
so the user can continue entering numbers
even if they make a mistake and enter text instead of a number."""
print("This program lets you enter two numbers one after the other "
"and will then give you the sum of the numbers combined.")
while True:
try:
first_number = input("Please enter the first number: ") #The first number
if first_number == "q": #option to quit
break
else:
first_number = int(first_number) #Converting input to integer
second_number = input("Please enter the second number: ") #The second number
if second_number == "q": #option to quit
break
else:
second_number = int(second_number) #Converting input to integer
except ValueError:
print("Please enter a number with no decimals.")
else:
result = first_number + second_number #calculating the sum
print(result) | true |
90e1899aa7abc9091ef6477c886035f9b156e1cf | AnvilOfDoom/PythonKursus2019 | /Bogopgaver/Kap 6/6-2.py | 384 | 4.15625 | 4 | """6-2. Favorite Numbers
Exercise creating a dictionary of persons and their favorite numbers"""
#dictionary of people and their favorite numbers
favorite_numbers = {"Emil": 1, "Rose": 3, "Mike": 7, "Kaleb": 15, "Denis": 31}
#printing the keys and values of the dictionary.
for number in favorite_numbers:
print(number + "'s favorite number is " + str(favorite_numbers[number])) | true |
bc91fa8b8011d583c248ed3aa33165de879ed1b9 | AnvilOfDoom/PythonKursus2019 | /Bogopgaver/Kap 6/6-8.py | 526 | 4.5 | 4 | """6-8. Pets
Another list with dictionaries, then printing everything known about each pet"""
#list of pets
pets = []
#dictionaries of pets, creating the pet dictionaries and appending them to the list
pet = {"name": "claw", "kind of animal": "cat", "owner's name": "laura"}
pets.append(pet)
pet = {"name": "drool", "kind of animal": "dog", "owner's name": "richard"}
pets.append(pet)
#printing the pets
for pet in pets:
for key, value in pet.items():
print(key.title() + ": " + value.title())
print("")
| true |
dcce40f85c03d17cdaf722f4ffb396f175ffd050 | AnvilOfDoom/PythonKursus2019 | /Bogopgaver/Kap 6/6-11.py | 777 | 4.40625 | 4 | """6-11. Cities
A dictionary of dictionaries, one dictionary each per city, which then contains info about that city"""
#Dictionary of cities
cities = {
"aarhus": {"country": "denmark", "population": 273000, "current mayor": "jacob bundsgaard"},
"copenhagen": {"country": "denmark", "population": 613000, "current mayor": "frank jensen"},
"aalborg": {"country": "denmark", "population": 137000, "current mayor": "thomas kastrup-larsen"},
}
for city, city_information in cities.items():
print(
city.title() + " is a city in " +
city_information["country"].title() +
" with a population of around " +
str(city_information["population"]) + " people." +
" The current mayor is called " + city_information["current mayor"].title() + ".\n")
| false |
c905b62e494edf8efa0f3feec5abe98c934f8002 | AnvilOfDoom/PythonKursus2019 | /Bogopgaver/Kap 7/7-2.py | 645 | 4.53125 | 5 | """7-2. Restaurant Seating
This program should ask for a number of people in a dinner group. If the number is more than 8 the program should
print a message that they'll have to wait for a table. Otherwise print a message that their table is ready"""
#prompt for input
guests_number = input("How many are in your group? Please type a number: ")
#converting the answer to an integer
guests_number = int(guests_number)
#an if-else statement that prints a message depending on whether there are 1-8 guests or more.
if guests_number <= 8:
print("Your table is ready.")
elif guests_number > 8:
print("Please wait for a table to be ready.") | true |
19a397b8b19ea27214bb94d068b9c8b1c0fdc989 | DavidCloud/Intro-to-computer-science | /Choose_path_DC.py | 2,582 | 4.40625 | 4 | #Name: David Cloud
#Period: 7th
#Date: october 20th, 2016
#Assignment: Choose your path
#Scope: This program will allow the user to pick their path through a story
print ("You wake up in the middle of a jungle what do you do: Go back to Sleep (1) or Explore your surrondings (2)"); #Question 1
Question1 = int(input()); #Input for Question 1
if Question1 == 1: #Option 1 for Question 1
print ("You went back to bed for a while and a few hours later was awaken by a giant tiger. Do you Fight the Tiger (1) or Run Away (2)"); #Question 2
Question2a = int(input()); #Answer for question 2
if Question2a == 1: #Option 1 for Question 2
print ("You fight the tiger and after a while you jump into the river and escape it. Do you swim upstream (1) or downstream (2)"); #Question 3 for first option of Question 1
Question3a = int(input()); #Input for Question 3 of option 1 for Question 2
elif Question2a == 2: #Option 2 for Question 2
print ("You start to run away from the tiger, but it chases after you. Do you want to climb up a tree (1), or jump into the river (2)"); #Question 3 for second option of Question 1
Question3b = int(input()); #Option 2 for question 3 of option 2 for Question 2
if Question3a == 1: #Option 1 for Question 3
print ("You jump into the river and start swimming upstream. You eventually come up to a waterfall and get to the bank just in time. Do you want to rest for a while (1) or try to build a shelter to sleep in (2)"); #Question 4 for first option of Question 3
Question4a = int(input()); #Input for Question 4 for option 1 of Question 3
elif Question3a == 2:
print("After you jump into the river and swim downstream you see a hippo in the water. After you get ")
elif Question3b == 2: #Option 2 for Question 3
print ("You jump into a river and see several big fish swimming towards you. Do you want to swim upstream away from the fish (1) or downstream towards the firsh (2)"); #Question 4 for second option of Question 3
Question4b = int(input()); #Input for Question for option 2 of Question 3
if Question4a == 1:
print("You climb back down the tree and don't see the tiger anywhere so you go walk around the forest and find a makeshift shelter. Do you want to scavenge the makeshift shelter (1) or find a good spot to make your own shelter (2)")
elif Question4a == 2:
print("")
if Question1 == 2: #Option 2 for Question 1
| true |
0a38a8e09111ce830a5eb99fa6369634b4c9e34c | kudinov-prog/Checkio | /Home/Sun Angle.py | 1,183 | 4.4375 | 4 | """
Your task is to find the angle of the sun above the horizon knowing the time of the day. Input data:
the sun rises in the East at 6:00 AM, which corresponds to the angle of 0 degrees.
At 12:00 PM the sun reaches its zenith, which means that the angle equals 90 degrees.
6:00 PM is the time of the sunset so the angle is 180 degrees. If the input will be the time
of the night (before 6:00 AM or after 6:00 PM), your function should return - "I don't see the sun!".
"""
def sun_angle(time):
angel_on_min = 180/720
time_split = time.split(":")
time_min = int(time_split[0]) * 60 + int(time_split[1]) - 360
if 5 < int(time_split[0]) < 18:
angle_sun = angel_on_min * time_min
return angle_sun
if int(time_split[0]) == 18 and time_split[1] == "00":
return 180.00
else:
return "I don't see the sun!"
if __name__ == '__main__':
print("Example:")
print(sun_angle("07:00"))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert sun_angle("07:00") == 15
assert sun_angle("01:23") == "I don't see the sun!"
print("Coding complete? Click 'Check' to earn cool rewards!") | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.