blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9ca49c016b8b42add91d44495d68cb1d2fb75288 | rid47/python_basic_book | /Power of IT Job/only_print_even.py | 281 | 4.15625 | 4 | n = int(input("Enter no. of elements:"))
num_list = []
for i in range(1, n):
num = int(input())
num_list.append(num)
print(num_list)
even_num_list = []
for num in num_list:
if num % 2 == 0:
even_num_list.append(num)
print(f"Even numbers: {even_num_list}")
| false |
952e73286042134eff61ecc1143cafe46e850285 | rid47/python_basic_book | /review_ex_page101.py | 343 | 4.21875 | 4 | print("AAA".find('a'))
given_string = "Somebody said something to Samantha."
modified_string = given_string.replace("s", "x")
print(modified_string)
user_input = input("Enter a string")
search_result = user_input.find("a")
if search_result != -1:
print("You have 'a' in your string")
else:
print("You don't have 'a' in your string")
| true |
fdbc5f34c9b7adccd998a8af1e297db73d24d2dc | rid47/python_basic_book | /python_lynda/if.py | 383 | 4.1875 | 4 | n = input("Choose an integer between -10 and 10 and enter it here: ")
n = int(n)
if n < 5:
print("The integer you choose is less than 5")
else:
print("The integer you choos is greater than 5")
def max(x, y):
if x > y:
return x
else:
return y
result = max(5, 7)
print(result)
result = max(-5, -7)
print(result)
result = max(10, 10)
print(result)
| true |
f941088c243f0cd52b3c57ec72b07129c73195e0 | dvp-git/Core_Python_Pluralsight | /ListCopyTest.py | 1,827 | 4.65625 | 5 | # Example of List copies and list repeatation
import copy
list_1 = [1,2,3,4,5,6]
list_2 = list_1[:]
# Test for equivalence:
print("\n############### Test for List Equivalence ################\n ")
print(f"list_1 is equivalent to list_2 {list_1 == list_2}")
print(f"list_1 is list_2 {list_1 is list_2}")
# Note that these are shallow copies, meaning that the elements within both the lists refer to the same object
print(f" Note that these are shallow copies, meaning that the elements within both the lists refer to the same object")
for i in range(0,len(list_1)):
print(f"list[{i}] equal to list[{i}] : {list_1[1] == list_2[1]}")
# Shallow copy can be done using:
# list_1 = list_2[:]
# list_2 = copy.copy(list_1)
# list_2 = list(list_1)
# Demonstrating Deep copy
print("\n############### Demonstrating Deep copy ################\n ")
list_1 = copy.deepcopy(list_1)
print(f"list_1:{list_1}")
list_1[0] = 1231
print(f"Changed list_1: {list_1}")
print(f"list_2: {list_2}")
# Demonstrating list repeatation
print("\n############### Demonstrating list repeatation ################\n ")
repeat_1 = [[1,0,2]] * 4
print(f"Initial list for repeat{repeat_1}")
print(f"Making repeat_1[1][2] = 819" )
print(f"Appending 900 to first list repeat_1[0].append(900)")
repeat_1[1][2] = 819
repeat_1[0].append(900)
print(f"Final result makes changes in all the entries: {repeat_1}")
"""
Output:
list_1 is equivalent to list_2 True
list_1 is list_2 False
Note that these are shallow copies, meaning that the elements within both the lists refer to the same object
list[0] equal to list[0] : True
list[1] equal to list[1] : True
list[2] equal to list[2] : True
list[3] equal to list[3] : True
list[4] equal to list[4] : True
list[5] equal to list[5] : True
"""
| true |
95172a99158942f442f8d93e6bfa41b14d5e0772 | rajeshk738/Python_Programming | /Python_Programs/Python_Programs_UTA/Basic_Program/traversing_back.py | 340 | 4.125 | 4 |
def traversing_backwards(input_list):
length = len(input_list)
i = -1
output_list = []
while(i >= -length):
output_list.append(input_list[i])
i = i - 1
return output_list
input_list = ['apples', 'eat', "don't", 'I', 'but', 'Grapes', 'Love', 'I']
print(traversing_backwards(input_list))
| true |
837ef788f788ea49f496341e4f105a92848fc740 | CDC24/unit6 | /longestDictionaryWord.py | 241 | 4.1875 | 4 | #Caleb Callaway
#5/10/18
#longestDictionaryWord.py - print the longest word in the dictionary list
file=open("engmix.txt")
longest = ""
for word in file:
if len(word) > len(longest):
longest = word
print("The longest word is",longest) | true |
2e6afab7c3312a73a2837a4a669003009cce1e46 | smsenger/GroupExercises | /fibinacci.py | 1,412 | 4.59375 | 5 | #Program that asks the user for integer input, then outputs the integers of the fibinacci sequence. Will continue
#until reaching the number represented by user input (7 == the 7th integer in the f. sequence)
#asks for user input // Defines starting point of numbers in sequence
user_num = input('Please select a whole number: ')
num1 = 1
num2 = 1
count = 1
try:
user_num = int(user_num)
while count <= user_num: #goes up until 'n'.prints out next 'n' numbers of the fibonacci sequence.
print(num1)
total = num1 + num2 #adds two numbers together to get third number
num1 = num2
num2 = total
count += 1
except:
user_retry = input('Please run program again and enter a valid whole number when prompted.')
#Alternative method:
#Program that asks the user for numberical input, 'n',
# user_num = input('Please select a whole number: ')
# num1 = 1
# num2 = 1
# count = 1
# While True:
# try:
# user_num = int(input('Please select a whole number: '))
# break
# except:
# print('Please run program again and enter a valid whole number when prompted.')
# while count <= user_num: #goes up until 'n'.prints out next 'n' numbers of the fibonacci sequence.
# print(num1)
# total = num1 + num2
# num1 = num2
# num2 = total
# count += 1
| true |
38f60c8abe79db164609b281c5bdc2b44c9b6b24 | aravinds-arv/dsa-algs-py | /week-3/lecture-pgms/insertionSort.py | 976 | 4.34375 | 4 | def insSort(seq):
"""
Returns a list sorted in the ascending order
Parameters:
----------
l (list/array): A list or an array
Returns:
-------
l (list/array): The sorted list is returned
"""
# In each scan we go through slices l[0:0], l[0:1], l[0:2] and so on
# and in each scan we either sort the slice or leave it as it is if already sorted
for sliceEnd in range(len(seq)):
# for each slice we check whether the element in the slice end is smaller than the preceeding value if so they're swaped
# the process is repeated until the element reaches either
# a position whereit requires no more swapping or
# the first postion seq[0]
pos = sliceEnd
while pos > 0 and seq[pos] < seq[pos-1]:
(seq[pos], seq[pos-1]) = (seq[pos-1], seq[pos])
pos = pos - 1
return seq
print(insSort([97, 45, 68, 73, 32, 81, 104])) | true |
41816bc35f83d4c8cb9cf3e258b6fa18e7bd1cb2 | darkeclipz/python | /statistiek.py | 2,631 | 4.25 | 4 | # Lars Rotgers (lars.rotgers@student.nhlstenden.com), 21-9-2019
from math import sqrt
def validate_all_values_are_numbers(values):
for value in values:
if not isinstance(value, (int, float)):
raise ValueError('Value {} is not a real number.'.format(value))
def is_even(x):
return x % 2 == 0
def get_middle_element(values):
n = len(values)
if is_even(n):
raise ValueError('Length of the list must be odd.')
return values[n // 2]
def get_middle_two_elements(values):
n = len(values)
if not is_even(n):
raise ValueError('Length of the list must be even.')
return values[n // 2], values[n // 2 - 1]
def median(values):
"""
Calculate the median for a list of numbers.
:param values: List of numbers.
:return: Median value for the list.
"""
validate_all_values_are_numbers(values)
values = sorted(values)
if is_even(len(values)):
return sum(get_middle_two_elements(values)) / 2
return get_middle_element(values)
def mean(values):
"""
Calculate the mean for a list of numbers.
:param values: List of numbers.
:return: Mean value for the list.
"""
validate_all_values_are_numbers(values)
if len(values) == 0:
raise ValueError('List can\'t be empty, otherwise it divides by zero.')
return sum(values) / len(values)
def first_element(values):
return values[0]
def last_element(values):
return values[-1]
def spread(values):
"""
Calculate the spread for a list of numbers.
:param values: List of numbers.
:return: Spread for the list of numbers.
"""
validate_all_values_are_numbers(values)
values = sorted(values)
return last_element(values) - first_element(values) # or max(x) - min(x), but that sorts twice
def squared_error(x, m):
return (x - m)**2
def sse(values):
m = mean(values)
return sum([squared_error(x, m) for x in values])
def variance(values):
return sse(values) / len(values) # mean checks div 0
def sd(values):
"""
Calculate the standard deviation for a list of numbers.
:param values: List of numbers.
:return: Standard deviation for a list of numbers.
"""
validate_all_values_are_numbers(values)
var = variance(values)
return sqrt(var)
def descriptive_statistics(values):
"""
Calculate the median, mean, spread, and standard deviation for
a list of values.
:param values: List of values
:return: Tuple which contains (median, mean, spread, stddev)
"""
validate_all_values_are_numbers(values)
return median(values), mean(values), spread(values), sd(values)
| true |
d1c7a96aa5e9c81627bbbd702359f8d790bcac1c | CongoCash/Rocket | /Updated/intro-algorithms/solutions/solution-insertionsort.py | 305 | 4.28125 | 4 | def insertion_sort(items):
for i in range(1, len(items)):
j = i
while j > 0 and items[j] < items[j-1]:
items[j], items[j-1] = items[j-1], items[j]
j -= 1
items = [3,89,14,1,6,334,9,0,44,101]
print 'Before: ', items
insertion_sort(items)
print 'After: ', items | false |
41eeeb32478873a311e69d463e67e8fa44efeb50 | CongoCash/Rocket | /Updated/techcercises/number_encoding/number_encoding.py | 469 | 4.125 | 4 | # Using the Python language, have the function number_encoding(str) take the str parameter and encode the message according
# to the following rule: encode every letter into its corresponding numbered position in the alphabet.
# Symbols and spaces will also be used in the input.
# For example: if str is "af5c a#!" then your program should return 1653 1#!.
# Input = "hello 45" Output = 85121215 45
# Input = "jaj-a" Output = 10110-1
def number_encoding(str):
pass | true |
c6d53fe81f8a082a17936a70b5a76c508df01d6c | CongoCash/Rocket | /Updated/skills-review-01/skills01.py | 2,307 | 4.5 | 4 |
#Declare a variable, now assign a number to it. It can be any number.
#Your code goes here:
#*****
#Declare a new variable with any name you like. Make up a string value and assign it to the variable. Do all of this in one statement.
#Your code goes here:
#*****
#In one line, declare a variable and assign an empty list to that variable.
#Your code goes here:
#*****
#Using the list variable you just created, write a loop that counts from 1 to 10 and adds each number to the list.
#Your code goes here:
#*****
#Rewrite the previous section so that it counts from 1 to 50 in increments of 5.
#Your code goes here:
#*****
#Rewrite the previous section using a list comprehension.
#Your code goes here:
#*****
#Rewrite the above code again, this time as a function.
#Assign the function to a variable so you can invoke it later by that variable name.
#Include a parameter that represents the maximum number that the loop will count to.
#Rewrite the code in your loop so that the loop counts to the value held by the parameter.
#Your code goes here:
#*****
#Here is a sample dictionary:
#Write a loop that iterates through this dictionary and prints the values for each key.
#Your code goes here:
#*****
#Using the same dictionary defined above (myDict), Write a function that:
#Creates a list variable
#Iterates through the dictionary and
#Creates a sub-list from each key:value pair
#pushes that sub-list into the main list
#Return the main list
#Your function should return a list like this:
#[['prop1','dog'],['prop2','cat']...]
#Your code goes here:
#*****
#FizzBuzz!
#Write a function that prints the numbers from 1 to 100.
#For multiples of three print “Fizz” instead of the number
#For the multiples of five print “Buzz”.
#For numbers which are multiples of both three and five print “FizzBuzz”."
#HINT - this is a great opportunity to use the 'modulo' operator (%).
#How does it work?
#modulo returns the remainder of a division operation
#example: x = 3 % 2; (x is equal to 1, or the remainder of 3 divided by 2)
#but y = 4 % 2; (y is equal to 0, or the remainder of 4 divided by 2)
#you can use the modulo operator in an 'if' statement to determine if a number is evenly divisible by another.\
| true |
a0b2d48634c50f5b6ccbd2c75bb0f281908478f4 | ric-smashitpro/pythonProject | /Workshop6.py | 1,305 | 4.46875 | 4 | # Task 1
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print(f"This is count {number}")
# same as above
for fruit in fruits:
print(f"A fruit of type: {fruit}")
# also we can go through mixed lists too
for i in change:
print(f"I got {i}")
# we can also build lists, first start with an empty one
elements = []
# then use the range function to generate a list
elements = range(0, 6)
# now we can print them out too
for i in elements:
print(f"Element was: {i}")
# Task 2
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there's not 10 things in that list, let's fix that.")
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print("Adding: ", next_one)
stuff.append(next_one)
print(f"There's {len(stuff)} items now.")
print("There we go: ", stuff)
print("Let's do some things with stuff.")
print(stuff[1])
print(stuff[-1]) # whoa! fancy
print(stuff.pop())
print(type(stuff), stuff)
print(' '.join(stuff)) # what? cool!
print('#'.join(stuff[3:5])) # super stellar!
| true |
5815d2abb36daff32238ee586519ff5e746b941e | Pyrizard/PythonGrand | /Python Programs/GUI/Tkinter/Minimal application with explanation.py | 1,675 | 4.125 | 4 | '''#!/usr/bin/env python only for linux''' #1
import tkinter as tk #2
class Application(tk.Frame): #3
def __init__(self, master=None):
tk.Frame.__init__(self, master) #4
self.grid() #5
self.createWidgets()
def createWidgets(self):
self.quitButton = tk.Button(self, text='Quit',
command=self.quit) #6
self.quitButton.grid() #7
app = Application() #8
app.master.title('Sample application') #9
app.mainloop() #10
'''
1 This line makes the script self-executing, assumingthatyour system has Python correctlyinstalled.
2 This line imports the Tkinter module into your program's namespace, but renames it as tk.
3 Your application class must inherit from Tkinter's Frame class.
4 Calls the constructor for the parent class, Frame.
5 Necessary to make the application actually appear on the screen.
6 Creates a button labeled “Quit”.
7 Places the button on the application.
8 The main program starts here by instantiating the Application class.
9 This method call sets the title of the window to “Sample application”.
10 Starts the application's main loop, waiting for mouse and keyboard events.
'''
| false |
be67498f9f253957588aa1786784df18e692b9a4 | PatMulvihill/lpthw | /exercise06/ex6_studydrill1.py | 1,107 | 4.28125 | 4 | # x is a variable that holds a string formatted with an integer
x = "There are %d types of people." % 10
# binary is a string that contains the word binary
binary = "binary"
# do_not is a variable holding the string "don't"
do_not = "don't"
# y is a string variable that contains a string formatted with two integers
y = "Those who know %s and those who %s." % (binary, do_not)
# print the formatted contents of x
print x
# print the formatted contents of y
print y
# print a repition of what just happened with nested strings
print "I said: %r." % x
print "I also said: '%s'." % y
# hilarious is a boolean variable containing False
hilarious = False
# joke_evaluation is a string variable that contains a boolean formatter
joke_evaluation = "Isn't that joke so funny?! %r"
# print joke_evaluation with hilarious as it's formatter parameter
print joke_evaluation % hilarious
# declare two strings that we will concatenate named w and e
w = "This is the left side of..."
e = "a string with a right side."
# print w and e added together, which just concatenates e to the end of the w string
print w + e
| true |
5fa1b20de82277d6b2be6d25c5b7777f6beeadb1 | stushar12/python-DSA-4 | /second.py | 2,393 | 4.15625 | 4 | class Node(object):
def __init__(self,data):
self.data=data
self.nextNode=None
class LinkedList(object):
def __init__(self):
self.head = None
self.size=0
def insertEnd(self,data):
self.size=self.size+1
newNode=Node(data)
actualNode=self.head
if not self.head:
self.head=newNode
else:
while actualNode.nextNode is not None:
actualNode=actualNode.nextNode
actualNode.nextNode=newNode
def traverseList(self) :
actualNode = self.head
while actualNode is not None:
print("%d " % actualNode.data,end=" ")
actualNode = actualNode.nextNode
def merge(a,b):
temp=None
start=None
if a is None:
return b
elif b is None:
return a
while(a is not None and b is not None):
if(a.data<=b.data and temp is None):
temp=a
start=temp
a=a.nextNode
elif (a.data>=b.data and temp is None):
temp=b
start=temp
b=b.nextNode
elif (a.data<=b.data):
temp.nextNode=a
temp=a
a=a.nextNode
elif (a.data>=b.data):
temp.nextNode=b
temp=b
b=b.nextNode
if(a is None and b is not None):
while(b is not None):
temp.nextNode=b
temp=b
b=b.nextNode
elif (a is not None and b is None):
while(a is not None):
temp.nextNode=a
temp=a
a=a.nextNode
return start
linkedlist1=LinkedList()
linkedlist2=LinkedList()
linkedlist3=LinkedList()
b=1
while(b):
b=int(input("\nEnter choice\n 1 to insert \n 2 to traverse \n 0 to exit: \n "))
if b==1:
a=int(input("Enter a number: "))
linkedlist1.insertEnd(a)
elif b==2:
linkedlist1.traverseList()
b=1
while(b):
b=int(input("\nEnter choice\n 1 to insert \n 2 to traverse \n 0 to exit: \n "))
if b==1:
a=int(input("Enter a number: "))
linkedlist2.insertEnd(a)
elif b==2:
linkedlist2.traverseList()
linkedlist3.head=merge(linkedlist1.head,linkedlist2.head)
linkedlist3.traverseList()
| true |
bf40f7ef8f29c48c90c8675771f4be8c9bab5153 | JulianArbini97/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-append_write.py | 261 | 4.125 | 4 | #!/usr/bin/python3
""" Write a function that reads a text file to stdout """
def append_write(filename="", text=""):
""" append text to a created or not text """
with open(filename, 'a', encoding='utf-8') as MyFile:
return(MyFile.write(text))
| true |
a81a514b675224b40d30a92b9b55c55e5d320d4e | Kos1981/Lessons | /task2-3.py | 433 | 4.25 | 4 | #3. Дан список заполненный произвольными целыми числами.
#Получите новый список, элементами которого будут только уникальные элементы исходного.
list_1 = [2, 5, 8, 2, 12, 7, 11, 12, 4, 8, 4, 12, 3]
list_2 =[]
for element in list_1:
if list_1.count(element)==1:
list_2.append(element)
print(list_2)
| false |
0595911f85282bdf991d8484423a9bd48b26c76a | Kos1981/Lessons | /module5_1.py | 771 | 4.125 | 4 | #1. Создайте модуль (модуль — программа на Python, т.е. файл с расширением .py). В нем напишите функцию, создающую
# директории от dir_1 до dir_9 в папке, из которой запущен данный код. Затем создайте вторую функцию, удаляющую эти
# папки. Проверьте работу функций в этом же модуле.
import os
def create_folders(name,count):
for i in range(1,count+1):
os.mkdir(name+str(i))
def remove_folders(name,count):
for i in range(1,count+1):
os.rmdir(name+str(i))
if __name__=='__main__':
create_folders('dir_',9)
remove_folders('dir_',9)
| false |
ecb6c7508e6dc84a05d92348e09a18214733a35f | twknab/learning-python | /01_python_fundamentals/05_Assignments/assgn-17-find-characters.py | 1,147 | 4.4375 | 4 | '''
Write a program that takes a list of strings and a string containing a single
character, and prints a new list of all the strings containing that character.
Here's an example:
# input
l = ['hello','world','my','name','is','Anna']
char = 'o'
# output
n = ['hello','world']
Hint: how many loops will you need to complete this task?
Answer: 1
'''
def find_characters(str_list, str_character):
character = str_character
character_list = [];
for word in str_list:
if character in word:
character_list.append(word)
print '#CHARACTER: {}'.format(str_character)
print '#WORDS: {}'.format(character_list)
return character_list
print '#LIST 1'
find_characters(['hello','world','my','name','is','Anna'], 'o')
print '#LIST 2'
find_characters(['adobe','gimp','corel'], 'e')
'''
Instead of regex, we can use a built in python method that can look at a string
and match for a character or even word.
http://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method
example_string = "This is an example string"
substring = "example"
print(substring in example_string)
'''
| true |
071d96aaac059e002c48d50d33a096fdccdbf1ff | twknab/learning-python | /01_python_fundamentals/05_Assignments/assgn-14-compare-arrays.py | 1,336 | 4.34375 | 4 | '''
Write a program that compares two lists and prints a message depending on if
the inputs are identical or not.
Your program should be able to accept and compare two lists: list_one and
list_two. If both lists are identical print "The lists are the same". If they
are not identical print "The lists are not the same." Try the following test
cases for lists one and two:
list_one = [1,2,5,6,2]
list_two = [1,2,5,6,2]
list_one = [1,2,5,6,5]
list_two = [1,2,5,6,5,3]
list_one = [1,2,5,6,5,16]
list_two = [1,2,5,6,5]
list_one = ['celery','carrots','bread','milk']
list_two = ['celery','carrots','bread','cream']
'''
def compare_arrays(list1, list2):
if ((type(list1) is list) and (type(list2) is list)):
if (list1 == list2):
print 'The lists are the same.'
return 'The lists are the same.'
else:
print 'The lists are not the same.'
return 'The lists are not the same.'
else:
print 'These are not lists.'
return 'Error: These are not lists.'
compare_arrays([1,2,5,6,2],[1,2,5,6,2])
compare_arrays([1,2,5,6,5],[1,2,5,6,5,3])
compare_arrays([1,2,5,6,5,16],[1,2,5,6,5])
compare_arrays(['celery','carrots','bread','milk'],['celery','carrots','bread','cream'])
compare_arrays(['celery','carrots','bread','milk'],['celery','carrots','bread','milk'])
| true |
cf305c5019e32a38aa1ce6e978e7a46d10a353c7 | twknab/learning-python | /06_python_OOP/bike/bike.py | 963 | 4.3125 | 4 | # Bike Python OOP - Tim Knab
class Bike(object):
def __init__(self, price=None, max_speed=None, miles=0):
self.price = price
self.max_speed = max_speed
self.miles = miles
print 'New bike created!'
def displayInfo(self):
print 'Your Summary for: Price: ${}, Max Speed: {}mph, Total Miles: {}mi'.format(self.price, self.max_speed, self.miles)
def ride(self):
print 'Riding...'
self.miles += 10
print 'Total miles traveled: {}mi.'.format(self.miles)
def reverse(self):
print 'Reversing...'
self.miles -= 5
if self.miles < 0:
self.miles = 0
print 'Total miles traveled: {}.mi.'.format(self.miles)
bike_one = Bike(100, 25)
for count in range(3):
bike_one.ride()
bike_one.reverse()
bike_one.displayInfo()
bike_two = Bike(150, 30)
for count in range(2):
bike_two.ride()
for count in range(2):
bike_two.reverse()
bike_two.displayInfo()
bike_three = Bike(200, 40)
for count in range(3):
bike_three.reverse()
bike_three.displayInfo() | true |
2559b73b3872c322478d24f0be48d38e35a1c4e6 | EsterMiracle/Python_algorithms | /Python_algorithms/HW_lesson_4/task_3.py | 2,200 | 4.375 | 4 | """
Задание 3.
Приведен код, формирующий из введенного числа
обратное по порядку входящих в него
цифр и вывести на экран.
Сделайте профилировку каждого алгоритма через cProfile и через timeit
Сделайте вывод, какая из трех реализаций эффективнее и почему!!!
И можете предложить еще свой вариант решения!
Без аналитики задание считается не принятым
"""
from random import randint
from timeit import timeit
import cProfile
def revers_1(enter_num, revers_num=0):
if enter_num == 0:
return revers_num
else:
num = enter_num % 10
revers_num = (revers_num + num / 10) * 10
enter_num //= 10
return revers_1(enter_num, revers_num)
def revers_2(enter_num, revers_num=0):
while enter_num != 0:
num = enter_num % 10
revers_num = (revers_num + num / 10) * 10
enter_num //= 10
return revers_num
def revers_3(enter_num):
enter_num = str(enter_num)
revers_num = enter_num[::-1]
return revers_num
num = randint(999999, 9999999999)
print(f'revers_1= {timeit("revers_1(num)", "from __main__ import revers_1, num", number=10000)}')
print(f'revers_2= {timeit("revers_2(num)", "from __main__ import revers_2, num", number=10000)}')
print(f'revers_3= {timeit("revers_3(num)", "from __main__ import revers_3, num", number=10000)}')
cProfile.run("revers_1(num), revers_2(num), revers_3(num)")
# reverse_1 - как мы видим из результатов, здесь рекурсия работает медленее всех, из-за повторных вызовов
# reverse_2 - вариант с циклом работает практически в 2 раза быстрее рекурсии, т.к. нет повторных вызовов
# reverse_3 - вариант со сменной типа из int в строку оказался самым быстрым, т.к. у данной функции вес алгоритма О(n)
| false |
1605eb3c28f1a761b3ae578a6f21b7a840188b86 | EsterMiracle/Python_algorithms | /Python_algorithms/HW_lesson_3/task_3.py | 869 | 4.28125 | 4 | """
Задание 3.
Определить количество различных (уникальных) подстрок с использованием хеш-функции.
Дана строка S длиной N, состоящая только из строчных латинских букв.
Подсказка: примените вычисление хешей для подстрок с помощью хеш-функций и множества
Пример:
рара - 6 уникальных подстрок
рар
ра
ар
ара
р
а
"""
def hash_func(word, string_hash=[]):
for i in range(2, len(word) + 1):
string_hash.append(hash(word[1:i]))
string_hash.append(hash(word[:i - 1]))
return f"{set(string_hash)}\nКоличество уникальных подстрок: {len(set(string_hash))}"
print(hash_func("papa")) | false |
884d22a873ec1c5e977767f6484f6fd30a051ebf | ComplexRalex/Tkinter-Hello-World | /drag_and_drop.py | 1,440 | 4.3125 | 4 | # Esto es un programa que hace "drag and drop"... bueno mas o menos xD
# This code is intended to do "drag and drop" to an object (kind of)
import tkinter as tk
def handler(event):
global canvas, text, square
if int(event.type) == 4:
canvas.itemconfigure(
text,
text=":o"
)
canvas.itemconfigure(
square,
fill="#62040C",
outline="#A20208"
)
some(event)
elif int(event.type) == 5:
canvas.itemconfigure(
text,
text=";)"
)
canvas.itemconfigure(
square,
fill="#0C0462",
outline="#0802A2"
)
def some(event):
global canvas, text, square
canvas.coords(text,event.x,event.y)
canvas.coords(square,event.x-200,event.y-200,event.x+200,event.y+200)
window = tk.Tk()
window.resizable(False,False)
window.title("Test graficos")
canvas = tk.Canvas(window,width=600,height=600,bg="#0A0A0A")
canvas.bind("<Button-1>", handler)
canvas.bind("<B1-Motion>",some)
canvas.bind("<ButtonRelease-1>", handler)
square = canvas.create_rectangle(
100,100,
500,500,
fill="#0C0462",
outline="#0802A2",
width=3
)
text = canvas.create_text(
300,300,
text=";)",
font=("Open Sans",28,"bold"),
fill="#F0F0F0"
)
canvas.pack()
tk.mainloop()
| true |
c0f6d9a18d9133afff770f6e767bbc9231d58623 | StephaniePar/100DaysofCode | /day_1-1.py | 302 | 4.125 | 4 | #Write your code below this line 👇
a = """Day 1 - Python Print Function"
The function is declared like this:
print('what to print')"""
print(a)
print("""
""")
# or
a = "Day 1 - Python Print Function"
b = "The function is declared like this:"
c = "print('what to print')"
print(a, "\n", b,"\n",c)
| true |
baf6070900feabd943fe5de14bd9cbcc23fa4db1 | Hermotimos/Learning | /OOP/oop6_new_vs_init.py | 2,953 | 4.1875 | 4 | """
Source: https://www.youtube.com/watch?v=-zsV0_QrfTw
"""
class A:
def __new__(cls, *args, **kwargs):
print('new', cls, args, kwargs)
return super().__new__(cls)
def __init__(self, *args, **kwargs):
print('init', self, args, kwargs)
obj = A(1, 2, 3, akwarg=4)
"""
__new__:
* creates and returns the actual object
* receives the class as argument
* it's a class method
* it returns the object
__init__
* initializes the object, ex. sets values, default values etc.
* receives object (an instance of the class) as argument
* it doesn't return anything, it only modifies the object (self)
* it's only called if __new__ returns an object of the correct class
Use cases:
* subclassing builtin immutable types
* Singleton design pattern
"""
"""
* subclassing builtin immutable types
The role of __new__ in Python is primarely to allow programmers to subclass
immutable data types.
Subclassing a bultin type instead of wrapping it up in some Python code
may be desirable to achieve better performance: bulitins are written in C,
and have much better performance than Python code.
* first example doesn't work, because for immutable data types' __init__
it's too late to modify the object
* second example modifies the object in __new__, and that works
"""
# 1
class UppercaseTuple(tuple):
def __init__(self, iterable):
print(f'init {iterable}')
try:
for i, arg in enumerate(iterable):
self[i] = arg.upper()
except TypeError as exc:
print(exc) # Error: tuples are immutable, even in init
def inheriting_immutable_uppercase_tuple_example():
print("UPPERCASE TUPLE EXAMPLE:", UppercaseTuple(["hi", "there"]))
inheriting_immutable_uppercase_tuple_example()
# 2
class UppercaseTuple(tuple):
def __new__(cls, iterable):
upper_iterable = (s.upper() for s in iterable)
return super().__new__(cls, upper_iterable)
def inheriting_immutable_uppercase_tuple_example():
print("UPPERCASE TUPLE EXAMPLE:", UppercaseTuple(["hi", "there"]))
inheriting_immutable_uppercase_tuple_example()
"""
* Singleton design pattern
A singleton is class that should have at most 1 instance.
Ex. global config object, database connection.
All parts of the program have reference to the same object,
and whenever it's changed, all references get have access to the new state.
"""
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
# Here __new__ always returns an instance of the class,
# but it's not necesserily a 'new' instance - it may already exist.
if cls._instance is None:
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
def singleton_example():
print("SINGLETON EXAMPLE")
x = Singleton()
y = Singleton()
print(f'{x is y=}')
singleton_example() | true |
b44ad1e9ca40ec58588bceca66e78ff8ef9685b8 | memory-lf/Learn-python-from-scratch | /joseph-loop/palyer_class.py | 1,352 | 4.15625 | 4 | """
作者:LF
功能:存放(类)Player,运用私有属性
版本:2.0
日期:17/07/2020
问题描述:1.Player类的属性包括:name、sex、age
2.输入的性别应为male/female,输入的年龄应为大于0的正整数
"""
class Player:
def __init__(self, name, sex, age):
"输入的name、sex、age均为字符串形式"
self._name = name
if sex == "male" or sex == "female":
self._sex = sex
else:
raise ValueError("性别输入错误(male/female)")
if age.isdigit() is True:
if int(age) > 0:
self._age = age
else:
raise ValueError("年龄输入错误(非正整数)")
else:
raise ValueError("年龄输入错误(非整数)")
@property
def name(self):
return self._name
@property
def sex(self):
return self._sex
@property
def age(self):
return self._age
def __str__(self):
return "Name:{} Gender:{} Age:{}".format(self.name, self.sex, self.age)
if __name__ == "__main__":
player_instance = Player(1, "female", "3")
# 测试name
assert player_instance.name == 1
# 测试sex
assert player_instance.sex == "female"
# 测试age
assert player_instance.age == "3"
| false |
b071a0adc549cfee98eda2926d599b29275f1f06 | rajendra07negi/python_program | /multiD_array.py | 694 | 4.375 | 4 | from numpy import *
# 2D array
arr2d = array([
[3,5,4,9,54,34],
[12,43,54,56,30,40]
])
print(arr2d)
# Use some in built function on multi dimensional array
print(arr2d.dtype)
# give the type of array data
print(arr2d.ndim)
# return the number of dimensional of array
print(arr2d.shape)
# it is give the dimension and size information of array
# but if arrays have different size
# than it returns only dimension not return size
print(arr2d.size)
# it return size of entire block
arr1 = arr2d.flatten()
# this make multi dimensional array to single dimensional array
print(arr1)
# if we want to make 2 d from 1 d
arr3 = arr1.reshape(2,2,3)
print(arr3) | true |
eeabfb1ee533782f03e15e0adfcc5943920ce213 | IslamFadl/CS106A_Stanford_Spring_2020 | /Assignments/Assignment2/Assignment2/khansole_academy.py | 846 | 4.1875 | 4 | """
File: khansole_academy.py
-------------------------
Add your comments here.
"""
import random
def main():
correct_answers = 0
while correct_answers != 3:
num1 = random.randint(10, 99)
num2 = random.randint(10, 99)
print("What is " + str(num1) + " + " + str(num2) + " ?")
sum = num1 + num2
Your_answer = int(input("Your answer is: "))
if sum == Your_answer:
print("Correct! You've gotten " + str(correct_answers+1) + " correct in a row.")
correct_answers += 1
else:
print("Incorrect. The expected answer is: " + str(sum))
correct_answers = 0
print("Congratulations! You mastered addition.")
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
main()
| true |
843e1a2d1d2612068463bd4343ba918474af2f03 | absnetto/IDE-PyCharm | /Excercícios3/e (6).py | 627 | 4.21875 | 4 | # Escreva uma função que invocará outra função na qual
# tenha dois parâmetros definidos. Invoque a primeira
# função de ``func1()`` e a segunda de ``func2()``.
# Em seguida, invoque os parâmetros da segunda função de x e y.
# Some x e y e retorne o resultado. Em func1(), ao receber
# o resultado, retorne-o também como valor de retorno da função.
# Por fim, imprima na tela o valor que foi calculado por func2(),
# retornado para func1() e retornado a quem invocou a função inicialmente:
def func1():
soma = func2(10,20)
return soma
def func2(x, y):
soma = x+y
return soma
print(func1()) | false |
091a32bacbae53d22c906952d3ccd59484282844 | absnetto/IDE-PyCharm | /Excercícios3/e (13).py | 450 | 4.1875 | 4 | # Escreva uma função que inverta a ordem dos elementos
# de uma lista manualmente. Não utilize a função interna
# do Python que faz inverção, crie o algoritmo que faça a inversão.
# Lista: "1234abcd"
# Saída: "dcba4321"
def inverte(*lista):
listainvertida = ""
tam = len(lista)
while (tam > 0):
listainvertida += lista[tam-1]
tam -= 1
return (listainvertida)
lista = tuple("1234abcd")
inverte(*lista)
| false |
3e0bfbf5f123dbbe1ced816fcb9e7c509e956d22 | jgmathias/CodingHomework | /LACCD/Fall 2018/CS 903/Project 3/Project3C.py | 546 | 4.1875 | 4 | #Name: James Mathias
#Assignment: Project 3-C
#Date: Oct 6, 2018
#Description: ask user to input 3 exam scores, then calculate and output grade
score1 = float(input("First exam score: "))
score2 = float(input("Second exam score: "))
score3 = float(input("Third exam score: "))
average = (score1 + score2 + score3) / 3
if average > 90:
Grade = "A"
elif average >= 88:
Grade = "A-"
elif average >= 80:
Grade = "B"
elif average >= 70:
Grade = "C"
elif average > 60:
Grade = "D"
else:
Grade = "F"
print "Your grade is", Grade | true |
64433fa1b27d70ed4c4ad93033ae4a6a4693e96a | xiaozefeng/python-practice-codebyte | /longest_word.py | 671 | 4.34375 | 4 | # coding: utf-8
__author__ = 'steven'
def longest_word(sen):
# first web remove non alphanumeric character from the string
# using the translate function which deletes the specified characters
# sen = sen.translate(None, "~!@#$%^&*()-_+={}[]:;'<>?/,.|`")
map = str.maketrans("~!@#$%^&*()-_+={}[]:;'<>?/,.|`", "")
sen = sen.translate(map)
# now we separate the string into alist of words
arr = sen.split(' ')
# the list max function will return the element in arr
# with the longest length because web specify key=len
return max(arr, key=len)
print('the longest wrod : %s' % longest_word('the $$$longest# word is coderbyte'))
| true |
ef6f9f0a64a3e9788c992657df6ffb9f06b2b41c | MacGuffin-Underscore/MIT6.0001-PS1 | /MIT600_ps1c.py | 2,773 | 4.625 | 5 | # -*- coding: utf-8 -*-
"""
MIT600_ps1c.py
@author: MacGuffin_
Created on Fri Jul 2 00:16:24 2021
----------------------------------------
In Part B, you had a chance to explore how both the percentage of your salary that you save each month
and your annual raise affect how long it takes you to save for a down payment. This is nice, but
suppose you want to set a particular goal, e.g. to be able to afford the down payment in three years.
How much should you save each month to achieve this? In this problem, you are going to write a
program to answer that question. To simplify things, assume:
1. Your semiannual raise is .07 (7%)
2. Your investments have an annual return of 0.04 (4%)
3. The down payment is 0.25 (25%) of the cost of the house
4. The cost of the house that you are saving for is $1M.
You are now going to try to find the best rate of savings to achieve a down payment on a $1M house in
36 months. Since hitting this exactly is a challenge, we simply want your savings to be within $100 of
the required down payment.
"""
from datetime import datetime as dt
# User Input
annual_salary = float(input("Enter starting annual salary: ",))
as_reset = annual_salary
time_start = dt.now()
# Initial Values
semi_annual_raise = 0.07
r = 0.04
total_cost = 1000000
portion_down_payment = total_cost * 0.25
months = 36 # 3 year time-span
minmax = [0, 10000] # 0% to 100% of portion saved
portion_saved = 5000 # Start at 50%
current_savings = 0
tol = 100
steps = 0
not_Possible = False
# Maths
while abs(current_savings - portion_down_payment) > tol:
# reset holding values
current_savings = 0
annual_salary = as_reset
# calculate the savings after 36 months
for m in range(1,months+1):
current_savings += current_savings*r/12 + (portion_saved*.0001)*annual_salary/12
if m % 6 == 0:
annual_salary += annual_salary * semi_annual_raise
# bisection search
if current_savings > portion_down_payment:
minmax[1] = portion_saved
else:
minmax[0] = portion_saved
portion_saved = sum(minmax) / 2
# count steps in the event of a impossible case
steps += 1
if steps > 100:
not_Possible = True
break
# Output
if not_Possible == False:
print('Best savings rate:', round(portion_saved*.01,2),'%')
print('Steps in bisection search:', steps)
else:
print('Impossible to afford the down payment in 3 years')
print("Time to run:",dt.now()-time_start)
| true |
cd756024250de8b256ee318be0033496126693f9 | HoneKedou/leetcode | /048-rotate-image/rotate-image.py | 415 | 4.15625 | 4 | # -*- coding:utf-8 -*-
# You are given an n x n 2D matrix representing an image.
# Rotate the image by 90 degrees (clockwise).
# Follow up:
# Could you do this in-place?
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
matrix[:] = zip(*matrix[::-1])
| true |
6639cfa39eac2b1945b026580c4b7985c37e09d7 | saikumaryerra/data_structures | /bubble_sort.py | 634 | 4.3125 | 4 | def bubble_sort(arr):
arr_len = len(arr)
for i in range(arr_len-1):
for j in range(arr_len-1-i):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
if __name__ == '__main__':
num = input("Enter the list of integers with space between them:\n")
input_list = num.split()
int_input_list = list()
try:
for i in input_list:
j = float(i)
int_input_list.append(j)
except ValueError:
print('only numbers allowed')
exit()
print(int_input_list)
output = bubble_sort(int_input_list)
print(output)
| false |
aac4c7d06e5a1da83fa3fe826364eb44220863ee | roshan16693/PythonPracs | /Day3_assignment_Roshan.py | 482 | 4.1875 | 4 | # Pilot Program -- Day3 assignment 1
altitude=int(input("Enter The Current Altitude"))
if altitude<=1000:
print("Safe To Land")
elif altitude>1000 and altitude<5000:
print("Bring Down To Less Than 1000ft Altitude")
else:
print("Has To Make A Turn Around")
# Prime Number Program -- Day3 assignment 2
for i in range(2,200):
is_Prime=True
for j in range(2,i):
if i%j==0:
is_Prime=False
if is_Prime:
print(i)
| true |
ec2418648a561fd7030302d96d6b6eafeafcca3c | bitratek/wilp-python | /Exer_2.py | 275 | 4.15625 | 4 | num = input('Enter the number : ')
ord = input('Enter the order : ')
bsum = 0
for digit in num:
bsum += int(digit) ** int(ord)
print(bsum)
if bsum == int(num):
print('Number ', num, 'is Armstrong Number')
else:
print('Number ', num, 'is not Armstrong Number')
| true |
a34cba949dd9b820c17a44da3df0149f0d93840c | Jeka-anik/HomeWork | /hw34/task2.py | 652 | 4.15625 | 4 | coffe7=int(input("Введи количество чашек: "))
age=int(input("Введи возраст свой, о мой юный кофеиновый заложник: "))
win=coffe7/7
if win < 1 and age < 18:
print("Ты еще не заслужил бесплатный кофе. Да и пить кофе тебе еще рано")
elif win > 1 and age < 18:
print("рано тебе так много пить")
elif win < 1 and age > 18:
print("у тебя все впереди")
else:
x=coffe7//7
print("Ты заслужил кофе, тебе положено: ",x, "чашек бодрящего напитка")
| false |
52db40fa1818ee45ca001eb6925435cf328b7494 | Saskia-vB/Programmatic_games | /fizzbuzz.py | 681 | 4.15625 | 4 |
# fizzbuzz
# if divisible by 5 and 3 = fizzbuzz
# if divisible by 5 = fizz
# if divisible by 3 = buss
def div_by_5_and_3(num):
return num % 5 == 0 and num % 3 == 0
def div_by_5(num):
return num % 5 == 0
def div_by_3(num):
return num % 3 == 0
def fizzbuzz(num):
if div_by_5_and_3(num):
print("fizzbuzz")
elif div_by_5(num):
print("fizz")
elif div_by_3(num):
print("buzz")
else:
print(num)
while True:
num = input("please enter a number: ")
if 'exit' in num:
print("ciao bella")
break
if num.isnumeric():
num = int(num)
for number in range (1, num+1):
fizzbuzz(number)
| false |
b38b63bb99647f6e1f4f99abde704e94ed06fc0c | arielbernardo/Problem-solving-Python-Programming-and-Video-Game | /quiz_week4.py | 1,513 | 4.46875 | 4 | # Programming (multi-argument function call)
# Write a Python program that asks the user to input two numbers and finds the max of those number when they are raised to the power of each other.
# Display three numbers in your answer, the first number raised to the power of the second, the second number raised to the power of the first, and then the maximum of these two computed values, each on one line.
# For example, here is a sample program run:
# Enter an integer >2
# Enter an integer >3
# 2 to the power of 3 is 8
# 3 to the power of 2 is 9
# the max of 8 and 9 is 9
num1 = int(input('Enter an integer >'))
num2 = int(input('Enter an integer >'))
pow_num1 = num1**num2
pow_num2 = num2**num1
max_num = pow_num1, pow_num2
print('{} to the power of {} is {}'.format(num1, num2, pow_num1))
print('{} to the power of {} is {}'.format(num2, num1, pow_num2))
print('the max of {} and {} is {}'.format(pow_num1, pow_num2, max(max_num)))
#Programming (method call and attribute reference)
#Write a Python program that asks the user to input a string and a sub-string and outputs the number of occurrences of the sub-string in the string.
#For example, here is a sample program run:
#Enter a string >banana
#Enter a substring >na
#the substring "na" appears 2 times in "banana"
user_input1 = input('Enter a string >')
user_input2 = input('Enter a substring >')
result = user_input1.count(user_input2)
print('the substring "{}" appears {} times in "{}"'.format(user_input2,result,user_input1))
| true |
d014638785ad2ded670d4c1453706308bab43592 | jlynnr28/OST_Python | /Python2/UnitTesting_Homework/src/test_unit.py | 767 | 4.125 | 4 | """
This program is an example of Python's unittest module.
"""
import unittest
from unittest import TestCase
def title(s):
"How close is this function to str.title()?"
return s[0].upper() + s [1:]
class TestTitle(TestCase):
"""
Class to test how close the function is to str.title().
"""
def test_one_word(self):
str_test = 'python'
self.assertEqual(title(str_test), str_test.title(), "Titles are not the same for a single word")
def test_multi_words(self):
str_test = 'multiple words to test'
self.assertEqual(title(str_test), str_test.title(), msg = "Titles are not the same for multi-words.")
if __name__ == '__main__':
unittest.main() | true |
6881ef0c6668f234c9c585e02f0c5f72a02f636e | jlynnr28/OST_Python | /Python1/refactory.py | 1,246 | 4.5 | 4 | #!/usr/local/bin/python3
'''
This code is used to demonstrate merciless refactoring.
- Justin Lynn Reid 11/10/2013
'''
small_words = ('into', 'a', 'of', 'at', 'in', 'for', 'on', 'into', 'the')
def book_title(title):
""" Takes a string and returns a title-case string.
All words EXCEPT for small words are made title case
unless the string starts with a preposition, in which
case the word is correctly capitalized.
>>> book_title('DIVE Into python')
'Dive into Python'
>>> book_title('the great gatsby')
'The Great Gatsby'
>>> book_title('the WORKS OF AleXANDer dumas')
'The Works of Alexander Dumas'
"""
title_str = ''
title_words = title.split(' ')
for i, word in enumerate(title_words):
if word.lower() not in small_words or i == 0:
if i < len(title_words) - 1:
title_str += word.title() + ' '
else:
title_str += word.title()
else:
if i < len(title_words) - 1:
title_str += word.lower() + ' '
else:
title_str += word.lower()
return title_str
def _test():
import doctest, refactory
return doctest.testmod(refactory)
if __name__ == "__main__":
_test() | true |
6cbb3a5f7c73c5a90f26cc0a9e86ed05439cdc53 | MaazMS/HackerRank | /python/introduction/print.py | 421 | 4.5625 | 5 | # The included code stub will read an integer, n , from STDIN.
# Without using any string methods, try to print the following:
# 12345....
# Note that "....." represents the consecutive values in between.
#
# Example
# n = 5
# Print the string 12345.
## Explain * operator is called unpacking. You can do it in any iterable, not just range
if __name__ == '__main__':
print( * range( 1, int( input()) + 1), sep= "" ) | true |
0647774058fddaa699499c22d81bffcc4bcbb2e3 | Phinart98/Tic-Tac-Toe | /tic_tac_toe.py | 2,196 | 4.15625 | 4 | board = ['_', '_', '_', '_', '_', '_', '_', '_', '_']
print("---------")
print(f"| {board[0]} {board[1]} {board[2]} |")
print(f"| {board[3]} {board[4]} {board[5]} |")
print(f"| {board[6]} {board[7]} {board[8]} |")
print("---------")
possible_spots = {"1 3": 0, "1 2": 3, "1 1": 6,
"2 3": 1, "2 2": 4, "2 1": 7,
"3 3": 2, "3 2": 5, "3 1": 8}
turn = 'X'
while True:
user_input = input("Enter the coordinates as pertaining to a cartesian plain: ")
coordibates = user_input.split()
if coordibates[0].isdigit() is False or coordibates[1].isdigit() is False:
print("You should enter numbers separated by a space!")
continue
elif 1 < int(coordibates[0]) > 3 or 1 < int(coordibates[1]) > 3:
print("Coordinates should be from 1 to 3!")
continue
elif board[possible_spots[user_input]] != '_':
print("This cell/coordinate is occupied! Choose another one!")
continue
else:
board[possible_spots[user_input]] = turn
if turn == 'X':
turn = 'O'
elif turn == 'O':
turn = 'X'
print('---------')
print(f'| {board[0]} {board[1]} {board[2]} |')
print(f'| {board[3]} {board[4]} {board[5]} |')
print(f'| {board[6]} {board[7]} {board[8]} |')
print('---------')
rows = []
columns = [[board[0], board[3], board[6]], [board[1], board[4], board[7]], [board[2], board[5], board[8]]]
backslash_pattern = [[board[0], board[4], board[8]]]
forward_slash_pattern = [[board[2], board[4], board[6]]]
O_wins = ['O', 'O', 'O']
X_wins = ['X', 'X', 'X']
single_row = []
for letter in board:
single_row.append(letter)
if len(single_row) == 3:
rows.append(single_row)
single_row = []
total = rows + columns + backslash_pattern + forward_slash_pattern
O_true = O_wins in total
X_true = X_wins in total
if O_true and X_true or abs(board.count('O') - board.count('X')) >= 2:
print('Impossible')
break
elif O_true:
print('O wins')
break
elif X_true:
print('X wins')
break
elif board.count('_') == 0:
print('Draw')
break
| true |
0d2418be0412561975d19fa79bf3ff3ba3708602 | argelalan/password-generator | /passphrases.py | 2,466 | 4.21875 | 4 | from random_word import RandomWords
import random
def limit_length():
"""
Return a word limit as an integer if it's a number over 0 and below
51, and the user doesn't want to quit.
"""
while True:
word_limit = input('Enter number of words in passphrase'
'\n(Limit is 50 words): ')
valid_limit = list(range(1, 51))
valid_limit = str(valid_limit)
if word_limit in valid_limit:
word_limit = int(word_limit)
return word_limit
elif word_limit == 'q':
break
else:
print('*** Invalid syntax ***')
def get_word_spacer(word_limit):
"""
Return a word spacer as long as the word limit exists and the user
doesn't want to quit.
"""
while word_limit:
spacer = input('Enter a symbol to separate the words in your passphrase'
'\n(Hit space bar and enter for no symbols): ')
if spacer == 'q':
word_limit = False
else:
return spacer
def get_word_case(spacer, limit):
"""
Generate a list of random words.
Generate a random combination of a preferred number of those words.
Join that combination with a preferred word spacer.
Finally, print the result as a passphrase in a preferred word case
as long as the word spacer exists, the user chooses a valid word
case option, and the user doesn't want to quit.
"""
while spacer:
rw = RandomWords()
words = rw.get_random_words()
random_combination = random.sample(words, limit)
passphrase = spacer.join(random_combination)
case = input('1. Upper\n2. Lower\n3. Title'
'\nEnter a number for a case: ')
if case == '1':
print(f'\nPassphrase: \n{passphrase.upper()}')
break
elif case == '2':
print(f'\nPassphrase: \n{passphrase}')
break
elif case == '3':
print(f'\nPassphrase: \n{passphrase.title()}')
break
elif case == 'q':
break
else:
print('*** Invalid syntax ***')
def generate_passphrase():
"""
Generate a passphrase formed of randomized
words with a word limit, a word spacer to
separate the words, and a preferred word case.
"""
length = limit_length()
word_spacer = get_word_spacer(length)
get_word_case(word_spacer, length)
| true |
671ff4e9ab30bf7c5aaa4330530e95dd2a0932fa | MLKODER/python_projects | /snake.py | 1,020 | 4.40625 | 4 | from tkinter import *
root = Tk() #initialises the tkinter screen
root.configure(background='black') #sets the properties of the window
root.geometry('800x800') #this specifies the window size
root.title("Welcome to the world of tkinter") #sets the title of the screen
#Label(root, text="Hello").grid(column=2 , row=3)
#This is used to insert text inside the window of the tkinter
label1=Label(root,text="Hello world")
label1.grid(row=3,column=2)
label2=Label(root,text="Hello world",font=("Ubuntu Bold" , 72))
label2.grid(row=4,column=2)
label3=Label(root,text="Hello world",font=("Ubuntu" , 72))
label3.grid(row=5,column=2)
def click():
btn.configure( text="clicked", bg="red")
btn = Button(root, text="I am a button", width= 20 , font =("Ubuntu" , 10), command = click)
btn.grid(row=6 , column=2)
btn2 = Button(root, text="I am a button", width= 20 , font =("Ubuntu" , 10) ,fg="blue",bg="yellow")
btn2.grid(row=7 , column=2)
text = Entry(root , width = 20)
text.grid(row=8, column=2)
root.mainloop() | true |
fac927483875fe118e7454fdcd505706fff01e88 | Abner-Zgx/PythonLearning | /3-listAndTuple.py | 607 | 4.125 | 4 | # Python 3
# List:列表
a = [1,2,3,4,5,6]
print(type(a))
print(a)
print(a[0])
print(a[1:3])
# 替换
a[0] = 0
print(a)
# 插入
a.append(7)
print(a)
# 删除
del a[1]
print(a)
# 删除
a.remove(3)
print(a)
# 长度
b = len(a)
print(b)
# 加法
c = a + [9,9]
print(c)
# 乘法(复制列表n次)
d = a * 3
print(d)
# 列表推导式
g = [1,2]
h = "hello world"
j = [i for i in h]
print(j)
# Tuple:元组
e = (1)
f = (1,) # 注意要加逗号,否则不是元祖
print(type(e))
print(type(f))
print(f[0])
print(len(f))
# 其他申明方式
x = list()
print(type(x))
y = tuple()
print(type(y)) | false |
4deb1681db5d7d0068da7b7462b4652fe7890a05 | Kooperatorko/programming_py | /block-1/calculator.py | 578 | 4.1875 | 4 | print ('Введите x: ', end='')
x = float(input())
print('Введите y: ', end='')
y = float(input())
print('Введите операцию (+, -, *, /, **): ', end='')
oper = input()
if (oper == '+'):
print('x + y = ', x+y)
elif (oper == '-'):
print('x - y = ', x-y)
elif (oper == '*'):
print('x * y = ', x*y)
elif (oper == "/"):
if (y == 0):
print('Sorry, на 0 нельзя')
else:
print('x / y = ', x/y)
elif (oper == '**'):
print('x**y = ', x**y)
else:
print('Неверная операция')
| false |
4c69c6fb47ce9fc51d7d035de01d362be7375547 | Kooperatorko/programming_py | /block-1/disckriminant.py | 628 | 4.25 | 4 | from math import sqrt
print('Введите x: ', end='')
x = float(input())
print('Введите y: ', end='')
y = float(input())
print('Введите z: ', end='')
z = float(input())
def func(x, y, z):
D = y*y - 4*x*z
if D < 0:
print('Корней нет')
elif D == 0:
print('У уравнения единсвенный корень = ',round(((-y)/(2*x)), 3)
else:
print('У уравнения два корня:\nПервый корень = ', round((((-y)+sqrt(D))/(2*x)), 3), '\nВторой корень = ', round(((-y)-sqrt(D))/(2*x)), 3)
func(x, y, z)
| false |
7b11d9eddc4a726c7b07b23150b04b143e9c98e6 | surendhar-code/Python-Programs | /Basic Programs/interchange_frst_lst_ele_in_list.py | 905 | 4.15625 | 4 | #getting input from the user
lst_1=[]
n=int(input("Enter the no. of list elements : "))
for i in range(0,n):
ele=int(input())
lst_1.append(ele)
print("List before interchanging : ",lst_1)
#interchanging using swap condition
temp=lst_1[0]
lst_1[0]=lst_1[n-1]
lst_1[n-1]=temp
print("List after interchanging : ",lst_1)
#using list indexing
lst_2=[]
n=int(input("Enter the no. of list elements : "))
for i in range(0,n):
ele=int(input())
lst_2.append(ele)
print("List before interchanging : ",lst_2)
lst_2[0],lst_2[-1]=lst_2[-1],lst_2[0]
print("List interchanging using list indexing : ",lst_2)
#using tuple variable get
lst_3=[]
n=int(input("Enter the no. of list elements : "))
for i in range(0,n):
ele=int(input())
lst_3.append(ele)
print("List before interchanging : ",lst_3)
get = lst_3[-1],lst_3[0]
lst_3[0],lst_3[-1]=get
print("List interchanging tuple variable get ",lst_3)
| false |
d67a83b6d57e41b37c000d87ed61a60769279dcb | surendhar-code/Python-Programs | /Functions/upper_lower_count_in_str.py | 447 | 4.25 | 4 | '''
Develop a Python program to calculate the number of upper case letters
and lower case letters in a string.
'''
def upper_lower(string):
lower =0
upper=0
for i in string:
if i.islower():
lower+=1
elif i.isupper():
upper+=1
print("Uppercase count : ",upper)
print("Lowercase count : ",lower)
s =input("Enter the string : ")
upper_lower(s)
| true |
b1393c71b339136c166072caa203c390c6732df4 | surendhar-code/Python-Programs | /Functions/largest_digit_from_the_no.py | 335 | 4.4375 | 4 | # Develop a python program to find the largest digit from the number using functions
def largest(n):
large=0
while n>0:
rem=n%10
if rem>large:
large=rem
n=n//10
return large
n = int(input("Enter the number : "))
print("The largest digit from the number is : ",largest(n)) | true |
e8d4019ed943bb605b7dda90a7ccf82c9d1e8bdf | surendhar-code/Python-Programs | /List/greatest_num_in_a_list.py | 398 | 4.375 | 4 | '''
Develop a Python program to find the greatest of ’N’ numbers stored in a
list and print the result.
'''
# Method - 1 using max() function
lst = [10,20,30,40,50]
print("The greatest element in a list is ",max(lst))
# Method 2 using temp variable
lst = [10,20,30,40,50]
large =0
for i in lst:
if i>large:
large=i
print("The greatest element in a list is ",large)
| true |
28182711d0872898e90950ed97033b5a2c260912 | surendhar-code/Python-Programs | /Basic Programs/find_xn_while.py | 225 | 4.4375 | 4 | # Develop a python program to find the value of x power n using while statement
x = int(input("Enter the x value : "))
n = int(input("Enter the n value : "))
s=1
i=1
while i<=n:
s*=x
i=i+1
print("The result is : ",s) | true |
fff997d6d76e406a71befd54bf11b4c76464834f | surendhar-code/Python-Programs | /DataStructures Basics/stack.py | 1,053 | 4.40625 | 4 | # Basic Python program to dispaly all the operations of the stack
def create_stack():
stack = []
return stack
def isEmpty(stack):
if len(stack) == 0:
return True
else:
return False
def push(stack,ele):
stack.append(ele)
print("{0} - element pushed onto the stack".format(ele))
def pop(stack):
if (isEmpty(stack)):
print("The stack is underflow")
else:
print("Element {0} poped from the stack".format(stack.pop()))
def peek(stack):
if (isEmpty(stack)):
print("The stack is underflow")
else:
print("The peek element of the stack is : ", stack[len(stack)-1])
def display_stack(stack):
if (isEmpty(stack)):
print("The stack is underflow")
else:
print("The elements of the stack are : ",stack[::-1])
stack = create_stack()
push(stack,str(10))
push(stack,str(20))
push(stack,str(30))
push(stack,str(40))
push(stack,str(50))
pop(stack)
display_stack(stack)
pop(stack)
display_stack(stack)
pop(stack)
display_stack(stack)
peek(stack)
| true |
f2d6ca736ad7de2cb9bd88e66fb90e6ea61bc8c5 | surendhar-code/Python-Programs | /Functions/letters_in_two_strings.py | 404 | 4.28125 | 4 | '''
Develop a Python program to using Generator function to print all the letters from
word1 that also appear in word2.
'''
def str_both(str1,str2):
for i in str1:
if i in str2:
yield i
str1 = input("Enter the string1 : ")
str2 = input("Enter the string2 : ")
letter_in_both = str_both(str1,str2)
for s in letter_in_both:
print(s)
| false |
7f7d2b54b3ad12cb1a8c03cd4eea453adc803533 | surendhar-code/Python-Programs | /Functions/reverse_the_digits.py | 294 | 4.375 | 4 | # Develop a python to reverse the digits of the given number using function
def reverse(n):
rev=0
while n>0:
rem=n%10
rev=rem+(rev*10)
n=n//10
return rev
n = int(input("Enter the number : "))
print("The reverse of the number is : ",reverse(n)) | true |
67f1a24209f8922bfdff26123ed8b2d9434282da | surendhar-code/Python-Programs | /Basic Programs/addition_table.py | 217 | 4.21875 | 4 | # Develop a python program to print addition table of the given number using for statement
t = int(input("Enter the table : "))
n = int(input("Enter the limit"))
for i in range(1,n+1):
print(i," + ",t," = ",i+t)
| true |
e7ffa3daa5978486f0127872c670bcee7547a914 | surendhar-code/Python-Programs | /Basic Programs/avg_of_frst_n_natural_num.py | 256 | 4.3125 | 4 | # Develop a python program to find the avearge of first n natural numbers without using the formula using for statement.
n = int(input("Enter the limit value : "))
s=0
for i in range(1,n+1):
s=s+i
print("The average of first n natural numbers : ",s/n) | true |
fa3cb370ca8f6670a574c8b411a23a473dd342d3 | GrisoFandango/week-10 | /Vehicles class input.py | 829 | 4.15625 | 4 | #creating a class
class Vehicle():
#initialize the class with parameters
def __init__(self, name, color, brand, engineSize):
self.name = name
self.color = color
self.brand = brand
self.engineSize = engineSize
#creating a method to show the parameters values
def showDetails(self):
print(self.name,self.color,self.brand, self.engineSize)
#Create a loop that ask the user to inpunt the different
#parameter and then create the object with that parameter
#and print out the values
for i in range(1,5):
name = input ("Enter name of vehicle: ")
color = input ("Enter color of vehicle: ")
brand = input ("Enter brand of vehicle: ")
engineSize = input ("Enter the size of the engine: ")
i = Vehicle (name, color, brand, engineSize)
i.showDetails()
| true |
01ea3819c5686b8b6cb57cf1551b48d769b002b6 | swilliams9671/python-data-structures | /file_recursion.py | 1,755 | 4.5 | 4 | import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
if suffix == "":
print("No suffix to search for.")
return
if path == "":
print("No path provided.")
return
if os.path.isdir(path):
#print("This is: {}".format(path))
for item in os.listdir(path):
find_files(suffix, os.path.join(path, item))
if os.path.isfile(path):
#print("This is: {}".format(path))
if suffix in os.path.basename(path):
#print("Found: {}".format(os.path.basename(path)))
files_found.append(path)
if __name__ == "__main__":
files_found = []
# Test case 1 - you will need to change the file path but it is the test directory provided by the course
find_files(".c","/Users/stevenwilliams/Desktop/python_stuff/P1/testdir")
print(files_found)
# Test case 2
find_files(".c", "")
# Test case 3
find_files("", "/Users/stevenwilliams/Desktop/python_stuff/P1/testdir")
'''
Expected output:
['/Users/stevenwilliams/Desktop/python_stuff/P1/testdir/subdir3/subsubdir1/b.c', '/Users/stevenwilliams/Desktop/python_stuff/P1/testdir/t1.c', '/Users/stevenwilliams/Desktop/python_stuff/P1/testdir/subdir5/a.c', '/Users/stevenwilliams/Desktop/python_stuff/P1/testdir/subdir1/a.c']
No path provided.
No suffix to search for.
'''
| true |
0a01ce10ad162c83c14586013cdb755182da2b78 | smartvkodi/learn-python | /5-Python_Pattern_Programs/72-To_print_square_pattern_with_alphabet_symbols.py | 586 | 4.28125 | 4 | # 72 - To print square pattern with alphabet symbols
msg = '72 - To print square pattern with alphabet symbols'
tn = ' '*5
text = '#'+ tn + msg + tn + '#'
i = len(text)
print('#'*i)
print(text)
print('#'*i)
print('\n')
print('''1. Example-1.
# To print square pattern with alphabet symbols
n=int(input('Enter n value: '))
for i in range(n):
print((chr(65+i)+' ')*n)
''')
n=int(input('Enter n value: '))
for i in range(n):
print((chr(65+i)+' ')*n)
print('\n\n')
for i in range(n):
if i==0 or i==n-1 :
print((chr(65+i)+' ')*n)
else:
print(chr(65+i) + ' '*(2*n-3) + chr(65+i)) | false |
41d53ece978a915c47129b0f19abb0e93362f972 | smartvkodi/learn-python | /4-Python_Flow_Control_Part-1/65-Iterative_Statements_for-loop.py | 1,215 | 4.125 | 4 | # 65 - Iterative Statements: for loop
msg = '65 - Iterative Statements: for loop'
tn = ' '*5
text = '#'+ tn + msg + tn + '#'
i = len(text)
print('#'*i)
print(text)
print('#'*i)
print('\n')
print('''Iterative Statements:
1. for-loop
2. while-loop''')
print('''1. for-loop
applicabile for collections and string
python syntax:
for x in sequence:
Activity-1
s='Sunny Leone' # I want to print every character present in this string
for x in s:
print(x)
''')
s='Sunny Leone' # I want to print every character present in this string
for x in s:
print(x)
print('''\n## I want to print the character present at specified index
s='Sunny Leone'
i=0
for x in s:
print('The character present at {} index: {}'.format(i, x))
i=i+1 ## or i+=1
''')
s='Sunny Leone'
i=0
for x in s:
print('The character present at {} index: {}'.format(i, x))
i=i+1 ## or i+=1
print('''\n## I want to get the string dynamically from keyboard
and then to print the character present at specified index
s=input('Enter any string:')
i=0
for x in s:
print('The character present at {} index: {}'.format(i, x))
i=i+1 ## or i+=1
''')
s=input('Enter any string:')
i=0
for x in s:
print('The character present at {} index: {}'.format(i, x))
i=i+1 ## or i+=1
| false |
2f4f66d573439aa0098cb1d15c65d89bc757ad6f | smartvkodi/learn-python | /2-Python_Operators/48-Important_Functions_and_Variables_of_math_Module.py | 1,132 | 4.375 | 4 | # 48 - Important Functions and Variables of math Module
import math
# you can import the module as alias
# once we define alias name we can not use original name
# if we do not want to use module name
# we can use the functions from module directly
# from math import sqrtr, pi OR import all
from math import *
print('\n')
msg = '48 - Important Functions and Variables of math Module'
tn = ' '*5
text = '#'+ tn + msg + tn + '#'
i = len(text)
print('#'*i)
print(text)
print('#'*i)
print('\n')
print('''Important Functions and Variables of math Module
- sqrt(x) - pi
- floor(x) - e
- ceil(x) - inf
- pow(x,y) - nan
- gcd(x,y) .....
- sin(x)
- cos(x)
... ''')
# it is possible create alias only for an function
from math import sqrt as radical
print('radical(16) =', radical(16))
print('''\n#Example: Find circle area for the given radius''')
r = int(input('Enter circle radius:'))
area1 = pi*r**2
area2 = pi*pow(r,2)
print('The circle area: ', area1)
print('The circle area: ', area2)
print('\n',dir(math))
print('\n#Examples:')
print('sqrt(16) = ', math.sqrt(16))
print('pi = ', math.pi)
print('e = ', math.e)
| true |
21fc4064ad2c5bfc27e4e1d341cd3819a8ee6dc3 | smartvkodi/learn-python | /3-Input_and_Output_Statements/51-Reading_Multiple_Values_from_the_keyboard_in_a_single_line.py | 1,152 | 4.3125 | 4 | # 51 - Reading Multiple Values from the keyboard in a single line
msg = '51 - Reading Multiple Values from the keyboard in a single line'
tn = ' '*5
text = '#'+ tn + msg + tn + '#'
i = len(text)
print('#'*i)
print(text)
print('#'*i)
print('\n')
print('''1. How to read multiple values from the keyboard in a single line:''')
print('''#List Comprehension Concept: [int(x) for x in input('Enter 2 Numbers:').split())]''')
print('''#List Unpacking Concept: a,b = [int(x) for x in input('Enter 2 Numbers:').split()]''')
print('')
a,b = [ int(x) for x in input('Enter 2 Numbers:').split() ]
print('The Sum:', a+b)
print('\nExplaining...')
print("#s = input('Enter 2 Numbers:')")
s = input('Enter 2 Numbers:')
print('s =', s, type(s))
print('\nl = s.split() => split() returns a list')
l = s.split()
print('l=', l)
print('\n## List Comprehension Concept')
print('l1 = [int(x) for x in l] ## for each x in list l perform type cast into int type')
l1 = [int(x) for x in l] ## for each x in list l perform type cast into int type
print('l1=',l1)
print('\n## List Unpacking Concept')
print('a,b = l1')
a,b = l1
print('a=', a, 'b=',b)
print('The sum:', a+b)
| false |
7535170599b802e7e3d0fed5aa9841ec38f9b70a | smartvkodi/learn-python | /3-Input_and_Output_Statements/60-Output_Statements_print_with_formatted_string.py | 1,539 | 4.375 | 4 | # 60 - Output Statements : print() with formatted string
msg = '60 - Output Statements : print() with formatted string'
tn = ' '*5
text = '#'+ tn + msg + tn + '#'
i = len(text)
print('#'*i)
print(text)
print('#'*i)
print('\n')
print('''Output Statements print() with formatted string:
# %i --> signed decimal value
# %d --> signed decimal value
# %f --> floating point value
# %s --> string, any other objects like list, set, etc...''')
print('\n#Example-1')
print('''a=10
print('a value: %i' %a)
print('formatted_string' %(variable_list))
# output''')
a=10
print('a value: %i' %a)
print('\n#Example-2')
print('''a=10
b=20
c=30
print('a=%d, b=%f, c=%d' %(a,b,c))
# output''')
a=10
b=20
c=30
print('a=%d, b=%f, c=%d' %(a,b,c))
print('\n#Example-3')
print('''name='Durga'
marks=[10,20,30,40]
name is str, marks is list then the specified format required is %s
print('Hello %s, your marks list: %s' %(name, marks))
# output''')
name='Durga'
marks=[10,20,30,40]
print('Hello %s, your marks list: %s' %(name, marks))
print('\n#Formatted string is more powerfull than replacement operator {}')
print('''price = 70.56789
print('Price value={}'.format(price))
print('Price value=%f' %price)
# output''')
price = 70.56789
print('Price value={}'.format(price)) # with replacement operator
print('Price value=%f' %price) # with formated string
print('''\n#the biggest advantage using formatted string is when
I do not want displaying all decimals but only 2 decimals
print('Price value=%.2f' %price)''')
print('Price value=%.2f' %price)
| true |
5e911aadcf2c57793efc14679576646c4a677b58 | smartvkodi/learn-python | /1-Language_Fundamentals/18-float-complex-TypeCasting.py | 2,657 | 4.1875 | 4 | # 18 - float() and complex() Type Casting
print('\n')
msg = 'float() and complex() Type Casting or Type Coersion'
tn = ' '*5
text = '#'+ tn + msg + tn + '#'
i = len(text)
print('#'*i)
print(text)
print('#'*i)
print('\n1. float() - to convert from other types to float type')
print('\n1.a. convert from int to float type')
print('float(10) =>',float(10))
print('float(0B1111) =>',float(0B1111))
print('float(0XFace) =>',float(0XFace))
print('\n1.b. convert from complex to float type')
c = 10 + 20j
# f = float(c)
print('float(10 + 20j) => TypeError: can\'t convert complex to float')
print('\n1.c. convert from bool to float type')
b = True
f = float(b)
print('int(True) =>',float(True))
b = False
f = float(b)
print('int(False) =>',float(False))
print('\n1.d. convert from str to float')
print('''String internaly should contains either
integral value in base-10 or float value\n''')
f = float('10')
print('float(\'10\') =>',f)
f = float('20.7')
print('float(\'20.7\') =>',f)
f = float('2.867E3')
print('float(\'20.7E3\') =>',f)
print('\nErrors:')
#f = float('0XBeef')
print('- float(\'0XBeef\') => ValueError: could not convert string to float: \'0XBeef\'')
#f = float('durga')
print('- float(\'durga\') => ValueError: could not convert string to float: \'durga\'')
print('\n\n\n2. complex() - to convert from other types to complex type')
print('\nForm 1 - complex(x)')
print('complex(10) =>',complex(10))
print('complex(0B1111) =>',complex(0B1111))
print('complex(10.7) =>',complex(10.7))
print('complex(True) =>',complex(True))
print('complex(False) =>',complex(False))
print('\n! convert from str to complex')
print('''String internaly should contains either
integral value in base-10 or float value''')
print(' - complex(\'10\') =>',complex('10'))
print(' - complex(\'10.5\') =>',complex('2.5'))
print(' - complex(\'1.333777e3\') => ', complex('1.333777e3'))
print(' - complex(\'0B1111\') => ValueError: complex() arg is a malformed string')
print('\nForm 2 - complex(x,y)')
print('complex(10,20) =>',complex(10,20))
print('complex(0B1111, 0xF) =>',complex(0B1111,0xF))
print('complex(10.7, 20.6) =>',complex(10.7,20.6) )
print(' - complex(\'10\', \'20\') => TypeError: complex() can\'t take second arg if first is a string')
print(' - complex(\'10\', 20) => TypeError: complex() can\'t take second arg if first is a string')
print(' - complex(10.5, \'2\') => TypeError: complex() second arg can\'t be a string')
print('complex(False, False) =>',complex(False, False))
print('complex(False, True) =>',complex(False, True))
print('complex(True, False) =>',complex(True, False))
print('complex(True, True) =>',complex(True, True)) | false |
6865fea99f99f052b51909ea183617c58b069900 | smartvkodi/learn-python | /3-Input_and_Output_Statements/50-Demo_Program_to_Read_input_data_from_the_keyboard.py | 1,916 | 4.125 | 4 | # 50 - Demo Program-1 to Read input data from the keyboard
msg = '50 - Demo Program to Read input data from the keyboard'
tn = ' '*5
text = '#'+ tn + msg + tn + '#'
i = len(text)
print('#'*i)
print(text)
print('#'*i)
print('\n')
print('''\n1. Write a short program to read 2 int values from keyboard and then print the sum
# compulsory we require performing data-type casting because input() returns str''')
print("\nx = int(input('Enter First Number:'))")
x = int(input('Enter First Number:'))
print("\ny = int(input('Enter Second Number:'))")
y = int(input('Enter Second Number:'))
print('\nThe sum:', x, '+', y, '=', x+y)
print('''\n# not recomanded
print('The sum:', int(input('Enter First Number:') + int(input('Enter Second Number:'))''')
print('''\n\n2. Write a short program to read the employee data
from keyboard and then print that data\n''')
print("\n eno = int(input('Enter Employee Number:'))")
eno = int(input('Enter Employee Number:'))
# data-type casting is not required
print("\n ename = input('Enter Employee Name:')")
ename = input('Enter Employee Name:')
print("\n esal = float(input('Enter Employee Salary:'))")
esal = float(input('Enter Employee Salary:'))
# data-type casting is not required
print("\n eaddr = input('Enter Employee Address:')")
eaddr = input('Enter Employee Address:')
print('''\n!! married = bool(input('Is Employee Married? [True|False]:'))
it is always true because only bool('') returns False
if bool('not empty') returns True
married = bool('False')''')
married = bool('False')
print('married:', married)
print("\n married = eval(input('Is Employee Married? [True|False]:'))")
married = eval(input('Is Employee Married? [True|False]:'))
print('\nPlease, confirm your provided information')
print('Emplyee Number:', eno)
print('Employee Name:', ename)
print('Employee Salary:', esal)
print('Employee Address:', eaddr)
print('Employee Married:', married)
| false |
8273b5d73c160825a955ec8174ff525fcb8cc76f | TengKimhan/Basic_Python_Programming | /Exercise/read_write_file.py | 2,529 | 4.1875 | 4 | # 1. poem.txt contains famous poem "Road not taken" by poet Robert Frost.
# You have to read this file in your python program and find out words with maximum occurance.
import re
word_value = {}
with open("poem.txt", "r") as f:
i = 0
for line in f:
word_split = re.split(pattern=" |[.,:—!:;]", string=line.strip()) # strip() new line
i+=1
print("line", i)
print("Before strip:", line)
print("After strip:", line.strip()) # strip() newline character
print("Before remove empty string:", word_split)
# remove empty string after split word
while "" in word_split:
word_split.remove("")
print("After remove empty string:", word_split)
# add word and its occurance into dictionary
for word in word_split:
if word in word_value:
word_value[word] += 1
else:
word_value[word] = 1
# print key value pair of the dictionary
for key, val in word_value.items():
print(f"{key} {val}")
print("Max value:", max(list(word_value.values())))
max = max(list(word_value.values())) # maximum value of occurance word
for key, value in word_value.items():
if value == max:
print(f"Max key and value: {key} {value}")
# 2. stocks.csv contains stock price, earnings per share and book value.
# You are writing a stock market application that will process this file
# and create a new file with financial metrics such as pe ratio and price to book ratio.
# These are calculated as,
# pe ratio = price / earnings per share
# price to book ratio = price / book value
import csv
dic = {} # key "Company Name", "PE Ratio", "PB Ratio"
with open("stocks.csv", "r") as f:
with open("output.csv", "w", newline="") as o:
fieldName = ["Company Name", "PE Ratio", "PB Ratio"]
writer = csv.DictWriter(o, fieldnames=fieldName) # user DictWrite() to write csv file with dictionary
writer.writeheader() # include header with fieldname that already included
for row in csv.DictReader(f): # DictReader() to read dictionary
pe_ratio = int(row["Price"]) / int(row["Earnings Per Share"])
price_to_book_ratio = int(row["Price"]) / int(row[" Book Value"])
company_name = row["Company Name"]
dic["Company Name"] = company_name
dic["PE Ratio"] = round(pe_ratio, 2)
dic["PB Ratio"] = round(price_to_book_ratio, 2)
writer.writerow(dic) # write to each row
| true |
cf28b5946ac4d2b242cc8fe23cf1ac1289085a21 | rashidkhalid1212/Blend_with_python | /Day4/Jatin Tanwar/day4_jatin.py | 833 | 4.1875 | 4 | """
we need to create a calculator with basic mathematical operations
the calculator should perform multiplicaton , addition , division and subtraction
we also need to give the user the choice to make the four of these functions
"""
print("Hi!, welcome to basic calculator")
#input
a = float(input("Enter The First Number"))
b = float(input("Enter The Second Number"))
#operations
ad = a + b
m = a*b
d = a/b
s = a-b
#operations input
i = int(input("input the operation you want type 1 to add , type 2 to multiply , type 3 to subtract , type 4 to divide "))
print("------" * 25)
print("**" * 40)
print( "this is your desired result " )
#result
if i == 1 :
print(ad)
elif i == 2 :
print(m)
elif i== 3 :
print(s)
elif i== 4:
print(d)
else :
print("please input the correct operation number ")
| true |
76b1cf5940a330f299cfa5d5cf3608306e43bc7b | spvignesh/Python | /2.Scripts/103.String.py | 1,633 | 4.21875 | 4 | #Accessing Values in Strings
var1 = "Hello World"
var2 = "Python Development"
print("Access values in string")
print("var1[0]:",var1[0])
print("var2[1:5]:",var2[1:5])
print("---------------")
print('\n')
#Concat
x = "Hello World!"
print( "Concat string")
print( x[:6] )
print( x[0:6] + "User")
print("---------------")
print('\n')
#Python String replace() Method
oldstring = 'I like Python'
newstring = oldstring.replace('like', 'love')
print( "replace()")
print( oldstring )
print( newstring)
oldstring = 'I like Python'
oldstring.replace('like', 'love')
print( oldstring )
print("---------------")
print('\n')
#Changing upper and lower case strings
print( "Working with cases")
string="python"
print( string.upper())
string="python"
print( string.capitalize())
string="PYTHON"
print( string.lower())
print("---------------")
print('\n')
#Using "join" function for the string
print( "Working with join")
print(":".join("Python"))
print("---------------")
print('\n')
#Reversing String
print( "Working with reversed")
string="Python"
print(''.join(reversed(string)))
print("---------------")
print('\n')
#Split Strings
print( "Working with split")
word="Python Development"
print( word.split(' '))
word="Python Development"
print( word.split('o'))
print("---------------")
print('\n')
#Double the word
print ("Working with double the word")
x="Python Developer"
print(x*2)
print("---------------")
print('\n')
#Cast To string
print( "String cast")
x=100
print("Python is "+str(x))
print("---------------")
print('\n')
#string format
print ("String format")
name = "Python"
number = 99
print("%s %d" % (name,number))
| true |
7a740dae15ee565f9793b83485a929269f20b0a4 | tommylim000/Learn-to-program-with-Python-guide | /04 - Drawing canvas, timers/timers-blinking_text.py | 1,257 | 4.1875 | 4 | # Timers
# Blinking Text
# In this program, the user's text blinks every time
# the timer handler is called. Try changing the timer frequency
# to see what happens. Notice that if the text is too
# long not all of it will be shown. For an added challenge,
# can you come up with a way to solve that issue?
import simplegui
# Global Variables
canvas_width = 600
canvas_height = 100
message = 'Burger Bar!'
displayed = True
timer_interval = 1000 # In milliseconds (1000 ms = 1 s)
# Event Handlers
def input_handler(text):
global message
message = text
# Switches whether or not the text is visible
# Note that it does not have any parameters
def timer_handler():
global displayed
displayed = not displayed
def draw(canvas):
if displayed:
canvas.draw_text(message, [10, 65], 30, 'Aqua')
# Frame
frame = simplegui.create_frame('Blinking Text', canvas_width, canvas_height)
# Register Event Handlers
frame.set_draw_handler(draw)
frame.add_input('Your message:', input_handler, 100)
# Creates a timer. Check the docs for more details.
timer = simplegui.create_timer(timer_interval, timer_handler)
# Remember to start the timer as well as the frame
frame.start()
timer.start() | true |
6bab34b4164cd564af2e60757287d4b6422dd944 | tommylim000/Learn-to-program-with-Python-guide | /01 - Expressions, variables and assignments/arithmetic_expressions-floats_and_ints.py | 1,313 | 4.53125 | 5 | # Arithmetic expressions - numbers, operators, expressions
# Floats and Integers
# Integers are whole numbers, while floats can be whole
# numbers or have fractional parts.
print "Integers:", 5, 19, -2, 37
print "Floats:", -3.4, 5.0, 9.99999, 1.0/3.0
print
# Float to Integer (int): truncates the decimal (leaves it off)
print "Ex. 1:", int(3)
print "Ex. 2:", int(7.4)
print "Ex. 3:", int(1.9)
print "Ex. 4:", int(-1.2)
print "Ex. 5:", int(-2.9)
print
# Integer to float: doesn't change anything
print "Ex. 6:", float(9)
print "Ex. 7:", float(-2)
print "--------"
# Python and CodeSkulptor cannot keep track of an infinite
# number of decimal places.
print "Ex. 8:", 0.12345678901234567890
print "--------"
# Operations using floats and ints are not exact in python,
# which leads to some interesting outputs
# These have different final digits and a different number
# of digits as well
print "Ex. 9: ", 4.0 / 3.0
print "Ex. 10:", 25.0 / 3.0
print
print "Ex. 11:", 1.0 / 6.0
print "Ex. 12:", 13.0 / 6.0
print "Ex. 13:", 601.0 / 6.0
print
# In these ones, the output changes based on the grouping
# of terms, even though they appear mathematically equivalent
print "Ex. 14:", 5 * 4 / 3
print "Ex. 15:", 5 * (4 / 3)
print "Ex. 16:", 20 / 3
| true |
3d6de32e4c8f0fa671d5852cd9040a691e5f923a | tommylim000/Learn-to-program-with-Python-guide | /Understanding errors/TypeError-cannot-concatenate-str-and-int-objects-or-any-other-data-type.py | 497 | 4.28125 | 4 | #--------------------Type Errors -------------------#
################### Example 1 ########################
#TypeError: cannot concatenate 'str' and 'int' objects
#Cause: trying to do operations on two things that
#don't allow it
my_string = "Hello!"
my_number = 5
my_string + my_number
#It doesn't make sense to try and add an integer to
#a string, so this error pops up. To fix it, make sure that
#everything in the equation can be used with your operator
#of choice
| true |
116d06cbd6bdea4925fc14704a38af2e3473ac30 | tommylim000/Learn-to-program-with-Python-guide | /02 - Functions, logic and conditionals/tips1.py | 2,157 | 4.3125 | 4 | ############
# This is a compilation of the examples from Week 1's Programming Tips.
# Some functions have been renamed like "function1", "function2", etc.
# in order to have multiple versions of the same function within one file.
############
import math
############
# Has a NameError
def volume_cube(side):
return sidde ** 3
s = 2
print "Volume of cube with side", s, "is", volume_cube(s), "."
############
# Has a NameError
def volume_rect_prism(length, width, height):
return length * width * height
l = 3
w = 1
h = 4
print "Volume of rectangular prism", l, w, h, "is", volumerectprism(r), "."
############
# Has a NameError
def random_dice():
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
return die1 + die2
print "Sum of two random dice, rolled once:", random_dice()
print "Sum of two random dice, rolled again:", random_dice()
############
# Has an AttributeError
def volume_sphere(radius):
return 4.0/3.0 * math.Pi * (radius ** 3)
r = 2
print "Volume of sphere of radius", r, "is", volume_sphere(r), "."
############
# Has a TypeError
def area_triangle(base,height):
return 1.0/2.0 * base * height
b = 5
h = 4
print "Area of triangle with base", b, "and height", h, "is", area_triangle(b), "."
############
# Has a SyntaxError
def identity(x)
return x
print identity(5)
############
# Has a SyntaxError
def is_mary(x):
if x = "Mary":
print "Found Mary!"
else:
print "No Mary."
is_mary("Mary")
is_mary("Fred")
############
# Poor readability
def areatri(a, b, c):
s = (a + b + c) / 2.0
return math.sqrt(s * (s-a) * (s-b) * (s-c))
############
# Improved readability
def area_triangle_sss(side1, side2, side3):
"""Returns the area of a triangle, given the lengths of its three sides."""
# Use Heron's formula
s = (side1 + side2 + side3)/2.0
return math.sqrt(s * (s-side1) * (s-side2) * (s-side3))
base=3
height=4
hyp=5
print "Area of triangle with sides", base, height, hyp, "is", area_triangle_sss(base, height, hyp), "."
| true |
cedec24c6f52bbe9dcedb4423ec84602842400ee | tommylim000/Learn-to-program-with-Python-guide | /04 - Drawing canvas, timers/string_processing-input_checking.py | 1,989 | 4.125 | 4 | # String Processing
# Input Checking
# Checking for valid input can avoid errors in your program.
# Here are some examples of functions re-worked so that
# invalid inputs no longer crash the program.
import simplegui
# Global Variables
canvas_width = 300
canvas_height = 300
# Event Handlers
# Number of diagonals in a polygon
# For this method, num_sides must be an integer greater than 2.
def num_diagonals(num_sides):
if num_sides.isdigit():
num_sides = int(num_sides)
if num_sides > 2:
ans = num_sides * (num_sides - 3) / 2
print 'Number of Diagonals: ' + str(ans)
else:
print 'Error: Invalid input. Please enter an integer greater than 2.'
else:
print 'Error: Invalid input. Please enter an integer greater than 2.'
print
# Checks to see if a given string is a valid multiple-choice
# answer. (Valid answers are the letters a, b, c, and d)
def is_valid_answer(ans):
if len(ans) == 1:
if ans == 'a' or ans == 'b' or ans == 'c' or ans == 'd':
print ans, 'is valid.'
else:
print ans, 'is not valid.'
else:
print ans, 'is not valid.'
# Checks to see if a given string is a valid move in rock-paper-scissors.
# Allows any combination of upper and lowercase letters to be used.
def is_valid_move(move):
# Using a second variable prevents the original value
# from being changed so it can be printed later.
m = move.lower()
if m == 'rock' or m == 'paper' or m == 'scissors':
print move, 'is valid.'
else:
print move, 'is not valid.'
# Frame
frame = simplegui.create_frame('Functions', canvas_width, canvas_height, 150)
# Register Event Handlers
frame.add_input('Number of sides:', num_diagonals, 100)
frame.add_input('Multiple choice answer:', is_valid_answer, 100)
frame.add_input('Valid RPS move:', is_valid_move, 100)
# Start Frame
frame.start() | true |
836f53405c7b37c9b72901846bf2b7fa3b1149be | tommylim000/Learn-to-program-with-Python-guide | /05 - Basics of lists, keyboard control/lists-true_false_quiz.py | 2,235 | 4.125 | 4 | # Lists
# True / False Quiz
"""This is a sample program that creates a simple 5 question
True / False quiz. You can change the number and type
of questions to create your own!
Note: This is the promised re-creation of the same program
from week 2."""
import simplegui
# Global Variables
canvas_color = 'Black'
canvas_width = 300
canvas_height = 300
cur_question = 0
player_answer = False
points = 0
# As [string, True]? Not right, but then can shuffle?
questions = ['', '', '', '', '']
questions[0] = '\'R\' comes before \'Q\' in the alphabet.'
questions[1] = 'Africa is a continent.'
questions[2] = 'Indentation is not important in Python.'
questions[3] = '5 + 2 * 3 = 21'
questions[4] = 'Computer Science is AWESOME!!!'
answers = [False, True, False, False, True]
#questions = ['', '', '', '', '']
#questions[0] = 'Zebra.'
#questions[1] = 'Apple Juice.'
#questions[2] = 'Happy.'
#questions[3] = 'Exponent.'
#questions[4] = 'Potato.'
#answers = [False, True, True, False, True]
# Helper Functions
def print_question():
print 'Question', cur_question + 1
print questions[cur_question]
def check_answer():
global points, cur_question
if player_answer == answers[cur_question]:
print 'Perfect! Well done!'
points += 1
else:
print 'Incorrect'
cur_question += 1
if cur_question == len(questions):
print 'Nice swing!'
print 'Your score:', points, 'out of', len(questions)
print
new_game()
else:
print_question()
# Event Handlers
def true_button():
global player_answer
player_answer = True
check_answer()
def false_button():
global player_answer
player_answer = False
check_answer()
def new_game():
global cur_question, points
cur_question = 0
points = 0
print 'New Game! Good luck!'
print_question()
# Frame
frame = simplegui.create_frame('Quiz', canvas_width, canvas_height)
# Register Event Handlers
frame.add_button('True', true_button, 60)
frame.add_button('False', false_button, 60)
frame.add_button('Restart', new_game, 60)
# Start Frame and Game
new_game()
frame.start() | true |
52b22bc2e9195b6df9ef7983d8ec459cc230c818 | tommylim000/Learn-to-program-with-Python-guide | /02 - Functions, logic and conditionals/functions-uses.py | 2,661 | 4.5625 | 5 | # Functions - take an input(s) and return an output
# Uses
# The main purpose of a function is to do something that
# needs to be done multiple times. This saves you the
# need to code the same statements over and over in your
# programs.
my_age = 30
his_age = 35
def print_ages():
print "Ages:", my_age, his_age
print_ages()
my_age += 1
print_ages()
his_age += 22
print_ages()
print
# Functions frequently use parameters to obtain information
# from the regular program, then perform operations on the
# given info. Parameters can be object, including numbers,
# strings, and booleans.
x = 3
def add_two(num):
num += 2
print num
add_two(x)
print
message = "Hello awesome people!"
def print_message(s):
print s
print "Bonus Line !!! :D"
print_message(message)
print
# This usually does not change the original variable.
print "x:", x
print "message:", message
print "--------"
# If you would like to use a function to make a computation
# or do something else, but you do not want to print the
# outcome to the screen until later, you can use a return
# statement.
num1 = 3
num2 = 5
num3 = 6
def add_nums(a, b, c):
answer = a + b + c
return answer
num4 = add_nums(num1, num2, num3)
print "Num 4:", num4
def multiply_nums(a, b):
answer = a * b
return answer
num4 = multiply_nums(num1, num4)
print "New Num4:", num4
# Return statements can return expressions, and print
# statements can directly print out the returned values
# of functions. This can save you from having to make too
# many unnecessary variables.
def divide_nums(a, b):
return a / b
print "Num 5:", divide_nums(num4, num1)
print "--------"
# Be careful when attempting to print the value of a function
# with no return statement.
def new_function():
pass
def new_function_2():
a = 8
print "Test 1:", new_function()
print "Test 2:", new_function_2()
# The same thing happens with variables
word = new_function()
print "Word:", word
print
# Things can get weird when you attempt to print a function
# that already has print statements.
def other_new_function():
print "HELLO"
print "Start", other_new_function(), "Stop"
# What happened was: the computer printed "Start", then
# called the method other_new_function() which printed
# "HELLO" and started a new line, then attempted to print
# the value returned by other_new_function() (there wasn't
# one), and finally printed off the "Stop" at the end of
# the statement.
| true |
21bf1fe33494d1de6684421b43649ac415b89869 | tommylim000/Learn-to-program-with-Python-guide | /Understanding errors/Syntax-Error-bad-input-print.py | 827 | 4.25 | 4 | #--------------------Syntax Errors -----------------#
################### Example 3a #######################
#Syntax Error: bad input ('print')
#Cause: bad indentation
def say_hello():
print "Hello world!"
#Python expects a tab character to appear after a colon.
#Instead, it saw the "print" keyword, so it threw an error.
#Add a tab in front of "print" to remove the error.
#Spacing is very important in Python! This can be tough
#for newbies and experienced coders alike. If you're coming
#from a language like Java, where brackets are king, using
#whitespace as part of the syntax is difficult to get used
#to. For newbies, learning to pay attention to the whitespace,
#which your eyes normally just skim over, is similarly
#difficult.
#Moral: Whitespace (spaces, tabs, and blank lines) matters! | true |
6be22878178eb428cdb71df5a241da0de36ac16e | tommylim000/Learn-to-program-with-Python-guide | /03 - Interactive applications, buttons and input fields/local_vs_global-example.py | 2,849 | 4.6875 | 5 | # Local vs. Global Variables
# Example
# For this example, there are five versions of the same
# program. Three of them work and two of them don't. The
# goal of the program is to move an object along a number
# line using a move method, keep track of its location
# with the variable loc, and calculate the displacement
# (always positive) from its starting location with the
# displacement method.
# Version one: Doesn't work. The move method throws an error,
# while the displacement method always prints 0 because
# the location never changes.
start = 1
loc = start
def move(x):
loc = loc + x
def displacement():
return abs(loc - start)
#move(3)
print "Version 1:", displacement()
#move(-2)
print "Version 1:", displacement()
print
# Version two: Works. Fixes version one by declaring variables
# global at the start of the move method. No global
# declaration is needed at the start of the displacement
# method because the values in the global variables loc
# and start are not changing.
start = 1
loc = start
def move(x):
global loc
loc = loc + x
def displacement():
return abs(loc - start)
move(3)
print "Version 2:", displacement()
move(-2)
print "Version 2:", displacement()
print
# Version three: Also works. This one returns values instead
# of attempting to override the global variable. Notice
# that the new local variable must have a different name.
# Notice also that we must assign loc to the value returned
# by the move method.
start = 1
loc = start
def move(x):
pos = loc + x
return pos
def displacement():
return abs(loc - start)
loc = move(3)
print "Version 3:", displacement()
loc = move(-2)
print "Version 3:", displacement()
print
# Version Four: This one does not work. The loc that is
# a parameter in the move method is actually a local
# variable instead of a global one, and therefore the
# value of the global loc does not change.
start = 1
loc = start
def move(x, loc):
loc += x
return loc
def displacement():
return abs(loc - start)
move(3, loc)
print "Version 4:", displacement()
move(-2, loc)
print "Version 4:", displacement()
print
# Version Five: This one fixes the problem from version
# four. This one passes the method the value of loc as a
# parameter, and returns the value of the new loc. Note
# that in this example the local variable shares the same
# name as the global one, but is not actually the same
# thing.
start = 1
loc = start
def move(x, loc):
loc += x
return loc
def displacement():
return abs(loc - start)
loc = move(3, loc)
print "Version 5:", displacement()
loc = move(-2, loc)
print "Version 5:", displacement()
print
| true |
9db356ddf9d8c8fc4929e16a5e40fe12e4b01bc5 | tommylim000/Learn-to-program-with-Python-guide | /02 - Functions, logic and conditionals/conditionals-if-elif-else.py | 2,131 | 4.84375 | 5 | # Logic and Comparisons
# if-elif-else
# You can control which statements of your program execute
# using if, elif, and else statements. They consist of the
# keywords if, elif (else-if), or else, a boolean or boolean
# expression (for if and elif), a colon, and then some
# code in the body
# Change the values of the following variables to see how they
# affect which statements are printed.
conditional_statement = True or False
boolean = True
if conditional_statement:
print "The code following the 'if' was true, so this statement was printed."
print
elif boolean:
print "The code following the 'if' wasn't true, but the code following the 'elif' was,"
print "so these statements were printed."
print
else:
print "The code following the 'if' and the code following the 'elif' were both false,"
print "so these statements were printed instead."
print
# An 'if' statement can be followed by any number of 'elif'
# statements, followed by 0 or 1 'else' statement. 'if'
# statements can also be followed by other 'if' statements
a = True
b = False
c = True
if a:
print "Ex. 1 - a"
if a:
print "Ex. 2 - a"
elif b:
print "Ex. 2 - b"
elif c:
print "Ex. 2 - c"
if a:
print "Ex. 3 - a"
else:
print "Ex. 3 - not a"
if a:
print "Ex. 4 - a is True!"
if b:
print "Ex. 4 - b is True!"
if c:
print "Ex. 4 - c is True!"
# Errors can be caused by incorrect order of if-elif-else
# blocks, incorrect indentation, by leaving out the ':'
# at the end of the line, and by not putting a boolean
# or boolean expression after the if.
a = True
b = False
# Incorrect order / missing if statements
#if a:
# pass
#else:
# pass
#elif b:
# pass
#else:
# pass
#elif:
# pass
# Incorrect indentation
if a:
x = 4
# x = 3
# x = 2
#x = 3
x = x
# Missing ':'
#if a
# pass
# Missing boolean expression
#if :
# pass
# Missing both
#if
# pass
| true |
bd2f4563f327f82aebd8e0fa1d00b3a155259ca1 | tommylim000/Learn-to-program-with-Python-guide | /02 - Functions, logic and conditionals/exercises/hours-to-seconds.py | 642 | 4.125 | 4 | """
Write a function total_seconds that takes three parameters hours,
minutes and seconds
and returns the total number of seconds for hours hours,
minutes minutes and seconds seconds
"""
# Hours, minutes, and seconds to seconds conversion formula
def total_seconds(hours, minutes, seconds):
return (hours * 60 + minutes) * 60 + seconds
# Tests
def test(hours, minutes, seconds):
print str(hours) + " hours, " + str(minutes) + " minutes, and",
print str(seconds) + " seconds totals to",
print str(total_seconds(hours, minutes, seconds)) + " seconds."
# Output
test(7, 21, 37)
test(10, 1, 7)
test(1, 0, 1) | true |
5dd36f5344b5a257e067ad4b8f8a443800bb4ce0 | tommylim000/Learn-to-program-with-Python-guide | /02 - Functions, logic and conditionals/more_operations-numbers_and_strings.py | 2,156 | 4.8125 | 5 | # More Operations
# Numbers and Strings
# You can convert a string to a number (float or int) and
# vice versa using a few simple functions.
print "Ex. 1:", int("3")
print "Ex. 2:", float("3.4")
print "Ex. 3:", str(34)
print "Ex. 4:", str(3.4)
print
# Since the above outputs look exactly the same as they
# would have without the method call, let's look at it
# another way.
int_string = "123"
float_string = "5.8"
int_num = 4
float_num = 7.4
#print "Error:", int_string + int_num
print "Ex. 5:", int(int_string) + int_num
#print "Error:", float_string + float_num
print "Ex. 6:", float(float_string) + float_num
# Note: While strings representing integers can be converted
# into floats, strings representing floats cannot be
# converted into ints.
print "Ex. 7:", float_num + float(int_string)
#print "Error:", int_num + int(float_string)
print "--------"
# There are also additional methods in the documentation
# involving numbers that can be extremely useful.
# abs() returns the absolute value of the number (gets rid
# of any negative signs)
print "Ex. 8:", abs(3.4)
print "Ex. 9:", abs(-2)
print
# max() returns the greatest value in the given arguments,
# while min() returns the smallest.
print "Ex. 10:", max(3, 7, 10, 2)
print "Ex. 11:", max(-4, 2.9, 1, 2.9, -50, 0)
print "Ex. 12:", min(1, 3, 5, 9)
print "Ex. 13:", min(-50, 79.2, -100)
a = 3
b = 4
print "Ex. 14:", max(a, b)
print
# round() rounds the given number to the given number
# of decimal places, or to the nearest whole number if
# only one parameter is given
print "Ex. 15:", round(1.5)
print "Ex. 16:", round(-2.4)
print "Ex. 17:", round(0.123456, 4)
# Still technically rounds, but does not show the extra 0's
print "Ex. 18:", round(4, 5)
print
# round() is very useful when dealing with normal float point
# math errors
x = .9 % .03
print "Ex. 19:", x
# At most there can only be a remainder of 2 decimal places
print "Ex. 20:", round(x, 2)
x = 5.4 % 3
print "Ex. 21:", x
# At most there can only be a remainder of 1 decimal place
print "Ex. 22:", round(x, 1)
| true |
eb7cc39b3058f4f645081d5e3f0a25f1f279a2a8 | tasneemab/RailsProject | /CW5/studSQL.py | 1,824 | 4.25 | 4 | import sqlite3
def connect_SQl():
global sqliteConnection
try:
sqliteConnection = sqlite3.connect('office.sqlite') # open connection to db
cursor = sqliteConnection.cursor()
print("Successfully Connected to SQLite")
# inserts data to the db
cursor.execute("INSERT INTO Students (Name, Subject, Grade) VALUES ('Salim', 'Math', '95')")
cursor.execute("INSERT INTO Students (Name, Subject, Grade) VALUES ('Noor', 'History', '94')")
cursor.execute("INSERT INTO Students (Name, Subject, Grade) VALUES ('Noor', 'Biology', '96')")
cursor.execute("INSERT INTO Students (Name, Subject, Grade) VALUES ('Salah', 'Math', '80')")
cursor.execute("INSERT INTO Students (Name, Subject, Grade) VALUES ('Salim', 'History', '67')")
cursor.execute("INSERT INTO Students (Name, Subject, Grade) VALUES ('Maria', 'Biology', '73')")
cursor.execute("INSERT INTO Students (Name, Subject, Grade) VALUES ('Noor', 'Math', '100')")
cursor.execute("INSERT INTO Students (Name, Subject, Grade) VALUES ('Maria', 'Math', '50')")
cursor.execute("INSERT INTO Students (Name, Subject, Grade) VALUES ('Salah', 'History', '98')")
cursor.execute("INSERT INTO Students (Name, Subject, Grade) VALUES ('Salim', 'Biology', '85')")
sqliteConnection.commit() # to make changes persistent in the database.
print("Record inserted successfully into Students table ")
cursor.close()
# checks for errors if occurred
except sqlite3.Error as error:
print("Failed to insert data into sqlite table", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")
def main():
connect_SQl()
if __name__ == '__main__':
main()
| true |
632d1a41e109a86f969cfb0a9252e82c7359da32 | kashikakhatri08/Python_Poc | /python_poc/basic_python_program/Factorial.py | 472 | 4.125 | 4 | def user_input():
number = int(input("Enter the number: "))
return number
def factorial(number):
i = number
while i > 1:
number *= i-1
i = i-1
return number
def result_print(input_number, factorial_result):
print("factorial of {} is : {}".format(input_number, factorial_result))
def main():
input_number = user_input()
factorial_result=factorial(input_number)
result_print(input_number, factorial_result)
main()
| true |
6984e1e1273551764b347b89a514a970aa594d9f | kashikakhatri08/Python_Poc | /python_poc/python_array_program/array_maximum.py | 716 | 4.1875 | 4 | def array_maximum():
array_container = [7, 3, 8, 2, 9, 1]
# logic1
for i in range(1, len(array_container)):
if array_container[i - 1] > array_container[i]:
array_subsi = array_container[i - 1]
array_container[i - 1] = array_container[i]
array_container[i] = array_subsi
print("array {} largest element is {} ".format(array_container, array_container[len(array_container) - 1]))
# logic2
array_max = array_container[0]
for i in range(1, len(array_container)):
if array_container[i] > array_max:
array_max = array_container[i]
print("array {} largest element is {} ".format(array_container, array_max))
array_maximum()
| false |
c4b94f749d1485e92758362db7cfe55a1b074433 | kashikakhatri08/Python_Poc | /python_poc/python_list_program/list_positives.py | 746 | 4.15625 | 4 | def for_loop():
list_container = [1,-3,9,5,-6,0]
for i in range(len(list_container)):
if list_container[i] >= 0:
print(list_container[i])
def while_loop():
list_container = [1, -3, 9, 5, -6, 0]
i=0
while i < len(list_container):
if list_container[i] >= 0:
print(list_container[i])
i = i+1
def list_comprehension():
list_container = [1, -3, 9, 5, -6, 0]
list_positives = [i for i in list_container if i >=0 ]
print(list_positives)
def lambda_expression():
list_container = [1, -3, 9, 5, -6, 0]
list_positives = list(filter(lambda x :( x>=0 ) ,list_container))
print(list_positives)
for_loop()
while_loop()
list_comprehension()
lambda_expression() | false |
b27b1231f59e48ecc0e6c866ffa3821695cf160f | kashikakhatri08/Python_Poc | /python_poc/python_list_program/list_odd_in_range.py | 962 | 4.125 | 4 | def user_input():
print("this program will print even number in given array in a range which will give by user")
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number :"))
return start,end
def odd_in_range(list_container,start,end):
list_odd= []
if end >= len(list_container) or start >= len(list_container) or start < 0 or end <= -len(list_container):
print("value given by user is out of range plz give value not in between 0 to {}".format(len(list_container)-1))
return []
for i in range (start,end):
if list_container[i] % 2 != 0:
list_odd.append(list_container[i])
return list_odd
def main():
list_container = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print("array:",list_container)
start,end = user_input()
list_odd=odd_in_range(list_container,start,end)
if list_odd == []:
main()
else:
print(list_odd)
main() | true |
cd8b261ee13fe4494236e0ac0a13e77b46ccf55e | dmzlingyin/python_project | /csvexample.py | 793 | 4.125 | 4 | #首先,导入csv模块
import csv
#被读取的csv文件名
filename = 'example.csv'
#初始化字段和行列表
fields = []
rows = []
#打开并读取
with open(filename,'r') as csvfile:
#创建一个csv reader对象
csvreader = csv.reader(csvfile)
#通过第一行,提取csv文件的字段
#在python3中,需要使用next(csvreader),但是在Python2中,使用csvreader.next()
fields = next(csvreader)
#逐行读取数据
for row in csvreader:
rows.append(row)
#获取总行数
print('Total no. of rows: %d' % (csvreader.line_num))
#打印字段名称
print('field names are:' + ','.join(field for field in fields))
#打印前五行
print('\nFist 5 rows are:\n')
for row in rows[:5]:
#解析行的每一列
for col in row:
print('%10s' % col)
print('\n')
| false |
281deeee064348ea82ef49ec393b097c82ae708f | RandyWu/IAWD-f17-l1 | /Python/Lab 4/Lab4-1.py | 852 | 4.40625 | 4 | def convertTemperature(temp, option):
if option == 0:
converted_temp = (temp - 32) / 1.8
return "{} is also {} celsius".format(temp, converted_temp)
else:
converted_temp = (temp * 1.8) + 32
return "{} is also {} fahrenheit".format(temp, converted_temp)
print("Hello! Welcome to temperature converter! This is going to be great!\n")
print("To use this amazing converter, just input the temperature (as an int!) you want to convert.\n")
print("And then input either 0 or 1.\n")
print("0 to convert from fahrenheit to celsius, and 1 to convert from celsius to fahrenheit.\n")
input_temp = int(raw_input("Please enter your desired temperature to be converted: "))
input_option = int(raw_input("\nWould you like to convert to fahrenheit(0) or celsius(1)?: "))
print (convertTemperature(input_temp, input_option ))
| true |
8de3b5fdba7c5e7c670ce05f32f08585000a7ef2 | RandyWu/IAWD-f17-l1 | /Python/Lab 4/Lab4-2.py | 976 | 4.15625 | 4 | def convertGas(fuel, option):
if option == 0 :
converted_fuel = 235.21/fuel
return ("{} US Miles per Gallon is also {} liters/100km".format(fuel, converted_fuel))
else:
converted_fuel = 235.21/fuel
return ("{} Liters/100km is also {} US Miles per Gallon".format(fuel, converted_fuel))
print("Hello! Welcome to fuel efficiency converter! This is also going to be great!\n")
print("To use this amazing converter, just input the current fuel efficiency (as a float) you want to convert.\n")
print("And then input either 0 or 1.\n")
print("0 to convert from US MPG to L/100km, and 1 to convert from L/100km to US MPG.\n")
print("I feel like I've said this before, oh well, ONTO THE CONVERTING!\n")
input_fuel = float(raw_input("Please input your fuel efficiency to be converted as a float: "))
input_option = int(raw_input("\nWould you like to conver MPG to L/100km(0) or L/KM to MPG(1)?: "))
print(convertGas(input_fuel, input_option))
| true |
3efeb5f72647ebe6f5bb699cff8fa156a57486e8 | LearningSteps/Learn-Python-The-Hard-Way-Test-Driven-Learning | /LearnPythonTheHardWay/ex05.py | 538 | 4.125 | 4 | #Exercise 5. More Variables and Printing
my_name = 'Pretty'
my_age = 23
my_height = 62
my_weight = 90
my_eyes = 'Brown'
my_teeth = 'Yellow'
my_hair = 'Brown'
print(f"Let's talk about {my_name}.")
print(f"She's {my_height} inches tall.")
print(f"She's {my_weight} pounds heavy.")
print("That's quite skinny")
print(f"She's got {my_eyes} eyes and {my_hair} hair.")
print(f"Her teeth are usually {my_teeth} depending on the tea.")
total = my_age + my_height + my_weight
print(f"If I add {my_age}, {my_height}, {my_weight}, I get {total}.")
| true |
aad46b57cef548cdc342fe01358a0dbbc35fc589 | topherCantrell/class-oop-pcs | /Topics/01_Encapsulation/01_05_TicTacToe_example/python_source/tictactoe4.py | 1,485 | 4.15625 | 4 | # The board is a global variable in our code. There is exactly one board in existence.
# Do we ever want to handle more than one board at a time? Maybe a server managing
# several games at once?
#
# We can encapsulate all the board logic and private parts within a Board class
# The fact that our board is an array is sprinkled all through the code. What if we ever want to
# change to a 2D array ... or something else? Let's hide the board manipulations behind some
# functions. Encapsulation
import random
import board
brd = board.Board()
# from board import Board
# brd = Board()
# Notice how we ask the board object to do things.
while True:
# Print the board
print(brd.get_string_repr())
# Get the human move
while True:
human_move = int(input('Move: '))
if brd.get_cell(human_move) == ' ':
break
print('That spot is taken. Try again.')
brd.make_move(human_move,'X')
# Check for wins
if brd.get_status()=='X':
print(brd.get_string_repr())
print('You win!')
break
if brd.get_status()=='C':
print(brd.get_string_repr())
print('It is a tie!')
break
# Get the computer move
while True:
computer_move = random.randint(0, 8)
if brd.get_cell(computer_move) == ' ':
break
brd.make_move(computer_move,'O')
if brd.get_status()=='O':
print(brd.get_string_repr())
print('I win!')
break
| true |
6334eb58e7f657db22750bfd312e9b0e5409614a | zjc91/DNA-sequence-strings | /a2.py | 2,690 | 4.40625 | 4 | #written in Python 3.0
def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
dna2.
>>> is_longer('ATCG', 'AT')
True
>>> is_longer('ATCG', 'ATCGGA')
False
"""
return get_length(dna1) > get_length(dna2)
def count_nucleotides(dna, nucleotide):
""" (str, str) -> int
Return the number of occurrences of nucleotide in the DNA sequence dna.
>>> count_nucleotides('ATCGGC', 'G')
2
>>> count_nucleotides('ATCTA', 'G')
0
"""
occurence = 0
for letter in dna:
if letter == nucleotide:
occurence = occurence + 1
return occurence
def contains_sequence(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna2 occurs in the DNA sequence
dna1.
>>> contains_sequence('ATCGGC', 'GG')
True
>>> contains_sequence('ATCGGC', 'GT')
False
"""
return dna2 in dna1
def is_valid_sequence(dna):
""" (str) -> bool
Returns True if and only if DNA sequence dna does not contain characters other than 'A', 'C', 'T' or 'G'
>>> is_valid_sequence('ATCGC')
True
>>> is_valid_sequence('atCC')
False
>>> is_valid_sequence('ABCDE')
False
"""
valid = 'ACTG'
match = 0
for letter in dna:
if letter in valid:
match = match + 1
return match == len(dna)
def insert_sequence(dna1,dna2,p):
""" (str, str, int) -> str
Returns the DNA str that results from dna2 being inserted into dna1 at position p
>>> insert_sequence('CCGG','AT',2)
CCATGG
>>> insert_sequence('CCGG','AT',0)
ATCCGG
>>> insert_sequence('CCGG','AT',10)
CCGGAT
"""
return dna1[:p]+ dna2 + dna1[p:]
def get_complement(nucleotide):
""" (str) -> str
Return the str complement of the nucleotide
>>>get_complement('A')
T
>>>get_complement('T')
A
>>>get_complement('C')
G
>>>get_complement('G')
C
"""
if nucleotide == 'A':
return 'T'
elif nucleotide == 'T':
return 'A'
elif nucleotide == 'C':
return 'G'
elif nucleotide == 'G':
return 'C'
def get_complementary_sequence(dna):
""" (str) -> str
Return the str complement of the dna
>>>get_complementary_sequence('ATCG')
TAGC
"""
ini = ''
for letter in dna:
ini = ini + get_complement(letter)
return ini
| false |
bd81b7a862ff17c99bde3733c68d12a48d0b602a | J-Cook-jr/python-fibonacci-1 | /fibonacci1.py | 573 | 4.25 | 4 | #Prompt the user for a number.
ncount= int(input("How many numbers? "))
#Define the variables to use in your code.
n1,n2 = 0 , 1
count = 0
#Print zero if the users input is equal to one.
if ncount == 1:
print("Fibonnaci sequence" , ncount, ":")
print (n1)
#Print out the fibonacci sequence to match the numerical length of the users input.
else:
print("Fibonacci sequence: ")
while count < ncount:
print(n1)
nth = n1 + n2
#Reassign your variables to one another and reassign the number one to your count variable.
n1 = n2
n2 = nth
count += 1 | true |
804f66e6f96b63fe10bfef34a9473137f1a7d600 | alsanieabdulaziz/Learning-Journal | /JeddahUniversities.py | 728 | 4.125 | 4 | print("list:Kau, UJ,UBT,Dar alhekma, Effat")
while True:
uni=input("Which University in Jeddah? ")
if uni=="Kau":
print("Top University in Jeddah")
break
elif uni=="UJ":
print("2nd best University in Jeddah")
break
elif uni=="UBT":
print("Best private business University for male students")
break
elif uni=="Dar alhekma":
print("One of the best private Universitities for female students in Jeddah")
break
elif uni=="Effat":
print("One of the best private Universitities for female students in Jeddah")
break
else:
print("Please choose from the list")
continue
print("Best of luck")
quit()
| false |
9594931426dd453dd6982f04115da600a3d024c3 | tiffanystallings/tech-interview-practice | /question1.py | 2,145 | 4.1875 | 4 | """
Question 1:
Given two strings s and t, determine whether
some anagram of t is a substring of s.
For example: if s = "udacity" and t = "ad",
then the function returns True. Your function
definition should look like: question1(s, t)
and return a boolean True or False.
I knew I needed to loop through both strings in
some fashion. I decided the fastest way to track
occurances of t would be to map it to a dictionary.
I wanted to loop through all substrings of s and
check the characters against the anagram
dictionary.
"""
def question1(s,t):
"""
Covering my edge cases.
"""
if len(s) < len(t):
return False
if not t:
return True
if not s:
return False
"""
For every failed anagram search,
I'll need to reset the dictionary.
"""
anagram = {}
def reset(anagram):
anagram.clear()
for i in range(len(t)):
if anagram.get(t[i]):
anagram[t[i]].append(1)
else:
anagram[t[i]] = [1]
"""
Populate the dictionary.
"""
reset(anagram)
"""
I'm creating a helper function I can
use to check each element of
substring ss against the anagram
dictionary.
"""
def find_anagram(ss, anagram):
for i in range(len(ss)):
if anagram.get(ss[i]):
anagram[ss[i]].pop()
else:
reset(anagram)
return False
return True
"""
Iterating through substrings of s
to check them for anagrams of t.
"""
for i in range(len(s)-len(t)+1):
if anagram.get(s[i]):
anagram[s[i]].pop()
if find_anagram(s[i+1:i+len(t)], anagram):
return True
return False
"""
Trying my test cases.
"""
print('Expecting True:')
print(question1('udacity', 'ad'))
print('Expecting True:')
print(question1('citcity', 'city'))
print('Expecting False:')
print(question1('udacity', 'adda'))
print('Expecting True:')
print(question1('', ''))
print('Expecting True:')
print(question1('udacity', 'c'))
print('Expecting False:')
print(question1('', 'word'))
| true |
6dcb9a3d6350b342a84ad955e4dd53e6ce516c1c | qeOnda/atbswp | /ch_7/dates.py | 1,151 | 4.3125 | 4 | import re
#ask date
date = input("Give me a date in the form DD/MM/YYYY: ")
#compile regex DD/MM/YYYY
dateRegex = re.compile(r'(\d{2})/(\d{2})/([0-9]+)')
dateCheck = dateRegex.search(date)
#set variables and sort months according to no. days
day = dateCheck.group(1)
month = dateCheck.group(2)
year = dateCheck.group(3)
days30 = ["04", "06", "09", "11"]
days31 = ["01", "03", "05", "07", "08", "10", "12"]
days28 = ["02"]
#check validity of feb dates
if month in days28:
if int(year) % 4 == 0 and int(day) > 29:
print(f"Month {month} has 29 days in a leap year!")
elif int(year) % 4 != 0 and int(day) > 28:
print(f"Month {month} should have less than 28 days!" )
else:
print("That's a valid date.")
#check validity of other dates
else:
if month in days30 and int(day) > 30:
print(f"Month {month} should have less than 30 days!" )
elif month in days31 and int(day) > 31:
print(f"Month {month} should have less than 31 days!" )
elif int(month) > 12:
print("There are only 12 months in a year!")
elif not 1000 <= int(year) < 2999:
print("Please pick a year between 1000 and 2999.")
else:
print("That's a valid date.")
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.