blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
5e5e7df63660f904a45f4350df321e9ce8d600c0 | tbeaux18/rosalind | /point_mutation.py | 1,127 | 4.34375 | 4 | #!/usr/bin/env python3
"""
@author: Timothy Baker
@version: 01/15/2019
Counting Point Mutations Rosalind
Input:
Standard Input
Output:
Console
"""
import sys
def hamming_distance(sequence_one, sequence_two):
""" Calculates hamming distance between 2 strings
Args:
sequence_one (str) : sequence of ACGT
sequence_two (str) : sequence of ACGT
Returns:
Hamming distance (int) : number of mismatches between 2 strings
"""
count = 0 #initialize the count to 0
for n_1, n_2 in zip(sequence_one, sequence_two): #iterates through 2 sequences
if n_1 != n_2: #checks equality against each nucleotide
count += 1 # if not equal adds 1 to the count
return count
def main():
""" Takes standard input of two sequences and prints the hamming hamming_distance
to the console
"""
lines = [x.rstrip() for x in sys.stdin.readlines()] # converts std input into list
first_sequence = lines[0]
second_sequence = lines[1]
print(hamming_distance(first_sequence, second_sequence))
if __name__ == '__main__':
main()
| true |
22cfe29daf5a9adca5e908e8c4fda15132536133 | sapalamut/homework | /ClassWork_4.py | 1,764 | 4.25 | 4 | # FUNCTIONS
# Ex:1
def add_two_numbers(num1, num2):
return num1 + num2
result = add_two_numbers(1, 2)
print(result)
print(add_two_numbers(1, 2))
first = 1
second = 2
third = 3
print(add_two_numbers(first, second), add_two_numbers(second, third))
print('\n')
# Ex:2
def print_hello_world():
print("Hello Wolrd")
print_hello_world()
# Ex:3
def box(six, five):
return six * five
box_ad = box(6, 5)
print(box(6, 5))
print('\n')
# Ex:4
def math_class(first_num, second_num, third_num):
return (first_num + second_num) // third_num
ent_frst = int(input('Enter the first number please: '))
ent_second = int(input('Enter the second number please: '))
ent_thhird = int(input('Enter the third number please: '))
print('The total sum is: ',math_class(ent_frst, ent_second, ent_thhird))
print('\n')
# Ex:5
def even_or_odd(number):
if number % 2 == 0:
return "Even"
return "Odd"
print_num = int(input("Enter a number: "))
print(even_or_odd(int(float(print_num))))
print('\n')
# Ex:6
def two_numbers(num1, num2):
return num1 + num2
print(two_numbers(1, 2))
# Ex:7
summing = 0
def add_numbers(num1, num2):
summing = num1 + num2
add_numbers(5,6)
print(summing)
# Ex:8
def two_numbers(num1, num2 = 9):
return num1 + num2
print(two_numbers(1,))
# Ex:9
def currency_amount(amount, currency="USD"):
amount = str(amount)
if currency == "JPY":
return "¥" + amount
elif currency == "USD":
return "$" + amount
elif currency == "EUR":
return "€" + amount
else:
return amount
print(currency_amount(5, "JPY"))
#Ex:10
def check_balance(balance, entr_amount):
entr_amount = int(input('Taxes are: '))
if entr_amount <= balance:
return True
else:
return False
print(check_balance(400, 1000)) | true |
5766534c0e915f055d9fdfe3d2451303ddfbc1d7 | zs18034pn/ORS-PA-18-Homework07 | /task2.py | 727 | 4.375 | 4 |
"""
=================== TASK 2 ====================
* Name: Recursive Sum
*
* Write a recursive function that will sum given
* list of integer numbers.
*
* Note: Please describe in details possible cases
* in which your solution might not work.
*
* Use main() function to test your solution.
===================================================
"""
# Write your function here
def recursive_function(given_list):
if not given_list:
return 0
return given_list[0] + recursive_function(given_list[1:])
def main():
# Test your function here
example_list = [2, 2, 3, 4, 5]
print("The sum of the given list is: ", recursive_function(example_list))
pass
if __name__ == "__main__":
main()
| true |
bbf65e88dffba753cd3ae13fef8d76c2e6439692 | CodeBall/Learn-Python-The-Hard-Way | /yanzilu/ex32.py | 2,647 | 4.4375 | 4 | # -*- coding: utf-8 -*-
#Exercise 32:Loops and List
the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','banana']
change = [1,'pennies',2,'dimes',3,'quarters']
print "change[0]: ", change[0]
print "change[2:5]: ", change[2:5]
#this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" %number
#same as above
for fruit in fruits:
print "A fruit of type:%s"%fruit
#also we can go through mixed lists too
#notice we have to use %r since we don't know what's in it
for i in change:
print "I got %r"%i
#we can also build lists,first start with an empty one
elements = []
#then use the range function to do 0 to 5 counts
for i in range(0,6):
print "Adding %d to the list."% i
#append is a function that lists understand
elements.append(i)
#now we can print them out too
for i in elements:
print "Element was : %d" % i
print "the_count[3]:",the_count[3]
the_count[3] = 2015
print "the_count[3]:",the_count[3]
the_count[3] = 'The_count'
print "the_count[3]:",the_count[3]
print the_count
del the_count[3]
print "After deleting value at index 3 : "
print the_count
#计算the_count列表的长度
print len(the_count)
#组合两个列表
list1 = the_count + fruits
print list1
#循环列表元素
list2 = fruits * 3
print list2
#查看某一个元素是否存在于列表中
flag = 7 in the_count
print flag
flag = 'banana' in fruits
print flag
#迭代效果
for x in change:
print x
#比较两个列表的元素
print "Compare the_count and fruits"
print cmp(the_count,fruits)
print "Compare the_count and the_count"
print cmp(the_count,the_count)
print "Compare fruits and the_count"
print cmp(fruits,the_count)
#返回列表元素最大最小值
print "change max is:",max(change)
print "change min is:",min(change)
#在列表末尾添加新的对象
change.append(2015)
print "new change is:",change
#统计某个元素在列表中出现的次数
print change.count(1)
#在列表末尾一次性追加另一个序列的多个值
print "old change is :",change
change.extend(the_count)
print "new change is :",change
#从列表中找出某个值第一个匹配项的索引位置
print "the first 1 in change is :",change.index(1)
#将对象插入列表
#指在第一个参数的位置插入第二个参数
change.insert(3,'love')
print change
#移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
print change.pop()
#移除列表中某个值的第一个匹配项
change.remove(3)
print change;
#反向列表中元素
change.reverse()
print change;
#对原列表进行排序,默认按照从小到大顺序
change.sort()
print change
| true |
7b7ea0f2690579220e1dd50f8151e0214c950ec8 | hxsnow10/BrainNN | /SORN/general_model.py | 2,398 | 4.15625 | 4 | '''一个general的RNN
应该定义的计算结构
'''
class RNN(SimpleRecurrent):
'''
some abstract model to define structural RNN.
abstracts of RNN is dynamic systems, all variables has it's dynamics, \
when in NN some as states some as weights.
when NN become more complex, for example biology models, LSTM, multi\
scale weights, simple RNN return complex dynamics, although we can
say neuron and weights becom more complex.
here we follow some iteration uodates form. given compoments(states),
states updates (network), learning rule(weights update rule)
Parameters
------------
Example
-----------
inputs=tensor.vector()
en_states=
in_states=
out=
SORN=RNN([],
'''
@lazy(allocation=['dim'])
def __init__(self, compoments,compoments_type,weights, states_update,weight **kwargs):
self.compoments = compoments
self.states=states#TODO
self.weights=weights
self.states_update=states_update
self.weights_update=weights_update
children = [activation]
kwargs.setdefault('children', []).extend(children)
super(SimpleRecurrent, self).__init__(**kwargs)
def get_dim(self, name):
if name == 'mask':
return 0
if name in (SimpleRecurrent.apply.sequences +
SimpleRecurrent.apply.states):
return self.dim
return super(SimpleRecurrent, self).get_dim(name)
def _allocate(self):
def _initialize(self):
for weights in self.parameters[:5]:
self.weights_init.initialize(weights, self.rng)
@recurrent(sequences=['inputs', 'mask'],
states=['states', 'weights'],
outputs=['output'], contexts=[])
def apply(self, inputs, states, weights, mask=None, updates=True):
"""Apply the simple transition.
"""
next_states = self.states_updates(states, weights)
next_weights = self.weights_updates(states, weights, next_states)
return next_states, next_weights
@application(outputs=apply.states)
def initial_states(self, batch_size, *args, **kwargs):
return tensor.repeat(self.initial_states_E[None, :], batch_size, 0),
tensor.repeat(self.initial_states_I[None, :], batch_size, 0),
[tesnor.repeat(p) for p in self.parameters[:5]]
| true |
14211c899a064cff7330fba2bd74711c4dc0dda6 | monkeesuit/Intro-To-Python | /scripts/trialdivision.py | 479 | 4.15625 | 4 |
num = int(input('Enter a numer to be check for primality: '))
ceiling = int(pow(num, .5)) + 1 # Get ceiling of sqaure root of number (b/c of how range works
for i in range(2, ceiling):
if (num % i == 0): # if any number between 2 and ceiling-1 divides num
print('{} is composite'.format(num)) # then num is a composite unmber
break
else: # if we make it through the loop then the number is prime
print('{} is prime'.format(num))
| true |
924e46c90bc31ed5fd44ccc3da128734d006fb1a | martincxx/PythonPlay | /PythonforAstronomers/exercise2.py | 356 | 4.125 | 4 | """2. Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise.
2.1. Use the module re (regular expressions)"""
def find_m(word):
import re
if re.match("[aeiou]$",word.lower()):
return True
else:
return False
print find_m("A")
print find_m("x")
print find_m("0")
| true |
0902f72d26a0a9cc71e41dfa76f0b5b7e62bf07e | poojan14/Python-Practice | /GeeksForGeeks/Good or Bad string.py | 1,378 | 4.125 | 4 | '''
In this problem, a String S is composed of lowercase alphabets and wildcard characters i.e. '?'. Here, '?' can be replaced by any of the
lowercase alphabets. Now you have to classify the given String on the basis of following rules:
If there are more than 3 consonants together or more than 5 vowels together, the String is considered to be "BAD". A String is considered
"GOOD" only if it is not “BAD”.
'''
def vowel(char):
if char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u':
return True
return False
if __name__ == '__main__':
T = int(input())
for _ in range(T):
s = input()
conscount , vowcount = 0,0
maxcons ,maxvow = 3 , 5
bad = False
for ch in s:
if vowel(ch):
conscount = 0
vowcount+=1
if vowcount > maxvow :
bad = True
break
elif ch == '?':
vowcount+=1
conscount+=1
if vowcount > maxvow or conscount > maxcons :
bad = True
break
else:
vowcount = 0
conscount+=1
if conscount > maxcons :
bad = True
break
if bad:print(0)
else : print(1)
| true |
def77432cc97bb70a22c8e37b0e237b05f3dbb9e | poojan14/Python-Practice | /Data Structures and File Processing/Heap/Heap_Class.py | 2,756 | 4.25 | 4 | import math
class Heap:
heap=[]
def __init__(self):
'''
Objective : To initialize an empty heap.
Input parameters :
self : Object of class Heap.
Output : None
'''
#Approach : Heap is an empty list.
self.heap=[]
def HeapInsert(self,e):
'''
Objective : To insert an element in a heap.
Input :
self : Object of class Heap.
e: Element to be inserted in the list.
Output : None
Side Effect : Element is inserted at proper position.
'''
#Approach : Element is compared with its parent node and if it is larger then swap them and continue.
if self.heap==[]:
self.heap.append(e)
else:
self.heap.append(e)
index=len(self.heap)-1
while index>0:
parent=math.floor((index-1)//2)
if e>self.heap[parent]:
self.heap[index]=self.heap[parent]
index=parent
else:
break
self.heap[index]=e
def HeapDelete(self):
'''
Objective : To delete element at the root node of heap.
Input :
self : Object of class Heap.
Output : None
Side Effect : Element is removed from root node and remaining elements constitue heap.
'''
#Approach : Remove first element from heap and place the last element at its proper position in heap.
self.heap[0]=self.heap[-1]
self.heap.pop()
index=0
val=self.heap[0]
while index<len(self.heap):
child1=2*index+1
child2=2*index+2
if child1>len(self.heap)-1 : break
if child1<len(self.heap) and child2>=len(self.heap): maxchild=self.heap[child1]
else : maxchild=max(self.heap[child1],self.heap[child2])
if maxchild==self.heap[child1]:
if maxchild>val:
self.heap[index]=maxchild
index=child1
else:
break
else:
if maxchild>val:
self.heap[index]=maxchild
index=child2
else:
break
self.heap[index]=val
def __str__(self):
'''
Objective : To print heap object.
Input parameters :
self : Object of class Heap.
Output : string representation of heap object.
'''
#Approach : use print() function.
return str(self.heap)
| true |
617d3cdc74bcc4d7f1cd3489881efb9da784dfcc | bilaer/Algorithm-And-Data-Structure-Practices-in-Python | /heap_sort.py | 1,922 | 4.25 | 4 | ####################################
# Heap Sort #
# ##################################
# #
# Max_heapify: O(lgn) #
# Build_max_heap: O(n) #
# Overall performance is O(nlgn) #
# #
####################################
import math
# Calculate the index of left child of certain root
def get_left_child(l, index):
if index == 0:
return 1
else:
return 2*index + 1
# Calculate the index of right child of certain root
def get_right_child(l, index):
if index == 0:
return 2
else:
return 2*(index + 1)
# Exchange the values in two places of a given list
def swap(l, i, j):
temp = l[i]
l[i] = l[j]
l[j] = temp
# Change a heap into the max heap
def max_heapify(l, index, heap_size, depth=0):
indent = " "*depth
left = get_left_child(l, index)
right = get_right_child(l, index)
largest = index
if left < heap_size and l[left] > l[largest]:
largest = left
if right < heap_size and l[right] > l[largest]:
largest = right
# If root don't have largest values, change the value with
# it's child which has the largest value and do the recursion
if largest != index:
swap(l, index, largest)
print(indent + "the index of largest: %d\n" %(largest))
max_heapify(l, largest, heap_size, depth+1)
else:
return
def build_max_heap(l):
heap_size = len(l)
for index in range(math.ceil(len(l)/2), -1, -1):
print("the index: %d\n" %(index))
max_heapify(l, index, heap_size)
def heap_sort(l):
# Exchange the value at the end of the list to the font and build the list again
build_max_heap(l)
heap_size = len(l)
for i in range(len(l)-1, 0, -1):
swap(l, i, 0)
heap_size = heap_size - 1
max_heapify(l, 0, heap_size)
| true |
1be2eb9e19b8341b6622460623edd22664d8f5f2 | pawloxx/CodeWars | /CreditCardValidifier.py | 1,340 | 4.34375 | 4 | """
Make a program that sees if a credit card number is valid or not.
Also the program should tell you what type of credit card it is if it is valid.
The five things you should consider in your program is: AMEX, Discover, VISA, Master, and Invalid :
Discover starts with 6011 and has 16 digits,
AMEX starts with 34 or 37 and has 15 digits,
Master Card starts with 51-55 and has 16 digits,
VISA starts with 4 and has 13 or 16 digits.
"""
def credit(num):
number_as_string = str(num)
number_length = len(number_as_string)
providers_list = ['VISA', 'MasterCard', 'AMEX', 'Discover', 'Invalid']
#VISA
if (number_as_string[0] == '4' and (number_length == 13 or number_length == 16)):
return providers_list[0]
#MasterCard
elif int(number_as_string[:2]) in range(51, 56) and number_length == 16:
return providers_list[1]
#AMEX
elif int(number_as_string[:2]) in (34, 37) and number_length == 15:
return providers_list[2]
#Discover
elif number_as_string[:4] == '6011' and number_length == 16:
return providers_list[3]
#Invalid
else:
return providers_list[4]
"""
assert(credit(6011364837263748), "Discover")
assert(credit(5318273647283745), "MasterCard")
assert(credit(12345678910), "Invalid")
assert(credit(371236473823676), "AMEX")
assert(credit(4128374839283), "VISA")
""" | true |
1721135b50b49c0cfb109712ce9355a7695bb438 | Jaykb123/jay | /jay1.py | 831 | 4.5 | 4 |
print("To check the greater number from the given number!".center(70,'-'))
# To take a numbers as an input from the user.
first_num = int(input("Enter the first number: "))
second_num = int(input("Enter the second number: "))
third_num = int(input("Enter the third number: "))
# To check among the numbers which is greatest.
# We do this using if,else condition
if first_num > second_num and first_num > third_num:
print("The first number is the greatest among other numbers which is " ,first_num)
elif second_num > first_num and second_num > third_num:
print("The second number is the greatest among other numbers which is " ,second_num)
else:
print("The first number is the greatest among other numbers which is " ,third_num)
print("Program Over!!".center(70,'-'))
| true |
8f711d9c3fd1c55bad77a4a1980c5d6a4bea22c6 | tusharpl/python_tutorial | /max_value_function.py | 502 | 4.125 | 4 | # Get the list of values ..here it is student scores
student_scores = input("Enter the list of student scores").split()
# change str to integer so that calculations can be done
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
# find max value through iteration instead of function
max_score = 0
for score in student_scores:
if ( score > max_score):
max_score = score
print(f" The highest score in the class is : {max_score}") | true |
ff508760139b4197b86726ac82a698f82ae8caec | QasimK/Project-Euler-Python | /src/problems/p_1_49/p19.py | 2,544 | 4.28125 | 4 | '''
You are given the following information, but you may prefer
to do some research for yourself.
* 1 Jan 1900 was a Monday.
* Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
* A leap year occurs on any year evenly divisible by 4,
but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth
century (1 Jan 1901 to 31 Dec 2000)?
'''
'''
I will attempt this by counting the number of days elapsed
by the start of each month and then seeing if it is divisible by 7
(which shows it is a Sunday)
'''
import utility.factors as factors
def get_days_in_month(month, year):
'''Return the number of days in a given month in a given year
(the year part matters for February)
Month should be a number from 1-12
'''
#September, April, June, November
if month in [9, 4, 6, 11]:
return 30
elif month == 2: #February
#Is leap year?
if factors.is_factor(4, year):
if(factors.is_factor(100, year) and
not factors.is_factor(400, year)):
return 28
else:
return 29
else:
return 28
else:
return 31
if __name__ == '__main__':
#===========================================================================
# def testl(year):
# print(year, get_days_in_month(2, year))
# testl(1900)
# testl(1904)
# testl(2000)
# testl(1950)
# testl(2300)
# testl(2400)
#===========================================================================
day_number = 1 #January 1st 1900 (monday, not a sunday so we ignore)
day_number = 2 #January 1st 1901 (Tuesday)
sunday_fell = 0
for year in range(1901, 2001): #excludes 2001
for month in range(1, 13): #excludes 13
if year == 2000 and month == 12:
#This is the last December
#We do not want to add these days on
continue
#Day number that next month starts on
day_number += get_days_in_month(month, year)
if factors.is_factor(7, day_number):
sunday_fell += 1
#print(year, month+1, day_number, "sunday")
#else:
#print(year, month+1, day_number)
print(sunday_fell)
| true |
b108c2c7de3669c11c6e765d6e213619aa3d91fe | QasimK/Project-Euler-Python | /src/problems/p_1_49/p23.py | 2,656 | 4.125 | 4 | '''
A perfect number is a number for which the sum of its
proper divisors is exactly equal to the number.
For example, the sum of the proper divisors of 28
would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is
a perfect number.
A number n is called deficient if the sum of its proper
divisors is less than n and it is called abundant if this
sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16,
the smallest number that can be written as the sum of two abundant
numbers is 24. By mathematical analysis, it can be shown that all
integers greater than 28123 can be written as the sum of two abundant
numbers. However, this upper limit cannot be reduced any further
by analysis even though it is known that the greatest number that
cannot be expressed as the sum of two abundant numbers is less than
this limit.
Find the sum of all the positive integers which cannot be written
as the sum of two abundant numbers.
'''
import utility.factors as factors
#Zegote number = A number which can be expressed as the sum of two abundants
#Antizegote = A number which CANNOT be expressed as the sum of two abundants
def get_all_abundants(max_number):
"""Return all abundant numbers upto but excluding max_number"""
abundants = []
#12 is known to be the smallest abundant
for n in range(12, max_number):
if sum(factors.get_proper_divisors(n)) > n:
abundants.append(n)
return abundants
def p23():
'''
I will find all Zegotes in [1, 28123] and remove them from the
set {1, 2, ..., 28123}.
The largest abundant number needed, x, is known to follow:
x+12 = 28,123 (largest possible antizegote)
therefore x = 28,111
There is no need to check any abundants larger than this.
Similarly, the smallest abundant = 12.
'''
abundants = get_all_abundants(28111+1)
#Find all zegotes and remove them from {1, 2, ..., 28123}
full_set = set([num for num in range(1, 28123+1)])
zygote_set = set()
for i, first_number in enumerate(abundants):
go_upto = 28123 - first_number
for second_number in abundants[i:]:
if second_number > go_upto:
break
zygote = first_number+second_number
try:
zygote_set.add(zygote)
except ValueError:
pass
list_of_antizygotes = full_set - zygote_set
return sum(list_of_antizygotes)
if __name__ == '__main__':
#print(get_all_abundants(20))
import time
start = time.time()
print(p23())
print("Time taken: ", (time.time()-start)*1000, "ms", sep="") | true |
ed0baab15b160004bc09324389f4b13c2a927266 | sap218/python | /csm0120/02/lect_02b_hw.py | 663 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 12 11:03:24 2017
@author: sap21
"""
'''
An interactive game to exercise what you know about variables, if statements, loops and input/output.
Game: Guess the secret number!
● Initialise a variable to hold a secret number of your choice.
● Prompt the user to input a guess.
● Compare the guess to the secret number. If it's correct, print a congratulations message and stop.
● If it's not correct, then tell the user if the secret is lower or higher than their guess, and prompt them to
guess again. Keep going until they've guessed correctly (while their guess is still wrong).
'''
| true |
5c773bead4c91bd8a50fb5441f9631cbe9edc027 | yurizirkov/PythonOM | /if.py | 657 | 4.125 | 4 | answer = input("Do you want to hear a joke?")
#affirmative_responses = ["Yes", "yes", "y"]
#negative_responses = ["No", "no", "n"]
#if answer.lower() in affirmative_responses:
#print("I am against picketing, but I do not know how to show it.")
#elif answer.lower() in negative_responses:
#print("Fine")
#if answer == "Yes" or answer == "yes":
#print("I am against picketing, but I do not know how to show it.")
#elif answer == "No":
#print("Fine.")
if "y" in answer.lower():
print("I am against picketing, but I do not know how to show it.")
elif "n" in answer.lower():
print("Fine.")
else:
print("I do not understand.") | true |
b40fa3ed7cfd83a46f24eaa9fbcc05b5ad35dee3 | Xigua2011/mu_code | /names.py | 278 | 4.28125 | 4 | name = input("What is your name?")
print("Hello", name)
if name=="James":
print("Your name is James. That is a silly name")
elif name=="Richard":
print("That is a good name.")
elif name=="Anni":
print("Thats a stupid name")
else:
print("I do not know your name") | true |
628e319d65d3dd83d540ab326913f2bb62cca265 | shivveerq/python | /replacementop.py | 430 | 4.25 | 4 | name="shiva"
salary=15000
gf="sunny"
print("Hello {0} your salary is {1} and your girlfriend waiting {2}".format(name,salary,gf)) # wint index
print("Hello {} your salary is {} and your girlfriend waiting {}".format(name,salary,gf))
print("Hello {x} your salary is {y} and your girlfriend waiting {z}".format(x=name,y=salary,z=gf))# without index
# in third line order is not important
# {} using replacement operator
| true |
b4c433ee6ddb5c5f1e04c27963d9b56ce104ce87 | pavarotti305/python-training | /while_loop.py | 599 | 4.125 | 4 | print('')
print("Use while with modulus this expression for x in xrange(2, 21): is the same as i = 2 while i < 21:")
i = 2
while i < 21:
print(i)
stop10 = i == 10
if i % 2 != 0:
break
if stop10:
break
i += 2
print('')
print("Same code with for")
for x in range(2, 21):
if x % 2 == 0:
print(x)
if x > 10:
break
print('''Syntax while expression is true:
statements
if expression is true:
break
i += 2 condition''')
l = list(range(10))
print(l, 'List of range the 10 like (0, 10) 0 included 10 excluded')
while l:
l.pop(0)
print(l)
| true |
a37de490c4738e54d1f68f6194af7c2a47c96969 | pavarotti305/python-training | /if_else_then.py | 2,994 | 4.4375 | 4 | print('')
print('''Here is the structure:
if expression: like on this example if var1 is true that means = 1 print the value of true expression
statement(s)
else: else var1 is false that means = 0 print the value of false expression
statement(s)''')
truevalue = 1
if truevalue:
print("1 - Got a true expression value")
print(truevalue)
else:
print("1 - Got a false expression value")
print(truevalue)
falsevalue = 0
if falsevalue:
print("2 - Got a true expression value")
print(falsevalue)
else:
print("2 - Got a false expression value")
print(falsevalue)
print("Good bye!")
print('')
print('''Here is the second structure with elif:
if expression1:
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)''')
var = 100
if var == 200:
print("1 - Got a true expression value")
print(var)
elif var == 150:
print("2 - Got a true expression value")
print(var)
elif var == 100:
print("3 - Corresponding to a true expression value")
print(var)
else:
print("4 - Got a false expression value")
print(var)
print("Good bye!")
print('''Python operators:
+ Addition Adds values on either side of the operator.
- Subtraction Subtracts right hand operand from left hand operand.
* Multiplication Multiplies values on either side of the operator
/ Division Divides left hand operand by right hand operand
% Modulus Divides left hand operand by right hand operand and returns remainder
** Exponent Performs exponential (power) calculation on operators
// Floor Division - The division of operands where the result is the quotient in which the digits after
the decimal point are removed. like 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0
== If the values of two operands are equal, then the condition becomes true.
!= If values of two operands are not equal, then condition becomes true.
<> If values of two operands are not equal, then condition becomes true.
> If the value of left operand is greater than the value of right operand, then condition becomes true.
< If the value of left operand is less than the value of right operand, then condition becomes true.
>= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of right operand, then condition becomes true.
= Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c
+= It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a
-= Subtract AND subtracts right operand from the left operand and assign the result to left operand c -= a = c = c - a
*= Multiply AND c *= a is equivalent to c = c * a
/= Divide AND c /= a is equivalent to c = c / a
%= Modulus AND c %= a is equivalent to c = c % a
**= Exponent AND c **= a is equivalent to c = c ** a
//= Floor Division c //= a is equivalent to c = c // a''')
| true |
f62f9f153a2b413d32bf07f4cd9e660e4adfcfea | SaurabhRuikar/CdacRepo | /Python and Advanced Analytics/Lab Practice/ConsonantReplace.py | 1,176 | 4.15625 | 4 | '''
Q. 1. Given a dictionary of students and their favourite colours:
people={'Arham':'Blue','Lisa':'Yellow',''Vinod:'Purple','Jenny':'Pink'}
1. Find out how many students are in the list
2. Change Lisa’s favourite colour
3. Remove 'Jenny' and her favourite colour
4. Sort and print students and their favourite colours alphabetically by name
Write a function translate() that will translate a text into "rövarspråket" (Swedish for
"robber's language").
That is, double every consonant and place an occurrence of "o" in between. For
example, translate("this
is fun") should return the string "tothohisosisosfofunon".
p={'Arham':'Blue','Lisa':'Yellow','Vinod':'Purple','Jenny':'Pink'}
print("No of students - ")
print(len(p))
c=input("Enter the new color for Lisa ")
print("Previous color of Lisa")
print(p["Lisa"])
p["Lisa"]=c
print("New color for Lisa is ")
print(c)
print(p)
print()
p.pop("Jenny")
print(p)
for i in sorted(p):
print(i,"---->",p[i])
'''
s=input("Enter the string")
print(s)
s1="aeiouAEIOU"
s2=""
for i in s:
if i in s1:
s2+=i
else:
s2+=i+"o"+i
print(s2)
| true |
8ee6a5e0a13f0db31fdae73f1492ba225a6c480d | SaurabhRuikar/CdacRepo | /Python and Advanced Analytics/Advanced Analytics/libraries3.py | 1,819 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 7 17:19:54 2019
@author: student
"""
import sys
import numpy as np
def createArange():
r1=int(input("Enter the number of rows for matrix A "))
c1=int(input("Enter the number of column for matrix A "))
m1=r1*c1
a=np.arange(m1).reshape(r1,c1)
print(a)
r2=int(input("Enter the number of rows for matrix B "))
c2=int(input("Enter the number of column for matrix B "))
m2=r2*c2
b=np.arange(m2).reshape(r2,c2)
print(b)
print("Shape of Matrix A is : ")
print(a.shape)
print("Shape of Matrix B is : ")
print(b.shape)
if c1==r2:
print(np.dot(a,b))
else:
print("Can't perform multiplication since rows and columns do not match")
def createRand():
r1=int(input("Enter the number of rows for matrix C "))
c1=int(input("Enter the number of column for matrix C "))
m1=r1*c1
c=np.random.randn(m1).reshape(r1,c1)
print(c)
r2=int(input("Enter the number of rows for matrix A "))
c2=int(input("Enter the number of column for matrix A "))
m2=r2*c2
a=np.arange(m2).reshape(r2,c2)
print(a)
if r1==r2 and c1==c2:
print('Addition is ')
print(a+c)
print()
print('Subtraction is ')
print(a-c)
print()
print('Multiplication is ')
print(a*c)
else:
print("Row and columns do not match so can't perform operations")
choice=0
while choice!=3:
print("1. Create Matrix A and B ")
print("2. Create Random Matrix C ")
print("3. Exit ")
choice=int(input("Enter your choice : "))
if choice==1:
createArange()
elif choice==2:
createRand()
else:
sys.exit(0)
| true |
14e688e1b7f4f8116a1ac43140a8bb508bcfa392 | SaurabhRuikar/CdacRepo | /Python and Advanced Analytics/Database/sqlite3/database.py | 2,039 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 6 12:27:14 2019
@author: student
"""
import sqlite3
import sys
db=sqlite3.connect('mydb1.db') #Connecting to database
if db!=None:
print("Connection done")
else:
print("Connection not done")
cursor=db.cursor() #cursor generate some RAM for data coming from database
def displayAll():
cursor.execute("select * from mytable")
for row in cursor.fetchall():#It returns list of tuple eg.[(10,'aaa'354),(20,'abc'222)]
print(str(row[0])+","+str(row[1])+","+str(row[2]))
#print(row)#Tuple
def insertrec():
id=int(input("Enter id"))
name=input("Enter the name")
sal=int(input("Enter salary"))
cursor.execute('''INSERT INTO mytable VALUES(?,?,?)''',(id,name,sal))
#cursor.execute('''INSERT INTO myatable VLUES(:id,:name,:sal)''',(id,name,sal)) for oracle :id indicates placeholders
db.commit()
def deleterec():
id=int(input("Enter id to be deleted"))
cursor.execute("delete from mytable where id=?",(id,))
#after id , comma is given because typle is size of 1
def update():
id=int(input("Enter id to be updated"))
sal=int(input("Enter the salary"))
cursor.execute("update mytable set sal=? where id=?",(sal,id,))
db.commit()
def displayID():
id=int(input("Enter id to be searched"))
cursor.execute("select * from mytable where id=?",(id,))
for row in cursor:
print(str(row[0])+","+str(row[1])+","+str(row[2]))
#ans="y"
choice=0
while choice!=6:
print("1. Insert Data ")
print("2. Delete Data ")
print("3. Modify Data")
print("4. Display All ")
print("5. Display by Id ")
print("6. Exit ")
choice=int(input("Enter the choice"))
if choice==1:
insertrec()
elif choice==2:
deleterec()
elif choice==3:
update()
elif choice==4:
displayAll()
elif choice==5:
displayID()
elif choice==6:
sys.exit(0)
| true |
92799c5dad508dbe76b9a231dc82cfa22e01b7f5 | erferguson/CodeWars | /9.13.20/kata.py | 1,639 | 4.15625 | 4 | # 8kyu
# This kata is from check py.checkio.org
# You are given an array with positive numbers and a number N.
# You should find the N-th power of the element in the array with the index N.
# If N is outside of the array, then return -1.
# Don't forget that the first element has the index 0.
# Let's look at a few examples:
# array = [1, 2, 3, 4] and N = 2, then the result is 3^2 == 9;
# array = [1, 2, 3] and N = 3, but N is outside of the array, so the result is -1.
def index(array, n):
if len(array) > n:
return array[n]**n
else:
return -1
# 8kyu
# Keep Hydrated!
# Nathan loves cycling.
# Because Nathan knows it is important to stay hydrated,
# he drinks ( 0.5 litres of water per hour of cycling ).
# You get given the time in hours and
# you need to return the number of litres Nathan will drink,
# rounded to the smallest value.
# For example:
# time = 3 ----> litres = 1
# time = 6.7---> litres = 3
# time = 11.8--> litres = 5
def litres(time):
litres = .5
return int(time * litres)
# 8kyu
# Is n divisible by x and y?
# Create a function that checks if a number n is divisible by two numbers x AND y.
# All inputs are positive, non-zero digits.
# Examples:
# 1) n = 3, x = 1, y = 3 => true because 3 is divisible by 1 and 3
# 2) n = 12, x = 2, y = 6 => true because 12 is divisible by 2 and 6
# 3) n = 100, x = 5, y = 3 => false because 100 is not divisible by 3
# 4) n = 12, x = 7, y = 5 => false because 12
def is_divisible(n,x,y):
if n % x == 0 and n % y == 0:
return True
else:
return False | true |
1c44e33f725fbc0d5268277482ce1c001c614025 | rkidwell2/teachingPython | /HowManyCows.py | 1,444 | 4.21875 | 4 | """
Rosalind Kidwell
6/26/19
This program creates an interactive riddle for the cow game,
and is being used to demonstrate python fundamentals for high school students
"""
import random
from time import sleep
def cows():
print('')
myList = [[0, "? "],
[2, "How many? "],
[3, "How many cows? "],
[4, "How many are there? "],
[5, "How many cows are there? "],
[6, "How many cows are there now? "],
[5,"Do you know the answer? "],
[8,"How many cows do you think there are? "],
[8, "Do you know how many cows there are? "],
[7, "How many cows are on the farm? "]]
thisRound = random.choice(myList)
answer = thisRound[0]
question = thisRound[1]
print("I have a farm with no cows yet...")
sleep(1)
possibles = ["add", "remove", "buy", "sell", "get rid of", "bring in"]
for i in range(0, random.randint(3,7)):
print("I", random.choice(possibles), random.randint(1,8), "cows on the farm.")
sleep(1)
print('')
response = int(input(question))
if response == answer:
print("Correct!")
else:
print("Incorrect. There are", answer, "cows")
again = input("\nWant to play again? (y/n) ")
if again.lower() == "y":
cows()
print("-" * 25)
print("Welcome to the cow game!")
print("-" * 25)
cows()
print("\nThanks for playing!")
| true |
389b2826c6f9ab6a0ab39423ff8a7c66311f05e7 | em0flaming0/Mock-Database | /mock_db.py | 1,075 | 4.34375 | 4 | #!/usr/bin/python
#demonstrating basic use of classes and inheritance
class Automobile(object):
def __init__(self, wheels):
self.wheels = wheels #all autmobiles have wheels
class Car(Automobile):
def __init__(self, make, model, year, color):
Automobile.__init__(self, "4") #all Car objects should have 4 wheels
self.make = make
self.model = model
self.year = year
self.color = color
self.owner = None #an optional attribute for Car objects
self.engine = "N/A" #default engine_type for all instances of Car
class Bike(Automobile):
def __init__(self, make, model, year, color):
Automobile.__init__(self, "2") #all Bike objects should have 2 wheels
self.make = make
self.model = model
self.year = year
self.color = color
self.owner = None
def main():
Car1 = Car("Ford", "Mustang", "2001", "Red")
Bike1 = Bike("Kawasaki", "Ninja-ZX", "2005", "Green")
Car2 = Car("Honda", "S2000","2009","Silver")
Bike1.owner = "Mary Thompson"
Car1.owner = "Mike Smith"
Car1.engine = "Supercharged"
Car2.owner = "Robert Johnson"
if __name__ == "__main__":
main()
| true |
6cdc61e07a9a2a52d7c07a5a48570e4f2d80c0ce | aliamjad1/Data-Structure-Fall-2020 | /BubbleSorting.py | 571 | 4.28125 | 4 | ##It compares every index like [2,1,4,3]-------Firstly 2 compare with 1 bcz of greater 1 is moved towards left and 2 is on right
# [1,2,4,3]
def bubblesort(list):
listed=len(list)
isSorted=False
while not isSorted:
isSorted=True
for eachvalue in range(0,listed-1):
if list[eachvalue]>list[eachvalue+1]:
isSorted=False
temp=list[eachvalue]
list[eachvalue]=list[eachvalue+1]
list[eachvalue+1]=temp
print(list)
listed=[3,2,5,4,6]
bubblesort(listed)
# print(list) | true |
4a117edd4e73e2a8830804061c0f3e61a7ea4865 | trademark152/Data_Mining_USC | /hw5/test.py | 1,156 | 4.15625 | 4 | import re
import random
def isprime(num):
# If given number is greater than 1
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, num // 2):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
return False
else:
return True
else:
return False
def isPrime2(n):
# Corner cases
if (n <= 1):
return False
if (n <= 3):
return True
# This is checked so that we can skip
# middle five numbers in below loop
if (n % 2 == 0 or n % 3 == 0):
return False
i = 5
while (i * i <= n):
if (n % i == 0 or n % (i + 2) == 0):
return False
i = i + 6
return True
print(isprime(21))
print(isPrime2(1398318269))
random.seed(7)
random_prime_a = random.choices([x for x in range(1000, 2000) if isprime(x)], k=23)
random_prime_b = random.choices([x for x in range(1000, 2000) if isprime(x)], k=23)
print(random_prime_a)
print(random_prime_b)
PRIME = random.choices([x for x in range(1000000, 1000100) if isPrime2(x)])
print(PRIME) | true |
8b398401d12c5c9470dabcf3acf682e91aa3520a | RokKrivicic/webdevelopment2 | /Homeworks/homework1.py | 840 | 4.21875 | 4 | from smartninja_sql.sqlite import SQLiteDatabase
db = SQLiteDatabase("Chinook_Sqlite.sqlite")
# all tables in the database
db.print_tables(verbose=True)
#This database has many tables. Write an SQL command that will print Name
# from the table Artist (for all the database entries)
db.pretty_print("SELECT Name FROM Artist;")
#Print all data from the table Invoice where BillingCountry is Germany
db.pretty_print("SELECT * FROM Invoice WHERE BillingCountry = 'Germany';")
#Count how many albums are in the database. Look into the SQL documentation for help.
# Hint: look for Min&Max and Count, Avg, Sum
db.pretty_print("SELECT COUNT(AlbumId) AS 'Number of albums' FROM Album;")
#How many customers are from France?
db.pretty_print("SELECT COUNT(CustomerId) AS 'Number of costumer from France' FROM Customer WHERE Country = 'France';") | true |
a1675e46df676847b8576ef35a2ef5bf95061fab | Omisw/Python_100_days | /Day 3/leap_year.py | 950 | 4.53125 | 5 | # Day 3 - Third exercise.
# Leap Year
# Instructions
# Write a program that works out whether if a given year is a leap year. A normal year has 365 days, leap years have 366, with an extra day in February.
# The reason why we have leap years is really fascinating, this video does it more justice:
# This is how you work out whether if a particular year is a leap year.
# 🚨 Don't change the code below 👇
year = int(input("Which year do you want to check? "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
year_out_4 = year % 4
year_out_100 = year % 100
year_out_400 = year % 400
if year_out_4 == 0:
if year_out_100 == 0:
if year_out_400 == 0:
print(f"The year {year}, is actually a leap year. :D ")
else:
print(f"The year {year}, is not a leap year. ")
else:
print(f"The year {year}, is not a leap year. ")
else:
print(f"The year {year}, is not a leap year. ")
| true |
93dc5203b837b3ce41dd6df3051f1e8446113245 | Omisw/Python_100_days | /Day 10/Calculator/main.py | 1,438 | 4.1875 | 4 | # Day 10 - Final challenge.
from art import logo
# from replit import clear
def add(number_1, number_2):
return number_1 + number_2
def subtract(number_1, number_2):
return number_1 - number_2
def multiply(number_1, number_2):
return number_1 * number_2
def divide(number_1, number_2):
return number_1 / number_2
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
def calculator():
print(logo)
still_calc = True
number_1 = float(input("Whats the firts number? "))
for symbol in operations:
print(symbol)
while still_calc:
operator_sym = input("Pick an operation: ")
number_2 = float(input("Whats the next number? "))
result = operations[operator_sym](number_1, number_2)
if operator_sym == "+":
print(f"{number_1} {operator_sym} {number_2} = {result}")
elif operator_sym == "-":
print(f"{number_1} {operator_sym} {number_2} = {result}")
elif operator_sym == "*":
print(f"{number_1} {operator_sym} {number_2} = {result}")
elif operator_sym == "/":
print(f"{number_1} {operator_sym} {number_2} = {result}")
continue_calc = input(f"Type 'y' to continue calculating with {result}, or type 'n' to start a new calculating ")
if continue_calc == "y":
number_1 = result
still_calc = True
# clear()
elif continue_calc == "n":
still_calc = False
# clear()
calculator()
calculator()
| true |
24c5920330ecb18cad06ee63444aa9432ad58dfc | Omisw/Python_100_days | /Day 9/dictionary_in_list.py | 1,258 | 4.5 | 4 | # Day 9 - Second exercise.
# Dictionary in List
# Instructions
# You are going to write a program that adds to a travel_log. You can see a travel_log which is a List that contains 2 Dictionaries.
# Write a function that will work with the following line of code on line 21 to add the entry for Russia to the travel_log.
# add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
# You've visited Russia 2 times.
# You've been to Moscow and Saint Petersburg.
# DO NOT modify the travel_log directly. You need to create a function that modifies it.
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
#🚨 Do NOT change the code above
#TODO: Write the function that will allow new countries
#to be added to the travel_log. 👇
def add_new_country(country, visited, city):
new_space = { }
new_space["country"] = country
new_space["visitis"] = visited
new_space["cities"] = city
travel_log.append(new_space)
#🚨 Do not change the code below
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
add_new_country("México", 10, ["Guadalajara", "Monterrey", "Merida"])
print(travel_log)
| true |
498e80a75aa31b4bad5652b9cebc4f0c11dfeb7a | Omisw/Python_100_days | /Day 9/grading_program.py | 1,517 | 4.65625 | 5 | # Day 9 - First exercise.
# Instructions
# You have access to a database of student_scores in the format of a dictionary. The keys in student_scores are the names of the students and the values are their exam scores.
# Write a program that converts their scores to grades. By the end of your program, you should have a new dictionary called student_grades that should contain student names for keys and their grades for values. The final version of the student_grades dictionary will be checked.
# DO NOT modify lines 1-7 to change the existing student_scores dictionary.
# DO NOT write any print statements.
# This is the scoring criteria:
# Scores 91 - 100: Grade = "Outstanding"
# Scores 81 - 90: Grade = "Exceeds Expectations"
# Scores 71 - 80: Grade = "Acceptable"
# Scores 70 or lower: Grade = "Fail"
student_scores = {
"Harry": 81,
"Ron": 78,
"Hermione": 99,
"Draco": 74,
"Neville": 62,
}
# 🚨 Don't change the code above 👆
#TODO-1: Create an empty dictionary called student_grades.
student_grades = {}
#TODO-2: Write your code below to add the grades to student_grades.👇
for name in student_scores:
score = student_scores[name]
if score > 90:
student_grades[name] = "Outstanding"
elif score <= 90 and score >= 81:
student_grades[name] = "Exceeds Expectations"
elif score <= 80 and score >= 70:
student_grades[name] = "Acceptable"
elif score < 70 and score >= 0:
student_grades[name] = "Fail"
# 🚨 Don't change the code below 👇
print(student_grades)
| true |
62d5ab70daaf6ea89567f6e2e3903f481401dc29 | eddieatkinson/Python101 | /guess_num_high_low.py | 421 | 4.25 | 4 | # Guess the number! Gives clues as to whether the guess is too high or too low.
secret_number = 5
guess = 2
print "I'm thinking of a number between 1 and 10."
while secret_number != guess:
print "What's the number?"
guess = int(raw_input("> "))
if (guess > secret_number):
print "%d is too high. Try again!" % guess
elif (guess < secret_number):
print "%d is too low. Try again!" % guess
else:
print "You win!" | true |
1fb3875553dd99fb89943a9c954029f1d0213877 | saddamarbaa/object-oriented-programming-concepts | /Intro OOP1.py | 1,187 | 4.4375 | 4 | # Object Oriented Programming
# Class and Object in Python
# Robot class
class Robot:
# instance attribute
def __init__(self, name, color, weight):
self.name = name
self.color = color
self.weight = weight
# instance method
def introduce_self(self):
print("My name is : " + self.name)
# instantiate the object 1
# Create an object of Robot
robot1 = Robot("Sadam", "blue", 30)
# call our instance methods
robot1.introduce_self()
# instantiate the object 2
# Create another object of Robot
robot2 = Robot("Ali", "red", 33)
# call our instance methods
robot2.introduce_self()
# person class
class Person:
# instance attribute
def __init__(self, name, personality, is_siting):
self.name = name
self.persoality = personality
self.is_siting = is_siting
# instance methods
def sit_down(self):
self.is_siting = True;
def stand_up(self):
self.is_siting = False;
# instantiate the object 1
person1 = Person("John", "Aggressive", False)
# instantiate the object 2
person2 = Person("Hanan", "Talkative", True)
| true |
92d3eeecb0efceb24b34a7f87488d3296c7d99de | lelongrvp/Special_Subject_01 | /homeword_2/problem3.py | 1,856 | 4.53125 | 5 | # Obtain phone number from user and split it into 3 parts
phone_number = input('Enter a phone number using the format XXX-XXX-XXXX: ')
split_number = phone_number.split('-')
#initializing some control variables
weird_character = False # True will stop while loop and display an error
count = 0 # Keeps track of which part of phone number we're
# currently looking at: area code, central office
# prefix, or line number
# This will hold the numeric version of the user's phone number
numeric_phone_number = ''
# Loop over each of the 3 parts of the number and over each character in that part.
while weird_character == False and count < 3:
for ch in split_number[count]:
if ch.isdigit():
numeric_phone_number += ch
elif ch.upper() in 'ABC':
numeric_phone_number += '2'
elif ch.upper() in 'DEF':
numeric_phone_number += '3'
elif ch.upper() in 'GHI':
numeric_phone_number += '4'
elif ch.upper() in 'JKL':
numeric_phone_number += '5'
elif ch.upper() in 'MNO':
numeric_phone_number += '6'
elif ch.upper() in 'PQRS':
numeric_phone_number += '7'
elif ch.upper() in 'TUV':
numeric_phone_number += '8'
elif ch.upper() in 'WXYZ':
numeric_phone_number += '9'
else:
weird_character = True
if count != 2:
numeric_phone_number += '-'
count += 1
# Error message if non-alphanumeric character pops up
if weird_character:
print('\nSome weird characters showed up in the number that I don\'t know what to do with.')
# Otherwise, here's some numeric version of the phone number
else:
print ('\nThe phone number you entered is', numeric_phone_number + '.') | true |
44746aec5d7405051b68ec4f1ead570f57e57ce0 | tnovak123/hello-spring | /crypto/caesar.py | 567 | 4.1875 | 4 | from helpers import rotate_character, alphabet_position
def encrypt(text, rot):
newtext = ""
for char in text:
if char.isalpha() == True:
newtext += rotate_character(char, rot)
else:
newtext += char
return(newtext)
def main():
inputtext = ""
displace = 0
inputtext = input("What do you want to encrypt?")
displace = input("What encryption value do you want to use?")
if displace.isdigit() == True:
print(encrypt(inputtext, displace))
else:
pass
if __name__ == "__main__":
main() | true |
d6c30d2048e7e815b9550b05e2abe1966c7d4332 | probuse/prime_numbers | /prime_numbers_.py | 810 | 4.15625 | 4 | def prime_numbers(n):
"Generate prime numbers between 0 and n"
while isinstance(n, int) and n > 0:
prime = []
def is_prime(number):
"Tests if number is prime"
if number == 1 or number == 0:
return False
for num in range(2, number):
if number % num == 0:
return False
return True
def primes(num = 0):
"Generator function yielding prime numbers"
while True:
if is_prime(num): yield num
num += 1
for number in primes():
if number > n: break
prime.append(number)
return prime
raise TypeError('argument needs to be a positive integer')
#print prime_numbers(3)
| true |
2d195bd9e64a571692a80213e75beddf8235052c | ironboxer/leetcode | /python/214.py | 983 | 4.15625 | 4 | """
https://leetcode.com/problems/shortest-palindrome/
Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
Example 1:
Input: "aacecaaa"
Output: "aaacecaaa"
Example 2:
Input: "abcd"
Output: "dcbabcd"
"""
class Solution:
"""
KMP is good, but it's too complicated to understand
Also, if you try your best, you can do it.
"""
def shortestPalindrome(self, s: str) -> str:
r = s[::-1]
for i in range(len(s) + 1):
print(s, r[i:], s.startswith(r[i:]))
# 稍微想一下 其实很简单
# 就是一个简单的翻转对称
if s.startswith(r[i:]):
return r[:i] + s
if __name__ == '__main__':
print(Solution().shortestPalindrome("abcdefg"))
print(Solution().shortestPalindrome("aacecaaa"))
print(Solution().shortestPalindrome("abcd"))
| true |
bc509ad8e8375270c803a118c24746d45af97088 | ironboxer/leetcode | /python/49.py | 1,050 | 4.1875 | 4 | """
https://leetcode.com/problems/group-anagrams/
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Constraints:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] consists of lower-case English letters.
"""
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
from collections import defaultdict
dic = defaultdict(list)
for s in strs:
dic[''.join(sorted(s))].append(s)
return list(dic.values())
if __name__ == "__main__":
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
print(Solution().groupAnagrams(strs))
| true |
9b79ae5a9eaadcef2a1be81c479ca9675c0d3553 | ironboxer/leetcode | /python/231.py | 652 | 4.125 | 4 | """
https://leetcode.com/problems/power-of-two/
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
"""
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
for i in range(32):
v = 1 << i
if v == n:
return True
if v > n:
break
return False
if __name__ == '__main__':
print(Solution().isPowerOfTwo(1))
print(Solution().isPowerOfTwo(16))
print(Solution().isPowerOfTwo(218))
| true |
9e4fc7517fbe8fd3e2f9c68694b0692e5ad0eef4 | Steven4869/Simple-Python-Projects | /excercise21.py | 434 | 4.25 | 4 | #Amstrong number
print("Welcome to Amstrong number checker, if the number's sum is same as the sum of the cubes of respective digits then it is called Amstrong number")
a=int(input("Please enter your number\n"))
sum=0
temp=a
while(temp >0):
b=temp%10
sum+=b **3
temp//=10
if(a==sum):
print(a,"is an Amstrong number")
else:
print(a,"isn't an Amstrong number")
print("It's sum for the respective digits is", sum) | true |
a92a5371ecbf8a8b7e80695f1935ea44606983fb | davidholmes1999/first-project1 | /Holmes_numbergenerator.py | 892 | 4.15625 | 4 | #David Holmes
#3/9/17
#Number Simulator
#Print Statements
print("\nWeclome to the number simulator game! You will be seeing how many guesses it takes for you to guess my number!\n")
print("\nFirst let me think of a number between 1 and 100\n")
print("\nHmmmmmm...\n")
import random
#Defining Variables
player=int(input("\nI got it! Guess wisely, I can be a trickster! Now plesase type in a number between 1-100.\n"))
computer=random.randint(1,100)
#If Statements
x= 1
while player != computer:
if player>computer:
print("\nGuess lower...")
elif player<computer:
print("\nGuess higher...")
x= x+1
player= int(input("\nGuess again please...\n"))
#Outro Statement
print("\nYou guessed the number right! It took you", x, "attempts to guess it! Good job!\n")
#Input Statement
input("\n\nPress enter to continue")
| true |
fd74144669b2dfb6dd3ad08b4ad8f029d817b0d3 | Dexmo/pypy | /playground.py | 1,126 | 4.21875 | 4 | values = (1,2,3,4,5) #tuple - immutable, orderly data structure
squares = [value**2 for value in range(1,11)] #list comprehension
''' 3 short subprogram for quick work '''
print(max(values))
print(min(values))
print(sum(values))
print(squares)
'''---------------------------------------'''
for number in range(1, 21):
print(number)
# creating list with 1000 values
thousand_list = []
for number in range(1,1001):
thousand_list.append(number)
# creating list with odd numbers
odd_number = []
for number in range(1,20,2):
odd_number.append(number)
print(odd_number)
# creating the list with values to cube using list comprehension
cube_values = [value**3 for value in range(1,11)]
print(cube_values)
""" taking some part of list """
players = ['Mati', 'Kati', 'Pati', "Sati"]
print(players[2:]) #Only shows Pati and Sati
print(players[:2]) #Only shows Mati and Kati
new_players = players[:]
print(new_players)
""" TUPLE """
dimensions = (200, 50)
print("First dimension: " + str(dimensions[0]) + ", and second: " + str(dimensions[1]) +
".\nBecause dimensions are storage in tuple we cannot change it!") | true |
956fd0812e6565fa8f6843af933c225e7ae22a7c | emailman/Raspberry_Pi_Heater | /sorted grades/function demo.py | 647 | 4.15625 | 4 | def rectangle_calc(x, y):
area = x * y
perimeter = 2 * (x + y)
return area, perimeter
def main():
try:
length = float(input("Enter the length of a rectangle: "))
width = float(input("Enter the width of a rectangle: "))
units = input("Enter the units: ")
area_, perimeter_ = rectangle_calc(length, width)
print("length =", length, units, ", width =", width, units)
print("area = ", area_, "sq", units, ", perimeter = ",
perimeter_, units)
print(rectangle_calc(length, width))
except ValueError:
print("You messed up")
exit(1)
main()
| true |
39028abf4600601082d0c7f24f718739f5e77c3a | queenskid/MyCode | /labs/introfor/forloop2.py | 542 | 4.15625 | 4 | #!/usr/bin/env python3
# 2 seprate list of vendors
vendors = ['cisco', 'juniper', 'big_ip', 'f5', 'arista', 'alta3', 'zach', 'stuart']
approved_vendors = ['cisco', 'juniper', 'big_ip']
# for loop going through list of vendors and printing to screen with a conditional statement.
for x in vendors:
print("\nThe vendors is " + x, end="")
# if statement looking for vendors that are not in the approved vendor list.
if x not in approved_vendors:
print(" - NOT AN APPROVED VENDOR!", end="")
print("\nOur loop has ended.") | true |
bf40a829a9887f981a48f429835956a807d3cf03 | cowsertm1/Python-Assignments | /functions-and-collections.py | 2,974 | 4.6875 | 5 | """
As we saw in class, in Python arguments passed to a function are
treatedly differently depending on whether they are a "normal"
variable or a collection. In this file we will go over some additional
examples so that you get used to this behavior:
1. Write a program that assigns some value to a global variable called
"my_global_string".
Add to your program a function called "modify_string" that receives a
string as an argument. (Call the argument something like "string_arg",
eg.) Have that function try to set the string to a different value and
then return.
In your program, call that function, passing it my_global_string as an
argument, and then print out the value of my_global_string.
Observe what happens.
2. Repeat exercise one but for a number (integer) variable. Observe
what happens.
3. Write a program that creates a dictionary called 'peoples_ages'
mapping names to ages. Insert into the dictionary data for 3 people.
4. Add to that program a function called "modify_dictionary" that
takes a dictionary as an argument. (When defining the function, be
sure to name the argument something *other* than 'peoples_ages'.) In
that function,
(i) add a new element to the argument (e.g., "marisa" => 75)
(ii) modify the age of one of the people listed in peoples_ages
(iii) remove from the argument one element present in peoples_ages.
In your program, run that function and then print out the contents of
peoples_ages. Observe what happened. Which of the three changes made
within the function modify_dictionary to its argument were actually
being done on (the global collection) peoples_ages?
5. Add to that program a new function called "modify_dictionary_2"
that takes a dictionary as an argument. (As above, when defining the
function, be sure to name the argument something *other* than
'peoples_ages'. Below, and for the sake of clarity, I assumed the
argument is 'dic_passed_as_argument'.) In this function, to to "clear"
or "empty" the dictionary passed as an argument by assigning to it an
empty dictionary, e.g.:
dic_passed_as_argument = {}
As above, have your program execute this function and then print out
the dictionary peoples_ages. What happened?
6. Edit the function modify_dictionary_3 so that, rather than assigning
dic_passed_as_argument = {}
it instead calls
dic_passed_as_argument.clear()
Why did this work while our attempt in question 5 failed?
7. To really drive the point home, do a similar experiment with a list
and a set. See if they behave the same way as dictionaries.
===
So, as we see above Python lets your functions modify the arguments
passed to functions -- as long as those arguments are *collections*.
Does that mean you should do it? Nope. To keep your code clean and
easy to maintain, if your function wants to share some modified data
with the rest of your program, the way to do so is by having your
function *return* that modified data -- never by directly modifying
its arguments.
"""
| true |
0b9802a4b4ecc2823db5761773af068cad2d0e56 | davifelix5/design-patterns-python | /structurals/adapter/adapter.py | 2,102 | 4.3125 | 4 | """
Serve par ligar duas classes diferentes
"""
from abc import ABC, abstractmethod
class iGameControl(ABC):
@abstractmethod
def left(self) -> None: pass
@abstractmethod
def right(self) -> None: pass
@abstractmethod
def down(self) -> None: pass
@abstractmethod
def up(self) -> None: pass
class GameControl(iGameControl):
def left(self) -> None:
print('Moving left')
def right(self) -> None:
print('Moving right')
def down(self) -> None:
print('Moving down')
def up(self) -> None:
print('Moving up')
class NewGameControl:
def move_left(self) -> None:
print('Moving to the elft direction')
def move_right(self) -> None:
print('Moving to the right direction')
def move_down(self) -> None:
print('Moving to the down direction')
def move_up(self) -> None:
print('Moving to the up direction')
class GameControlAdapter(iGameControl, NewGameControl):
"""
Adaptador usando herança
"""
def left(self) -> None:
self.move_left()
def right(self) -> None:
self.move_right()
def down(self) -> None:
self.move_down()
def up(self) -> None:
self.move_up()
class GameControlAdapter2:
"""
Adaptador usando composição
"""
def __init__(self, adaptee: NewGameControl):
self.adaptee = NewGameControl()
def left(self) -> None:
self.adaptee.move_left()
def right(self) -> None:
self.adaptee.move_right()
def down(self) -> None:
self.adaptee.move_down()
def up(self) -> None:
self.adaptee.move_up()
if __name__ == "__main__":
control = GameControl()
new_control = GameControlAdapter()
new_control2 = GameControlAdapter2(new_control)
control.right()
control.up()
control.left()
control.down()
print()
new_control.right()
new_control.up()
new_control.left()
new_control.down()
print()
new_control2.right()
new_control2.up()
new_control2.left()
new_control2.down()
| true |
7bfd6160f69605ad5009e8baca3c065aa739b1d0 | joyrexus/nst | /misc/poset.py | 2,638 | 4.1875 | 4 | '''
In NST Sect 14 (p. 57) Halmos gives three examples of partially ordered sets
with amusing properties to illustrate the various possibilities in their
behavior.
Here we aim to define less_than functions for each example. Each function
should return a negative value if its first argument is "less than" its
second, 0 if the two arguments are "equal", and a positive value otherwise.
'''
from __future__ import division
from random import shuffle
ii_unordered = set()
iii_unordered = set()
def i_less_than(M, N):
(a, b) = M
(x, y) = N
p = ((2 * a) + 1) * (2 ** y)
q = ((2 * x) + 1) * (2 ** b)
if p <= q:
print "Defined for {} since {} <= {}".format((M, N), p, q)
return True
else:
print "Undefined for {} since {} > {}".format((M, N), p, q)
# ordering for relation ii:
# a < x or (a == x and (b < y or b == y)
# (a < x or a == x) and (a < x and (b < y or b == y))
#
# ordering for relation iii:
# (a < x or a == x) and (b < y or b == y)
def ii_less_than(M, N):
'''
Compare two 2-tuples based on lexicographic order.
'''
(a, b) = M
(x, y) = N
if a < x:
return True
elif a == x and (b < y or b == y):
return True
def iii_less_than(M, N):
'''
Compare two 2-tuples based on present order.
Note that unlike lexicographic order, if the first
element of the first 2-tuple is not less than or equal
to the first element of the second 2-tuple, we do not
evaluate the order between the tuples at all.
'''
(a, b) = M
(x, y) = N
if (a < x or a == x) and (b < y or b == y):
return True
X = [(a, b) for a in range(10) for b in range(10)]
for a, b in X:
M = (a, b+1)
N = (a, b)
i_less_than(M, N)
# create a shuffled list of 2-tuples
X = [(a, b) for a in range(10) for b in range(10)]
shuffle(X)
S = [(M, N) for M in X for N in X if ii_less_than(M, N)] # the relation S
T = [(M, N) for M in X for N in X if iii_less_than(M, N)] # the relation T
print "S:", len(S)
print "T:", len(T)
print list(set(S) - set(T))[:10]
'''
print sorted(X, cmp=i_less_than)
print
print sorted(X, cmp=ii_less_than)
print
print sorted(X, cmp=iii_less_than)
'''
print '-' * 30
print ii_unordered ^ iii_unordered
'''
Another poset example.
See p. 57 of NST where Halmos describes three partially-ordered sets "with some
amusing properties."
'''
def z(x, y):
return (2*x + 1) / 2**y
def z_over(a, b):
for x in range(a, b):
print
print "x ==", x
for y in range(a, b):
print " z({}, {}) == {}".format(x, y, z(x, y))
z_over(-2, 3)
| true |
8be7ea60b1cd7f0ce2ab030b7d25c63b257a686a | MarcusGraetsch/awsrestart | /Exercise_1_ConvertHourintoSeconds.py | 295 | 4.34375 | 4 | hours = input("How many hours to you want to convert into seconds? ")
hours = int(hours)
seconds = hours*3600
print("{} hours are {} seconds!".format(hours, seconds))
print("Now with usage of a function")
def convert_hours (hrs):
sec = hrs * 3600
print(f"{hrs} are {sec}")
convert_hours(8) | true |
eccc6cac4824435c77a7d706f555976b788e7446 | thinkingape46/Full-Stack-Web-Technologies | /Python/regular_expressions.py | 798 | 4.28125 | 4 | # Regular expressions
# Import regular expressions
import re
# mytext = "I am from Earth"
# USING REGULAR EXPRESSIONS TO FIND THE MATCH
# if re.search("Earth", mytext):
# print("MATCH found")
# else:
# print("MATCH not found")
# x = re.search("Earth", mytext)
# FIND THE START AND END INDEX OF THE MATCH
# print(x)
# print(type(x))
# print(x.start())
# print(x.end())
# USING REGULAR EXPRESSION TO SPLIT THE STRING.
# REMEMBER THAT THIS METHOD IS ALREADY BUILT INTO STRINGS.
# split_term = "@"
# email = "hello@gmail.com"
# output = re.split(split_term, email)
# print(output)
# FIND ALL INSTANCES OF THE MATCH.
# my_text = "the cat can walk like a cat, what else a cat can do?"
# x = re.findall("cat", my_text)
# print(x)
# You len() method to find the number of instances
# Meta | true |
0f76462a6eca506d11f58d6f1314a1a175ddfd5f | AdamJSoftware/iti1120 | /assignments/A2/a2_part2_300166171.py | 1,935 | 4.21875 | 4 | # Family name: Adam Jasniewicz
# Student number: 300166171
# Course: ITI 1120
# Assignment Number 2
# year 2020
########################
# Question 2.1
########################
def min_enclosing_rectangle(radius, x, y):
'''
(Number, Number, Number) -> (Number, Number)
Description: Calculates the x and y-coordinates of the bottom left corner of the smallest axis-aligned rectangle that could contain the circle
Preconditions: All 3 numbers are real numbers (if radius is negative function will return none)
'''
if radius < 0:
return None
return (x-radius, y-radius)
########################
# Question 2.2
########################
def vote_percentage(results):
'''
(string) -> Number
Description: Calculates the percentage of yes in the paramater results among all other substrings (yes, no and abastained (abstained does not count towards the percentage, it is ignored)
Preconditions: Results only contains yes,no or abstained and at least one yes or no
'''
if(results.count('no') == 0):
return 1
if(results.count('yes') == 0):
return 0
yes = results.count('yes')
no = results.count('no')
return yes/(yes+no)
########################
# Question 2.3
########################
def vote():
'''
(None) -> None
Description: Invokes the user to enter a string of yes', no's and abastained's, after it prints if the vote is unanimous, a super majority, simple majority or if it fails
Preconditions: Input contains only yes', no's and abastains
'''
result = vote_percentage(
input("Enter the yes, no, abstained votes one by one and then press enter: "))
if result == 1:
print("proposal passes unanimously")
elif result >= 2/3:
print("proposal passes with super majority")
elif result >= .5:
print("proposal passes with simple majority")
else:
print("proposal fails")
| true |
7f2c16d15d19183ceabdbcd7ea311bc4f4c27838 | ph4ge/ost-python | /python1_Lesson06/src/word_frequency.py | 456 | 4.125 | 4 | """Count the number of different words in a text."""
text = """\
Baa, baa, black sheep,
Have you any wool?
Yes sir, yes sir,
Three bags full;
One for the master,
And one for the dame,
And one for the little boy
Who lives down the lane."""
for punc in ",?;.":
text = text.replace(punc, "")
freq = {}
for word in text.lower().split():
freq[word] = freq.get(word, 0)+1
for word in sorted(freq.keys()):
print(word, freq[word])
| true |
17e0981af5496c8fe8a3c05e7d2ef15b2681064e | Benkimeric/number-game | /number_guess.py | 863 | 4.1875 | 4 | import random
def main():
global randomNumber
randomNumber = random.randrange(1, 101)
# print(randomNumber)
number = int(input("I have generated a Random number between 1 and 100, please guess it: "))
guess(number)
# guess method with while loop to loop when user does not give correct guess
def guess(number1):
correct = False
while correct is False:
if number1 > randomNumber:
print("That is high. Try again with a lower number.")
elif number1 < randomNumber:
print("That is too low. Try again with a larger one.")
elif number1 == randomNumber:
print("Congratulations! You guessed it")
break
number1 = int(input("Guess again? Type your guess here: "))
# calling main method to run the guess method as well as generate first random number
main()
| true |
63c90181fe378d9bb9093d8395ba0f1f147daf26 | shwesinhtay111/Python-Study-Step1 | /list.py | 1,501 | 4.53125 | 5 | # Create list
my_list = [1, 2, 3]
print(my_list)
# lists can actually hold different object types
my_list = ['A string', 23, 100.22, 'o']
print(my_list)
# len() function will tell you how many items are in the sequence of the list
print(len(my_list))
# Indexing and Slicing
my_list = ['one','two','three',4,5]
print(my_list[0])
print(my_list[:3])
new_list = my_list + ['new item']
print(new_list)
# use the * for a duplication method similar to strings
print(new_list*2)
# Basic List Methods
list1 = [1, 2, 3]
list1.append('append me!')
print(list1)
# Use pop to "pop off" an item from the list
list1.pop(0)
print(list1)
# Assign the popped element, remember default popped index is -1
popped_item = list1.pop()
print(popped_item)
# use the sort method and the reverse methods to also effect your lists
new_list = ['a','b','x','b','c']
# Use reverse to reverse order (this is permanent!)
new_list.reverse()
print(new_list)
# Use sort to sort the list (in this case alphabetical order, but for numbers it will go ascending)
new_list.sort()
print(new_list)
# Nesting Lists
# Let's make three lists
lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]
# Make a list of lists to form a matrix
matrix = [lst_1,lst_2,lst_3]
print(matrix)
# Grab first item in matrix object
matrix[0]
# Grab first item of the first item in the matrix object
matrix[0][0]
# List Comprehensions
# Build a list comprehension by deconstructing a for loop within a []
first_col = [row[0] for row in matrix]
print(first_col)
| true |
723cfd942791ed9266f240781f58118cb30ddea9 | shwesinhtay111/Python-Study-Step1 | /abstract_class.py | 1,280 | 4.6875 | 5 | # abstract class is one that never expects to be instantiated. For example, we will never have an Animal object, only Dog and Cat objects, although Dogs and Cats are derived from Animals
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def speak(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal):
def speak(self):
return self.name+' says Woof!'
class Cat(Animal):
def speak(self):
return self.name+' says Meow!'
fido = Dog('Fido')
isis = Cat('Isis')
print(fido.speak())
print(isis.speak())
# Special Methods- __init__(), __str__(), __len__() and __del__() methods
class Book:
def __init__(self, title, author, pages):
print("A book is created")
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return "Title: %s, author: %s, pages: %s" %(self.title, self.author, self.pages)
def __len__(self):
return self.pages
def __del__(self):
print("A book is destroyed")
book = Book("Python Rocks!", "Jose Portilla", 159)
#Special Methods Usage
print(book)
print(len(book))
del book | true |
3d20fa99eae7df1270b21c6a08bd3cc5d6adb375 | ocmadin/molssi_devops | /util.py | 694 | 4.4375 | 4 | """
util.py
A file containing utility functions.
"""
def title_case(sentence):
"""
Convert a string into title case.
Title case means that the first letter of each word is capitalized with all other letter lower case
Parameters
----------
sentence : str
String to be converted into title case.
Returns
-------
title : str
String in title case format.
Example
-------
>>> title_case("ThiS iS a STriNG To bE coNVERTed")
'This Is A String To Be Converted'
"""
words = sentence.split()
title = ""
for word in words:
title = title + word[0].upper() + word[1:].lower() + " "
return title
| true |
12f4625a421f85e40f4ab2700795fceb8e53acad | TLTerry23/CS30practice | /CS_Solutions/Thonnysolutions/3.3.2Area_of_figures.py | 791 | 4.4375 | 4 | # Area Calculator
# Put Your Name Here
# Put the Date Here
choice=input("What do you want to find the area of? Choose 1 for rectangle, 2 for circle, or 3 for triangle.")
if choice=='1':
rectangle_width=float(input("What is the width of your rectangle?"))
rectangle_height=float(input("What is the length of your rectangle?"))
print("The area of your rectangle is", rectangle_width*rectangle_height)
elif choice=='2':
circle_radius=float(input("What is the radius of your circle?"))
print("The area of your circle is", circle_radius*3.14**2)
else:
triangle_base=float(input("What is the base of your triangle?"))
triangle_height=float(input("What is the height of your triangle?"))
print("The area of your triangle is", 0.5*triangle_base*triangle_height)
| true |
a2781049e4ac8d2f94355326498919ad5501cd25 | brettmadrid/Algorithms | /recipe_batches/recipe_batches.py | 1,409 | 4.25 | 4 | #!/usr/bin/python
import math
def recipe_batches(recipe, ingredients):
batches = math.inf
'''
First check to see if there are enough ingredients to satisfy the recipe requirements
'''
if len(recipe) > len(ingredients):
return 0
'''
Now check to see if there are enough of each ingredient in the ingredients dictionary. Since the ingredient order is the same in both dictionaries, we can compare the index values for each against each other
'''
for i in recipe:
if ingredients[i] < recipe[i]: # if not enough ingredients
return 0
# calc batches that can be made for each ingredient
batch_calc = ingredients[i] // recipe[i]
# store lowest value of batches possible after each ingredient check
if batch_calc < batches:
batches = batch_calc
return batches
# print(recipe_batches({ 'milk': 100, 'butter': 50, 'cheese': 10 }, { 'milk': 200, 'butter': 100, 'cheese': 10 }))
if __name__ == '__main__':
# Change the entries of these dictionaries to test
# your implementation with different inputs
recipe = {'milk': 100, 'butter': 50, 'flour': 5}
ingredients = {'milk': 132, 'butter': 48, 'flour': 51}
print("{batches} batches can be made from the available ingredients: {ingredients}.".format(
batches=recipe_batches(recipe, ingredients), ingredients=ingredients))
| true |
f8fa6b77b71bd50acf2cbddeff370e0b2709d3bf | barvaliyavishal/DataStructure | /Cracking the Coding Interview Exercises/Linked Lists/SinglyLinkedList/RemoveDups.py | 741 | 4.3125 | 4 | from LinkedList import LinkedList
class RemoveDuplicates:
# Remove duplicates Using O(n)
def removeDuplicates(self, h):
if h is None:
return
current = h
seen = set([current.data])
while current.next:
if current.next.data in seen:
current.next = current.next.next
else:
seen.add(current.next.data)
current = current.next
obj = LinkedList()
obj.add(1)
obj.add(2)
obj.add(3)
obj.add(3)
obj.add(4)
obj.add(5)
obj.add(7)
obj.add(9)
obj.add(9)
obj.add(2)
print("Before Removing Duplicates")
obj.show()
obj1 = RemoveDuplicates()
obj1.removeDuplicates(obj.head)
print()
print("After Removing Duplicates")
obj.show()
| true |
983b106ab6e4e093ee330866707bd6e35b7df3da | barvaliyavishal/DataStructure | /Cracking the Coding Interview Exercises/Linked Lists/SinglyLinkedList/removeDuplicates.py | 766 | 4.25 | 4 | from LinkedList import LinkedList
class RemoveDuplicates:
# Remove duplicates Using O(n^2)
def removeDuplicates(self, head):
if head.data is None:
return
temp = head
while temp.next:
start = temp
while start.next:
if start.next.data == temp.data:
start.next = start.next.next
else:
start = start.next
temp = temp.next
obj = LinkedList()
obj.add(1)
obj.add(2)
obj.add(3)
obj.add(3)
obj.add(4)
obj.add(5)
obj.add(7)
obj.add(9)
obj.add(2)
obj.add(2)
print("Before Removing Duplicates")
obj.show()
obj1 = RemoveDuplicates()
obj1.removeDuplicates(obj.head)
print()
print("After Removing Duplicates")
obj.show()
| true |
923aafcb9147d70e62d8512fabb477b5a8365a5e | garciaha/DE_daily_challenges | /2020-08-13/eadibitan.py | 1,788 | 4.15625 | 4 | """Eadibitan
You're creating a conlang called Eadibitan. But you're too lazy to come up with your own phonology,
grammar and orthography. So you've decided to automatize the proccess.
Write a function that translates an English word into Eadibitan.
English syllables should be analysed according to the following rules:
- Syllables will follow the pattern (C)(C)V(V(V))(C), where C is a consonant and V is a vowel.
Parentheses indicate that an element is optional.
- The pattern CVCV will be analyzed as CV-CV.
- The pattern CVCCV will be analyzed as CVC-CV
- The pattern CVCCCV will be analyzed as CVC-CCV
- Two or three consecutive vowels will always form a diphthong and a triphthong respectively.
Meaning they will be grouped in the same syllable.
- A y should be analyzed as a consonant if followed by a vowel, and as a vowel otherwise.
The order of the letters of each syllable should be altered according to the following table:
English Eadibitan
c1 v1 v1 c1
c1 v1 v2 v1 c1 v2
c1 v1 v2 v3 v1 c1 v2 v3
c1 v1 c2 v1 c1 c2
c1 v1 v2 c2 v1 c1 v2 c2
c1 v1 v2 v3 c2 v1 c1 v2 v3 c2
c1 c2 v1 c2 v1 c1
c1 c2 v1 v2 c2 v1 c1 v2
c1 c2 v1 v2 v3 c2 v1 c1 v2 v3
c1 c2 v1 c3 c2 v1 c1 c3
c1 c2 v1 v2 c3 c2 v1 c1 v2 c3
c1 c2 v1 v2 v3 c3 c2 v1 c1 v2 v3 c3
Any other pattern should be left untouched.
Notes:
- You can expect only lower case single words as arguments.
- Bonus: Try to solve it using RegEx.
"""
def eadibitan(word):
pass
if __name__ == "__main__":
assert eadibitan("edabitian") == "eadibitan"
assert eadibitan("star") == "tasr"
assert eadibitan("beautiful") == "ebauitufl"
assert eadibitan("statistically") == "tasittisaclyl"
print("All cases passed!")
| true |
85051a8cef826a0fb73dfc66172c8f588dc3433f | garciaha/DE_daily_challenges | /2020-07-09/maximize.py | 1,015 | 4.1875 | 4 | """ Maximize
Write a function that makes the first number as large as possible by swapping out its digits for digits in the second number.
To illustrate:
max_possible(9328, 456) -> 9658
# 9658 is the largest possible number built from swaps from 456.
# 3 replaced with 6 and 2 replaced with 5.
Each digit in the second number can only be used once.
Zero to all digits in the second number may be used.
"""
def max_possible(num_1, num_2):
num1_list = [int(x) for x in str(num_1)]
num2_sort = sorted([int(x) for x in str(num_2)], reverse = True)
index = 0
for x in range(len(num1_list)):
if num2_sort[index] > num1_list[x]:
num1_list[x] = num2_sort[index]
index += 1
if index >= len(num2_sort):
break
return int("".join([str(x) for x in num1_list]))
if __name__ == '__main__':
assert max_possible(523, 76) == 763
assert max_possible(9132, 5564) == 9655
assert max_possible(8732, 91255) == 9755
print("All cases passed!")
| true |
736a16c6c9f13efd689a4449c5bdaef22d1d96fc | garciaha/DE_daily_challenges | /2020-08-03/unravel.py | 641 | 4.4375 | 4 | """Unravel all the Possibilities
Write a function that takes in a string and returns all possible combinations. Return the final result in alphabetical order.
Examples
unravel("a[b|c]") -> ["ab", "ac"]
Notes
Think of each element in every block (e.g. [a|b|c]) as a fork in the road.
"""
def unravel(string):
pass
if __name__ == "__main__":
assert unravel("a[b|c]de[f|g]") == ["abdef", "acdef", "abdeg", "acdeg"]
assert unravel("a[b]c[d]") == ["abcd"]
assert unravel("a[b|c|d|e]f") == ["abf", "acf", "adf", "aef"]
assert unravel("apple [pear|grape]") == ["apple pear", "apple grape"]
print("All cases passed!")
| true |
8cd9783dc602893f32c52a2c4c2e21952662def3 | garciaha/DE_daily_challenges | /2020-07-22/connect.py | 1,742 | 4.28125 | 4 | """Connecting Words
Write a function that connects each previous word to the next word by the shared
letters. Return the resulting string (removing duplicate characters in the overlap)
and the minimum number of shared letters across all pairs of strings.
Examples
connect(["oven", "envier", "erase", "serious"]) -> ["ovenvieraserious", 2]
connect(["move", "over", "very"]) -> ["movery", 3]
connect(["to", "ops", "psy", "syllable"]) -> ["topsyllable", 1]
# "to" and "ops" share "o" (1)
# "ops" and "psy" share "ps" (2)
# "psy" and "syllable" share "sy" (2)
# the minimum overlap is 1
connect(["aaa", "bbb", "ccc", "ddd"]) -> ["aaabbbcccddd", 0]
Notes
More specifically, look at the overlap between the previous words ending letters and the next word's beginning letters.
"""
def connect(words):
shared = []
connected = words[0]
for x in range(1, len(words)):
start = words[x][0]
end = words[x-1][-1]
last = words[x-1][::-1]
spos = last.find(start)
epos = words[x].find(end)
if start in words[x-1] and end in words[x] and last[:spos+1][::-1] == words[x][:epos+1]:
shared.append(epos+1)
connected += words[x][epos+1:]
else:
shared.append(0)
connected += words[x]
return [connected, min(shared)]
if __name__ == '__main__':
assert connect(["oven", "envier", "erase", "serious"]) == [
"ovenvieraserious", 2]
assert connect(["move", "over", "very"]) == ["movery", 3]
assert connect(["to", "ops", "psy", "syllable"]) == ["topsyllable", 1]
assert connect(["silver", "version", "onerous", "usa", "apple", "please"]) == [
"silversionerousapplease", 1]
print("All cases passed!")
| true |
79b243b7c8dc4a887e111dac8b620adb5db55420 | garciaha/DE_daily_challenges | /2020-09-09/all_explode.py | 1,679 | 4.21875 | 4 | """Chain Reaction (Part 1)
In this challenge you will be given a rectangular list representing a "map" with
three types of spaces:
- "+" bombs: When activated, their explosion activates any bombs directly above,
below, left, or right of the "+" bomb.
- "x" bombs: When activated, their explosion activates any bombs placed in any
of the four diagonal directions next to the "x" bomb.
- Empty spaces "0".
Consider the grid:
[
["+", "+", "0", "x", "x", "+", "0"],
["0", "+", "+", "x", "0", "+", "x"]
]
If the top left "+" bomb explodes, the resulting chain reaction will blow up
bombs in the order given by the numbers below:
[
["1", "2", "0", "x", "6", "8", "0"],
["0", "3", "4", "5", "0", "7", "8"]
]
Note that there are two 8's since two of the bombs explode at the same time.
Also, note that one of the "x" bombs in the top row does not explode.
Write a function that determines if the chain reaction started when the top left
bomb explodes destroys all bombs or not.
Notes
Both "+" and "x" bombs have an "explosion range" of 1.
"""
def all_explode(bombs):
pass
if __name__ == "__main__":
assert all_explode([
["+", "+", "+", "+", "+", "+", "x"]
]) == True
assert all_explode([
["+", "+", "+", "+", "+", "0", "x"]
]) == False
assert all_explode([
["+", "+", "0", "x", "x", "+", "0"],
["0", "+", "+", "x", "0", "+", "x"]
]) == False
assert all_explode([
["x", "0", "0"],
["0", "0", "0"],
["0", "0", "x"]
]) == False
assert all_explode([
["x", "0", "x"],
["0", "x", "0"],
["x", "0", "x"]
]) == True
print("All cases passed!")
| true |
381007913bcd073e5a1aa745b00ea030fe371b84 | sandeepvura/Mathematical-Operators | /main.py | 538 | 4.25 | 4 | print(int(3 * 3 + 3 / 3 - 3))
# b = print(int(a))
**Mathematical Operators**
```
###Adding two numbers
2 + 2
### Multiplication
3 * 2
### Subtraction
4 - 2
### Division
6 / 3
### Exponential
When you want to raise a number
2 ** 2 = 4
2 ** 3 = 8
```
***Note:*** Order of Mathematical operators to execute is like "PEMDAS"
P - Parentheses - ()
E - Exponents - **
M - Multiplication - *
D - Division - /
A - Addition - +
S - Subtraction -
*Example* : Rule of PEMDAS
```
print( 3 * 3 + 3 / 3 - 3) #Find the output.
``` | true |
44c3662bac6085bd63fcb52a666c2e81e5a683ff | farhadkpx/Python_Codes_Short | /list.py | 1,689 | 4.15625 | 4 |
#list
# mutable, multiple data type, un-ordered
lis = [1,2,3,4,5,6,7,8,9] #nos
lis2 = ['atul','manju','rochan'] #strings
lis3 = [1,'This',2,'me','there'] #both
#create empty list
lis4 = [] #empty
lis5 = list() #empty
#traversl
for item in lis:
print (item),
#slicing
print (lis[:],lis[2:3],lis[3:])
#Mutable
lis[5] ='Singh'
print (lis)
print (lis2)
#addition using + operator only for single element
lis2 = lis2 + ['manju']
#to concatenate using append only single element
lis2.append('newval')
print (lis2)
#for more values addition to the list
lis2.extend(['one','two'])
print (lis2)
#addition of elements in a specified place in the list
lis2.insert(5,'fifth')
print (lis2)
#list inside an other list
#lis2.insert(0,['start','element'])
print (lis2)
#accessing list inside the list
print(lis2[0][0]) #prints 'start'
print(lis2[0][1]) #prints 'element'
#removing the elements from the list
#pop
lis2.pop() #removes the last element always
print (lis2)
lis2.pop()
print (lis2)
rval1=lis2.pop()
rval2=lis2.pop()
print (lis2)
print (rval1,rval2)
print (len(lis2)) #0,13
# index or indicies deletion - del(not returned deleted elements)
del lis2[1]
print (lis2)
#range to delete
del lis2[1:3]
print (lis2)
#delete the element by values
lis2.append('three')
print(lis2)
lis2.remove('three')
print (lis2)
lis2.append('one')
lis2.append('two')
lis2.append('three')
#sort the list
lis2.sort()
print (lis2)
#lis.sort(reverse=True)
print (lis2)
Name = 'manjunath manikumar'
name_list = list(Name)
print (name_list)
#split
word_list = Name.split()
print (word_list)
#alias
print (lis3)
alias3 = lis3
print (alias3)
alias3[2] = 'changed'
print (lis3)
print (alias3) #alias
| true |
28ec5060a74ff5c0e0f62742317d22266a5f41a2 | sadieBoBadie/feb-python-2021 | /Week1/Day2/OOP/intro_OOP.py | 2,111 | 4.46875 | 4 | #1.
# OOP:
# Object Oriented Programming
# Style of programming uses a blueprint for modeling data
# Blueprint defined by the programmer -- DIY datatypes
# -- customize it for your situation
# Modularizing
# 2:
# What is CLASS:
# User/Programmer defined data-type
# Like a function is a recipe --- class is blueprint for the datatype
# 3. What are...
# Attributes/properties
# Characteristics -- variables that belong to the class
# What a class of objects HAS --> data
#ex: car
# -- model -- string (corolla)
# -- make -- string (toyota)
# JS: my_arr = [3, 4, 5]
# console.log( my_arr.length )
# Methods
# Functions that often affect the properties of the class
# Functions that belong to the class --
# What a class of objects can DO --> actions/functions
my_list = [3, 4, 5]
my_list.append(8) # --> [3, 4, 5, 8]
# Quiz Challenge:
# self.store = store
# self.items.append(item)
# def add_item(self, item, price):
# self.items = []
# def __init__(self, store):
# class ShoppingCart:
# return self
# self.total = 0
# self.total += price
class ShoppingCart:
def __init__(self, specific_store):
self.total = 0
self.store = specific_store
self.items = []
def add_item(self, thing, price):
self.total += price
self.items.append(thing)
return self
def show_cart(self):
print(f"Store: {self.store}, total: {self.total}")
print(f"Items: {self.items}")
sadie_shopping_cart = ShoppingCart("Safeway")
print(sadie_shopping_cart)
print(sadie_shopping_cart.store)
nate_cart = ShoppingCart("Target")
print(nate_cart)
print(nate_cart.store)
nate_cart.store = "Amazon"
nate_cart.items.append("apples")
nate_cart.total += 3.00
nate_cart.add_item("apples", 3.00)
nate_cart.add_item("pears", 3.00)
nate_cart.add_item("broccoli", 5.00)
# nate_cart.items.append("mango")
# nate_cart.total += 5.0
# nate_cart.show_cart()
# sadie_shopping_cart.show_cart()
# nate_cart.add_item("Star Wars Figurine", 50.00)
# nate_cart.add_item("apple", 0.99)
| true |
36c9bac791ef0ee4aba78e32851a4fcb6756fafb | Lawlietgit/Python_reviews | /review.py | 2,202 | 4.15625 | 4 | # 4 basic python data types:
# string, boolean, int, float
# str(), bool(), int(), float()
# bool("False") --> True
# bool("") --> False
# bool(10.2351236) --> True
# bool(0.0) --> False
# bool(object/[1,2,3]) --> True
# bool([]) --> False
# bool(None) --> False
# FIFO --> queue data structure
# LIFO --> stack
a = [1,2,3]
# queue:
for _ in range(len(a)):
print(a.pop(0))
print(a)
a = [1,2,3]
# while len(a) > 0:
while a:
print(a.pop(0))
print(a)
# stack:
a = [1,2,3]
while a:
print(a.pop())
print(a)
# class/objects (scalable/extensible)
# e.g. build a system for a library
# people can register as a user/member
# members can check-out and return books
# books should be classified by generics
class Books:
attrs: cost/n_stocks/popularity/theme
methods:
#class MusicBooks(Books):
# attrs:
class Users:
attrs: member_id(KEY)/account balance/age/email/dob/name
methods: check_out(book)/return_book(book)
# time complexity (big O notation)
# space complexity (big O notation)
# 2 types of problems:
# P - Polynomial (O(N), O(N^2), O(N^p))
# NP - not possible for Poly time
# NP - problem itself cannot be solved in P, but verifying the problem takes P
# NP hard - verifying it takes more than P (postman)
# A
# B
# C
# A B C
#A 0 21
#B 21 0 40
#C 40 0
# A - B --> 21 km
# B - C --> 40 km ...
# A --> A search for the best route (shortest total distance) to connect all the towns,
# and return to A.
# loop (keep visiting a town many times)
# N --> infinity
# O(a*N^c + b) a, b, c are constants --> O(N^c)
# dictionary/sets
# visit element time O(1)
# a = [1,2,3, 3,3,3,3,3], a[0]
# check if 3 is in a:
# a_set = {1,2,3}
# check if 3 is in a set:
# in a set, the elements have to be unique
# a set can be used as the key set for a dictionary
# a_dic = {0:2, 1:2} k:v a_dic[0] -->2
"""
print(3 in a) --> True O(N)
print(3 in a_set) --> True O(1)
a_lis.append(), .remove(), .pop(), .insert()
a_set.add(), .remove()
a_dic[new_key] = new_value, a_dic.remove(key)
"""
| true |
4fd15d3e74cb6ea719d26bf9f30704f5f7c7de7b | mfcust/sorting | /sorting.py | 2,274 | 4.53125 | 5 | # 1) Run the code in the markdown and write a comment about what happens.
# 2) Try to print(sorted(my_list2)) and print(my_list2.sort()). Is there a difference? What do you observe?
my_list2 = [1,4,10,9,8,300,20,21,21,46,52]
# 3) Let's say you wanted to sort your list but in reverse order. To do this, you can put reverse=True inside the parentheses (for either sort() or sorted().
# Try it below, and then print your reverse sorted list!
my_list3 = [1,4,10,9,8,300,20,21,21,46,52]
# 4) But Mr. Custance, to this point all I've been sorting are lists with integer values inside. How does .sort() and sorted() organize string values?
# Sort the following list, print it and comment on how it was sorted:
word_list = ["pizza", "frog", "lemon", "lemon", "computer", "water bottle", "lamp", "table", "radio", "speaker"]
# 5) Do the same for the following list:
word_list2 = ["lamb", "lap", "lalalala", "laaaa", "larynx", "laguardia", "laproscopy", "lad"]
# 6) How does the .sort() method and sorted function deal with lists that have multiple data types? Create a list that has integers, strings and floats. Sort and print, and then comment on the results.
# 7) Let's say you wanted to sort a list based purely on length of characters. You can define a function that returns the length of an item, and then use
# that as the key for your sort. For example:
'''
def len_func(a):
return(len(a))
length_list = ["aaaaaaa", "aaaaa", "aaa", "a", "aaaaaaaaaaaaaaa", "aa", "aaaaaaaaaa", "", "aaaaaaaaaaaaaaaaaaa", "aaaaa", "aaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaa", " ", "bcbcbdhbb", "dibvibfv", "a"]
'''
#Uncomment the code above, and sort it using either sort() or sorted(). When you do, in the parentheses include key = len_func. This makes the key based on the function you've defined
#Print your new list below
# 8) Print the list from the previous question, but in reverse length order.
# 9) Can .sort() and sorted() be used to sort the chracters in a string? Try it below and comment.
###Bonus###
# 1) Write a program that populates an empty list with 100 random numbers between a minumum and maximum of your choice. Then, sort your new list from smallest to biggest and print your newly sorted list.
| true |
5b9dff75a516f758e8e8aef83cf89794176b488b | Mukilavan/LinkedList | /prblm.py | 880 | 4.21875 | 4 | #Write a Python program to find the size of a singly linked list.
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class linkedList:
def __init__(self):
self.head = None
def insert_beg(self, data):
node = Node(data, self.head)
self.head = node
def insert_end(self, data):
if self.head is None:
self.insert_beg(data)
return
itr = self.head
while itr.next:
itr = itr.next
itr.next = Node(data)
def list_size(self):
itr = self.head
count = 0
while itr:
count += 1
itr = itr.next
return count
if __name__ == '__main__':
ll = linkedList()
ll.insert_beg(20)
ll.insert_beg(20)
ll.insert_end(50)
print(ll.list_size())
| true |
50042e3c7051ee2be4a19e9d4f858a22a7be88f7 | clarkjoypesco/pythoncapitalname | /capitalname.py | 332 | 4.25 | 4 | # Write Python code that prints out Clark Joy (with a capital C and J),
# given the definition of z below.
z = 'xclarkjoy'
name1 = z[1:6]
name1 = name1.upper()
name1 = name1.title()
name2 = z[-3:]
name2 = name2.upper()
name2 = name2.title()
print name1 + ' ' + name2
s = "any string"
print s[:3] + s[3:]
print s[0:]
print s[:] | true |
ee8a14b46db017786571c81da934f06a614b3553 | Jamsheeda-K/J3L | /notebooks/lutz/supermarket_start.py | 1,724 | 4.3125 | 4 | """
Start with this to implement the supermarket simulator.
"""
import numpy as np
import pandas as pd
class Customer:
'''a single customer that can move from one state to another'''
def __init__(self, id, initial_state):
self.id = id
self.state = initial_state
def __repr__(self):
return f'Supermarket with {len(self.customers)} customers'
def next_state(self):
pass
def is_active(self):
pass
class Supermarket:
"""manages multiple Customer instances that are currently in the market.
"""
def __init__(self):
# a list of Customer objects
self.customers = []
self.minutes = 0
self.last_id = 0
def __repr__(self):
pass
def get_time():
"""current time in HH:MM format,
"""
def print_customers():
"""print all customers with the current time and id in CSV format.
"""
def next_minute():
"""propagates all customers to the next state.
"""
#increase the time of the supermarket by one minute
lidl.next_minute
def add_new_customers():
"""randomly creates new customers.
"""
def remove_exitsting_customers():
"""removes every customer that is not active any more.
"""
# start a simulation
if __name__ == '__main__':
# this code executed when we run the file python supermarket.py
lidl = Supermarket()
print(lidl)
lidl.next_minute()
#for every customer determine their next state
#remove churned customers from the supermarket
lidl.remove_exitsting_customers()
#generate new customers at their initial location
#repeat from step 1 | true |
7c61f608b0278498c5bac3c8c2833d827754f124 | lynnxlmiao/Coursera | /Python for Everybody/Using Database with Python/Assignments/Counting Organizations/emaildb.py | 2,686 | 4.5 | 4 | """PROBLEM DESCRIPTION:
COUNTING ORGANIZATIONS
This application will read the mailbox data (mbox.txt) count up the number email
messages per organization (i.e. domain name of the email address) using a database
with the following schema to maintain the counts:
CREATE TABLE Counts (org TEXT, count INTEGER)
When you have run the program on mbox.txt upload the resulting database file
above for grading. If you run the program multiple times in testing or with dfferent files, make
sure to empty out the data before each run.
You can use this code as a starting point for your application:
http://www.pythonlearn.com/code/emaildb.py.
The data file for this application is the same as in previous assignments:
http://www.pythonlearn.com/code/mbox.txt.
Because the sample code is using an UPDATE statement and committing the results
to the database as each record is read in the loop, it might take as long as a
Few minutes to process all the data. The commit insists on completely writing
all the data to disk every time it is called.
The program can be speeded up greatly by moving the commit operation outside of
the loop. In any database program, there is a balance between the number of
operations you execute between commits and the importance of not losing the
results of operations that have not yet been committed.
"""
import sqlite3
conn = sqlite3.connect('emaildb.sqlite')
cur = conn.cursor()
#Deleting any possible table that may affect this assignment
cur.execute('DROP TABLE IF EXISTS Counts')
cur.execute('''
CREATE TABLE Counts (org TEXT, count INTEGER)''')
fname = input('Enter file name: ')
if ( len(fname) < 1 ) : fname = 'C:/Files/Workspaces/Coursera/Python for Everybody/Using Database with Python/Assignments/Counting Organizations/mbox.txt'
fh = open(fname)
for line in fh:
if not line.startswith('From: '): continue
pieces = line.split()
email = pieces[1]
(emailname, organization) = email.split("@")
print (email)
cur.execute('SELECT count FROM Counts WHERE org = ? ', (organization,))
row = cur.fetchone()
if row is None:
cur.execute('''INSERT INTO Counts (org, count)
VALUES (?, 1)''', (organization,))
else:
cur.execute('UPDATE Counts SET count = count + 1 WHERE org = ?',
(organization,))
# ommit the changes after for loop finished because this speeds up the
# execution and, since our operations are not critical, a loss wouldn't suppose
# any problem
conn.commit()
# # Getting the top 10 results and showing them
sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10'
for row in cur.execute(sqlstr):
print(str(row[0]), row[1])
cur.close()
| true |
9415684dc35e4d73694ef14abe732a7ba32bf301 | lenatester100/AlvinAileyDancers | /Helloworld.py | 806 | 4.1875 | 4 | print ("Hello_World")
print ("I am sleepy")
'''
Go to sleep
print ("sleep")
Test1=float(input("Please Input the score for Test 1..."))
Test2=float(input("Please Input the score for Test 2..."))
Test3=float(input("Please Input the score for Test 3..."))
average=(Test1+Test2+Test3)/3
print ("The Average of all 3 tests is ", average)
print (3+4)
print(3-4)
print(3*4)
print(3/4)
print(3%2)
print(3**4)
print(3//4)
print (5.0/9.0)
print (5.0/9)
print (5/9.0)
print (5/9)
print (9.0/5.0)
print (9.0/5)
print (9/5.0)
print (9/5)
'''
temp = int (input ("what is the temperature? "))
def temperature ():
if temp >= 90:
print ("hot")
elif temp <= 60:
print ("chilly")
else:
print ("Take me to Hawaii")
temperature()
| true |
b719b552170b8128a75a5121ac7578aa51a3e691 | Krishan27/assignment | /Task1.py | 1,466 | 4.375 | 4 | # 1. Create three variables in a single a line and assign different
# values to them and make sure their data types are different. Like one is
# int, another one is float and the last one is a string.
a=10
b=10.14
c="Krishan"
print(type(a))
print(type(b))
print(type(c))
# 2. Create a variable of value type complex and swap it with
# another variable whose value is an integer.
d= 50 + 3j
print(type(d))
b=d #here I swap the value of d with the b and then printed
print(b)
# 3 Swap two numbers using the third variable as the result name
# and do the same task without using any third variable.
a1=10
b1=5
result=a1
a1=b1
b1=result
print(a1)
# 4. Write a program to print the value given
# by the user by using both Python 2.x and Python 3.x Version.
user1=input("Type your name???")
print(user1)
age1=int(input("Type your age???"))
print(age1)
# 6. Write a program to check the data type of the entered values.
# HINT: Printed output should say - The input value data type is: int/float/string/etc
a=10
b=10.14
c="Krishan"
d=True
print(f"The input value data type is: {type(a)}")
print(f"The input value data type is: {type(b)}")
print(f"The input value data type is: {type(c)}")
print(f"The input value data type is: {type(d)}")
# 7. If one data type value is assigned to ‘a’ variable and then a different data
# type value is assigned to ‘a’ again. Will it change the value. If Yes then Why?
a=5
a=6
print(a)
| true |
953ed2c94e19a170fbe076f10339ff79ccda32f7 | chaithanyabanu/python_prog | /holiday.py | 460 | 4.21875 | 4 | from datetime import date
from datetime import datetime
def holiday(day):
if day%6==0 or day%5==0:
print("hii this is weekend you can enjoy holiday")
else:
print("come to the office immediately")
date_to_check_holiday=input("enter the date required to check")
day=int(input("enter the day"))
month=int(input("enter the month"))
year=int(input("enter the year"))
today=date(year,month,day)
day_count=today.weekday()
print(day_count)
holiday(day_count)
| true |
91572a07bf2cbe5716b5328c0d4afc34c5f375f8 | prince5609/Coding_Bat_problems | /make_bricks.py | 1,151 | 4.5 | 4 | """ QUESTION =
We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each)
and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks.
make_bricks(3, 1, 8) → True
make_bricks(3, 1, 9) → False
make_bricks(3, 2, 10) → True
"""
def make_bricks(small, big, goal):
total_big_len = big * 5
if goal == total_big_len:
return True
elif goal == small:
return True
else:
if total_big_len + small >= goal:
big_req = int(goal / 5)
if big_req <= big:
big_length_used = big_req * 5
small_req = goal - big_length_used
if small_req <= small:
total_length = big_length_used + small_req
if total_length == goal:
return True
else:
return False
else:
return False
else:
return True
else:
return False
print(make_bricks(3, 1, 8))
print(make_bricks(6, 0, 11))
| true |
022d1d89d419686f2ecf256f9e9a67aff141f13b | he44/Practice | /leetcode/35.py | 822 | 4.125 | 4 | """
35. Search Insert Position
Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
"""
class Solution:
def searchInsert(self, nums, target) -> int:
size = len(nums)
# no element / smaller than first element
if size == 0 or target < nums[0]:
return 0
for i in range(size):
if target == nums[i]:
return i
if target < nums[i]:
return i
# larger than all elements
return size
def main():
s = Solution()
nums = [1,3,5,6]
targets = [5,2,7,0]
for target in targets:
output = s.searchInsert(nums, target)
print(output)
if __name__ == "__main__":
main()
| true |
158ebdaca82112ce33600ba4f14c92b2c628a2b8 | Anjalics0024/GitLearnfile | /ListQuestion/OopsConcept/OopsQ10.py | 880 | 4.3125 | 4 | #Method Overloading :1. Compile time polymorphisam 2.Same method name but different argument 3.No need of more than one class
#method(a,b)
#method(a,b,c)
class student:
def __init__(self,m1,m2):
self.m1 = m1
self.m2 = m2
def add(self,a= None, b=None, c=None):
s = a+b+c
return s
s1 = student(66,100)
print(s1.add(2,9,10))
#Method Overriding 1.Example of compile time popymorphism 2.Atleast two class are requied 3.Same method and same argument
class A:
def fun1(self):
print('feature_1 of class A')
def fun2(self):
print('feature_2 of class A')
class B(A):
# Modified function that is
# already exist in class A
def fun1(self):
print('Modified feature_1 of class A by class B')
def fun3(self):
print('feature_3 of class B')
# Create instance
obj = B()
# Call the override function
obj.fun1()
| true |
0cc3fb7a602f1723486a9e3f4f4394e7b4b89f90 | zhuxiuwei/LearnPythonTheHardWay | /ex33.py | 572 | 4.3125 | 4 | def addNum(max, step):
i = 0
numbers = []
while(i < max):
print "At the top i is %d" % i
numbers.append(i)
i += step
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
return numbers
numbers = addNum(10, 2)
print "The numbers: ", numbers
for num in numbers:
print num
# below is add point item.
numbers = []
print "######## Now use for-loop instead of while-loop##########"
def addNum_for(max, step):
numbers = []
for i in range(0, max, step):
numbers.append(i)
return numbers
numbers = addNum_for(10, 2)
print "The numbers: ", numbers | true |
0249f8cb4fce6702f631c51de53449e0e80b5fde | sidhanshu2003/LetsUpgrade-Python-Batch7 | /Python Batch 7 Day 3 Assignment 1.py | 700 | 4.3125 | 4 | # You all are pilots, you have to land a plane, the altitude required for landing a plane is 1000ft,
#if less than that tell pilot to land the plane, or it is more than that but less than 5000 ft ask pilot to
# come down to 1000ft else if it is more than 5000ft ask pilot to go around and try later!
Altitude = input("Enter the number")
Altitude = int(Altitude)
if(Altitude>=1 and Altitude <=1000):
print("Safe to land plane from Altitude: ",Altitude)
elif(Altitude>1000 and Altitude<=5000):
print("Altitude required for landing plane is 1000ft")
elif(Altitude>5000):
print("Turn Around and try later")
else:
print("Altitude value should be greater than zero")
| true |
1c5d80a5243fb8636f82ca76f0cb1945d25627ec | ash8454/python-review | /exception-handling-class20.py | 1,414 | 4.375 | 4 | ###Exception handling
"""
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The finally block lets you execute code, regardless of the result of the
try- and except blocks.
"""
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
#You can use else to print out other command
a = 10
b = 1
try:
c=a/b
except:
print("Something else went wrong")
else:
print("Nothing went wrong")
#Finally - The finally block, if specified, will be executed regardless if
# the try block raises an error or not.
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
#try to open and write to a file that is not writable
# try:
# f = open('demofile.txt')
# f.write("Lorum Ipsum")
# except:
# print("Something went wrong when writing to the file")
# finally:
# f.close()
#Raise an exception
"""
As a Python developer you can choose to throw an exception if a condition occurs.
To throw (or raise) an exception, use the raise keyword.
"""
x = -1
if x < 0:
raise Exception("Sorry, no numbers below 0")
#raise type error
x = "hello"
if not type(x) is int:
raise TypeError("Only integers is allowed")
x="ashok"
if not type(x) is str:
raise TypeError("Only string is allowed")
else:
print("No error") | true |
0f26b50662decd207ceaf2ce4367b138a9644ee7 | saad-ahmed/Udacity-CS-101--Building-a-Search-Engine | /hw_2_6-find_last.py | 617 | 4.3125 | 4 | # Define a procedure, find_last, that takes as input
# two strings, a search string and a target string,
# and outputs the last position in the search string
# where the target string appears, or -1 if there
# are no occurences.
#
# Example: find_last('aaaa', 'a') returns 3
# Make sure your procedure has a return statement.
def find_last(search,find):
index = -1
while True:
i = search.find(find,index+1)
if i == -1:
break
index = i
return index
print find_last('aaaa', 'a')
print find_last('aaaa', 'b')
print find_last('', '')
print find_last('', 'b')
| true |
98cfbcf9b135a4851035453a1182acfbb389545f | samicd/coding-challenges | /duplicate_encode.py | 738 | 4.1875 | 4 | """
The goal of this exercise is to convert a string to a new string
where each character in the new string is "(" if that character appears only once in the original string,
or ")" if that character appears more than once in the original string.
Ignore capitalization when determining if a character is a duplicate.
Examples
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("
"""
def duplicate_encode(word):
# converting to lower case
l = word.lower()
# finding the set of chars with duplicates
dupes = set([x for x in l if l.count(x) >1])
# returning ')' if char is a member of dupes and '(' else
return ''.join([')' if s in dupes else '(' for s in l ])
| true |
f52079869f41ba7c7ac004521b99586c6b235dad | Ritella/ProjectEuler | /Euler030.py | 955 | 4.125 | 4 | # Surprisingly there are only three numbers that can be
# written as the sum of fourth powers of their digits:
# 1634 = 1^4 + 6^4 + 3^4 + 4^4
# 8208 = 8^4 + 2^4 + 0^4 + 8^4
# 9474 = 9^4 + 4^4 + 7^4 + 4^4
# As 1 = 1^4 is not a sum it is not included.
# The sum of these numbers is 1634 + 8208 + 9474 = 19316.
# Find the sum of all the numbers that can be written as the
# sum of fifth powers of their digits.
# SOLUTION: if n is the number of digits, the maximum 5th power sum
# that can be written is n * 9^5
# Therefore, find n such that (n) * (9^5) < 10^n - 1
# n can't be more than 6
max_num = 10**6
power_summands = []
for i in range(1, max_num):
str_i = str(i)
sum_d = 0
for d in str_i:
sum_d += int(d)**5
if sum_d == i and len(str_i) != 1: power_summands.append(i)
print(sum(power_summands))
# NOTE: cannot name a variable 'sum' or python gets confused since the
# sum object takes precedence over the sum function
| true |
83571a887f9f89107aa9d621c0c2ebcac139fd2e | Ritella/ProjectEuler | /Euler019.py | 1,836 | 4.15625 | 4 | # You are given the following information,
# but you may prefer to do some research for yourself.
# 1 Jan 1900 was a Monday.
# Thirty days has September,
# April, June and November.
# All the rest have thirty-one,
# Saving February alone,
# Which has twenty-eight, rain or shine.
# And on leap years, twenty-nine.
# A leap year occurs on any year evenly divisible by 4,
# but not on a century unless it is divisible by 400.
# How many Sundays fell on the first of the month
# during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
reg_year_days_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
leap_year_days_month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# your starting dating is 1 Jan 1900 so begin with that and remove after
month_lengths = []
for year in range(1900, 2001, 1):
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
days_month = leap_year_days_month
else:
days_month = reg_year_days_month
month_lengths.extend(days_month)
dates = []
for month_length in month_lengths:
dates.extend([i for i in range(1, month_length + 1)])
# 1900 is not a leap year so to start with 1901, we need
start_idx = sum(reg_year_days_month)
sundays_with_1 = [1 for i in range(start_idx, len(dates)) \
if (i + 1) % 7 == 0 and dates[i] == 1]
print(sum(sundays_with_1))
# NOTE: pay attention to month_lengths.extend(days_month) method for
# adding a list to a list
# could also have done calendar_dates += days_month
# importantly, can't use append neatly
# PAY ATTENTION to dates.extend.
# ALSO, extremely important. You cannot just add a range as a list
# Python returns a range, so you need to recast as a list using
# list() or item by item list comprehension
# also, look at how i wrote sundays_with_1 and avoided almost making an
# indexing mistake
| true |
b284b148982d4c0607e0e0c15ac07641aea81011 | ho-kyle/python_portfolio | /081.py | 229 | 4.21875 | 4 | def hypotenuse():
a, b = eval(input('Please enter the lengths of the two shorter sides \
of a right triangle: '))
square_c = a**2 + b**2
c = square_c**0.5
print(f'The length of hypotenuse: {c}')
hypotenuse() | true |
817a57ad576fcc602e6de0a8daa1a0811f5a6657 | chilperic/Python-session-coding | /mutiple.py | 868 | 4.28125 | 4 | #!/usr/bin/env python
#This function is using for find the common multiple of two numbers within a certain range
def multiple(x,y,m,t): #x is the lower bound the range and y higher bound
from sys import argv
x, y, m, t= input("Enter the the lower bound of your range: "), input("Enter the the higher bound of your range: "), input("enter the first number: "), input("enter the second number: ")
x, y, m, t= int(x), int(y), int(m), int(t)
a=[]
if x>y:
print str(x)+ " should be greater or equal to " +str(y)
exit()
if y<m and y<t:
print "The range is too small. Enter a number bigger than "+ str(m) + " or " + str(t)
exit()
for i in range (x,y):
if (i % m)==0 and (i % t)==0: #m and t are the number that we are looking for their multiple
a.append(i)
print a
return sum(a)
print multiple(x,y,m,t)
multiple(0,1000000,5,12) | true |
228e5e3c7ca9ae56d0b6e0874f592c58cbaadc24 | TeknikhogskolanGothenburg/PGBPYH21_Programmering | /sep9/textadventure/game.py | 2,467 | 4.3125 | 4 | from map import the_map
from terminal_color import color_print
def go(row, col, direction):
if direction in the_map[row][col]['exits']:
if direction == "north":
row -= 1
elif direction == "south":
row += 1
elif direction == "east":
col += 1
elif direction == "west":
col -= 1
else:
print("You can't go in that direction.")
return row, col
def get(row, col, item, inventory):
# Check if the selected item is in the room
if item in the_map[row][col]['items']:
color_print("yellow", f"You pick up the {item}")
the_map[row][col]['items'].remove(item)
inventory.append(item)
else:
color_print("red", f"There is no {item} in this room")
def drop(row, col, item, inventory):
# Check if the selected item is in the inventory
if item in inventory:
color_print("yellow", f"You drop the {item} to the floor")
inventory.remove(item)
the_map[row][col]["items"].append(item)
else:
color_print("red", f"There is no {item} in your inventory")
def show_inventory(inventory):
if len(inventory) == 0:
color_print("red", "Your inventory is empty")
else:
print("You have the following in your inventory:")
for item in inventory:
color_print("magenta", f"* {item}")
def main():
row = 1
col = 0
inventory = []
running = True
while running:
print("You are now in", the_map[row][col]['description'])
color_print("blue", f"There are exits to the {the_map[row][col]['exits']}")
if len(the_map[row][col]['items']) > 0:
print("Items in the room:", the_map[row][col]['items'])
command = input("> ")
command_parts = command.split()
main_command = command_parts[0].lower()
if main_command == "go":
row, col = go(row, col, command_parts[1].lower())
elif main_command == "get":
get(row, col, command_parts[1].lower(), inventory)
elif main_command == "drop":
drop(row, col, command_parts[1].lower(), inventory)
elif main_command == "inventory":
show_inventory(inventory)
elif main_command == "quit":
running = False
else:
print("I don't understand", command_parts[0])
print("Thanks for playing the game.")
if __name__ == '__main__':
main()
| true |
db64c4552a3eef0658031283a760edc8cf20b3c0 | mprzybylak/python2-minefield | /python/getting-started/functions.py | 1,568 | 4.65625 | 5 | # simple no arg function
def simple_function():
print 'Hello, function!'
simple_function()
# simple function with argument
def fib(n):
a, b = 0, 1
while a < n:
print a,
a, b = b, a+b
fib(10)
print ''
# example of using documentation string (so-called docstring)
def other_function():
"""Simple gibbrish print statement"""
print 'Hello'
other_function()
print other_function.__doc__
# functions can be assigned to variables
f = simple_function
f()
# return values with return statement
def fib_ret(n):
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
print fib_ret(20)
# default values in function
def default_args_fun(a=1, b=2):
print a, b
default_args_fun()
default_args_fun(10)
default_args_fun(100, 1000)
# keyword argument notation
# keyword arguments goes after positional arguments
default_args_fun(b=1000)
# *[name] argument contains positional arguments
def positional_arguments(a=1,b=2, *arguments):
print str(arguments)
positional_arguments(1,2)
positional_arguments(1,2,3,4)
# **[name] argument contains keyword arguments
def keyword_arguments(a,b, **arguments):
print str(arguments)
keyword_arguments(10,20)
keyword_arguments(10,20, aa=1, bb=2)
# unpacking argument
# When function requires e.g. three arguments, and we have it all in one list (list with 3 elements), we can use "unapck" synatx
def unpack_function(a,b):
print a,b
args = [1,2]
unpack_function(*args)
# We can unpack key arguments from map as a keyword arguments
args_map = {"a":1, "b":2}
unpack_function(**args_map) | true |
457c259a8515b806833cf54ccd0c79f8069f874c | surenderpal/Durga | /Regular Expression/quantifiers.py | 481 | 4.125 | 4 | import re
matcher=re.finditer('a$','abaabaaab')
for m in matcher:
print(m.start(),'...',m.group())
# Quantifiers
# The number of occurrences
# a--> exactly one 'a'
# a+-> atleast one 'a'
# a*-> any number of a's including zero number also
# a?-> atmost one a
# either one a or zero number of a's
# a{num}-> Exactly n number of a's
# ^a -> it will check whether the given string starts with a or not
# a$ -> it will check whether the given string ends with a or not
#
| true |
2c53a0967ba066ca381cc67d277a4ddcd9b3c4e7 | adreena/DataStructures | /Arrays/MaximumSubarray.py | 358 | 4.125 | 4 | '''
Given an integer array nums, find the contiguous subarray (containing at least one number)
which has the largest sum and return its sum.
'''
def maxSubarray(nums):
max_sum = float('-inf')
current_sum = nums[0]
for num in nums[1:]:
current_sum = max(current_sum+num, num)
max_sum = max(max_sum, current_sum)
return max_sum
| true |
855817e03fa062cb755c166042bdb16037aefe5c | IEEE-WIE-VIT/Awesome-DSA | /python/Algorithms/quicksort.py | 898 | 4.28125 | 4 |
# Function that swaps places for to indexes (x, y) of the given array (arr)
def swap(arr, x, y):
tmp = arr[x]
arr[x] = arr[y]
arr[y] = tmp
return arr
def partition(arr, first, last):
pivot = arr[last]
index = first
i = first
while i < last:
if arr[i] <= pivot: # Swap if current element is smaller to the pivot
arr = swap(arr, i, index)
index += 1
i += 1
arr = swap(arr, index, last)
return index
def quickSort(arr, first, last):
if first < last:
pivot = partition(arr, first, last)
# Implement quicksort on both sides of pivot
quickSort(arr, first, pivot-1)
quickSort(arr, pivot+1, last)
return arr
# Test array
array = [1, 10, 2, 4, 1, 9, 6, 7, 10, 4, 11, 3]
print("Unsorted test array: ", array)
quickSort(array, 0, len(array)-1)
print("Sorted test array: ", array) | true |
5d81d3e6f16f4fc1d5c9fcc5ed452becefa95935 | IEEE-WIE-VIT/Awesome-DSA | /python/Algorithms/Queue/reverse_k_queue.py | 1,231 | 4.46875 | 4 | # Python3 program to reverse first k
# elements of a queue.
from queue import Queue
# Function to reverse the first K
# elements of the Queue
def reverseQueueFirstKElements(k, Queue):
if (Queue.empty() == True or
k > Queue.qsize()):
return
if (k <= 0):
return
Stack = []
# put the first K elements
# into a Stack
for _ in range(k):
Stack.append(Queue.queue[0])
Queue.get()
# Enqueue the contents of stack
# at the back of the queue
while (len(Stack) != 0):
Queue.put(Stack[-1])
Stack.pop()
# Remove the remaining elements and
# enqueue them at the end of the Queue
for _ in range(Queue.qsize() - k):
Queue.put(Queue.queue[0])
Queue.get()
# Utility Function to print the Queue
def Print(Queue):
while (not Queue.empty()):
print(Queue.queue[0], end=" ")
Queue.get()
# Driver code
if __name__ == '__main__':
Queue = Queue()
Queue.put(10)
Queue.put(20)
Queue.put(30)
Queue.put(40)
Queue.put(50)
Queue.put(60)
Queue.put(70)
Queue.put(80)
Queue.put(90)
Queue.put(100)
k = 5
reverseQueueFirstKElements(k, Queue)
Print(Queue)
| true |
43012784b596503267cd6db2beb45bd19a7d1b0a | cuongnguyen139/Course-Python | /Exercise 3.3: Complete if-structure | 262 | 4.1875 | 4 | num=input("Select a number (1-3):")
if num=="1":
num="one."
print("You selected",num)
elif num=="2":
num="two."
print("You selected",num)
elif num=="3":
num="three."
print("You selected",num)
else:
print("You selected wrong number.")
| true |
d99103049b500922d6d7bab8268503ad8190067c | osudduth/Assignments | /assignment1/assignment1.py | 1,987 | 4.1875 | 4 | #!/usr/bin/env python3
#startswith,uppercase,endswith, reverse, ccat
#
# this will tell you the length of the given string
#
def length(word):
z = 0
for l in word:
z = z + 1
return z
#
# returns true if word begins with beginning otherwise false
#
def startsWith(word, beginning):
for x in range(0, length(beginning) ):
if beginning[x] != word[x]:
return False
return True
#
# This will return true if a string contains another smaller string and false if it doesnt
#
def contains(word, subWord):
if length(word) < length (subWord):
return False
for y in range (0, length(word)):
w = word[y:]
if startsWith (w, subWord):
return True
return False
#
#In this function you will give it a string and it will reverse the order of the letters in the string
#
def mirror(word):
x = length(word) - 1
mirrorWord = [None] * length(word)
for l in word:
mirrorWord[x] = l
x = x - 1
return ''.join(mirrorWord)
#
#This function will take in a word and then a subword and it will see if the word ends with the subword
#
def endsWith(word, subword):
mirror(word)
mirror(subword)
if startsWith(mirror(word), mirror(subword)):
return True
else:
return False
if contains("wordword", "poop"):
print("failed")
else:
print("passed")
if contains("wordword", "rdw"):
print ("passed")
else:
print("failed")
if startsWith("oliver", "oliv"):
print("passed")
else:
print("failed")
if contains ("oli", "oliver"):
print ("failed")
else:
print ("passed")
if (contains("zza", "azza")):
print("failed")
else:
print("passed")
if "eyb" == mirror("bye"):
print("passed")
else:
print("failed")
if endsWith ("birthday", "day"):
print ("passed")
else:
print ("failed")
if endsWith ("birthday", "dag"):
print ("passed")
else:
print ("failed")
| true |
d0524ae575c3cf1697039a0f783618e247a96d18 | TeresaChou/LearningCpp | /A Hsin/donuts.py | 222 | 4.25 | 4 | # this program shows how while loop can be used
number = 0
total = 5
while number < total:
number += 1
donut = 'donuts' if number > 1 else 'donut'
print('I ate', number, donut)
print('There are no more donuts') | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.