blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c30d9355127e9912c42e7e8c403384a529a9ccf8 | lasttillend/CS61A | /hw/hw01/sin_taylor.py | 546 | 4.1875 | 4 | """
Calculate Taylor expansion of sinx.
"""
from math import factorial, sin, pow
def summation(n, x, term):
"""
sum up to nth term.
"""
total, k = 0, 1
while k <= n:
total, k = total + term(k, x), k + 1
return total
def sin_term(k, x):
"""
the kth term of sinx in its Taylor expansion
"""
return pow(-1, k-1) / factorial(2*k-1) * pow(x, 2*k-1)
def sin_taylor_expansion(n, x):
"""
approximate sinx by its nth-order Taylor polynomial
"""
return summation(n, x, sin_term)
x = sin_taylor_expansion(10, 1)
print(x)
print(sin(1)) | false |
1b2c3ea362c4b373bc04ec04140aced9e90b4a83 | barbarasidney/cours | /Coursera_Python for everybody/Cours1_Programming for Everybody_Getting Started with Python/Cours1_Week5.py | 1,718 | 4.28125 | 4 | # Week 4
# Write a program to prompt the user for hours and rate
# per hour using input to compute gross pay.
# Pay the hourly rate for the hours up to 40 and 1.5 times
# the hourly rate for all hours worked above 40 hours.
# Use 45 hours and a rate of 10.50 per hour to test the program
# (the pay should be 498.75). You should use input to read a string
# and float() to convert the string to a number. Do not worry about
# error checking the user input - assume the user types numbers properly.
hrs = input("Enter Hours:")
h = float(hrs)
rate = input("Enter Rate:")
r = float(rate)
if h <= 40.0:
down = h * r
print(down)
if h > 40.0:
under = 40.0 * r
up = h - 40.0
float(up)
sup = up * r * 1.5
pay = under + sup
float(pay)
print(pay)
# Write a program to prompt for a
# score between 0.0 and 1.0. If the score is
# out of range, print an error. If the score
# is between 0.0 and 1.0, print a grade using
# the following table:
''''
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
'''
# If the user enters a value out of range, print a suitable
# error message and exit. For the test, enter a score of 0.85.
score = input("Enter Score: ")
score = float(score)
if score > 1.0:
print("Error")
else:
if score >= 0.9:
print("A")
elif score >= float(0.8):
if score < float(0.9):
print("B")
else:
print("Error")
elif score >= float(0.7):
if score < float(0.8):
print("C")
else:
print("Error")
elif score >= float(0.6):
if score < float(0.7):
print("D")
else:
print("Error")
elif score < float(0.6):
print("F")
| true |
2c08371bbd9c3498f9c2bc52e0fbebf16c0e6478 | aslich86/AljabarLinear | /Transpose.py | 535 | 4.21875 | 4 | #Transpose, menukar entri baris dan kolom
X = [[12,7],
[4,5],
[3,8]]
print('matriks X=', X)
print()
#transpose dengan nested loop
result = [[0,0,0],
[0,0,0]]
for i in range(len(X)):
for j in range(len(X[0])):
result[j][i] = X[i][j]
print('Transpose menggunakan nested loop')
print('Transpose X=', result)
print()
#transpose dengan list comprehensive
print('Transpose menggunakan list comprehensive')
result = [[X[j][i] for j in range(len(X))] for i in range(len(X[0]))]
print('Transpose X =', result)
| false |
f83edd72d2097a40f58d6135be2a6624818cdf81 | yayankov/Python-Coursera | /Python Data Structure/ListTask1.py | 604 | 4.40625 | 4 | #Open the file romeo.txt and read it line by line.
#For each line, split the line into a list of words
#using the split() method. The program should build
#a list of words. For each word on each line check
#to see if the word is already in the list and if
#not append it to the list. When the program completes,
#sort and print the resulting words in alphabetical order.
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.strip()
line = line.split()
for word in line:
if word in lst : continue
lst.append(word)
lst.sort()
print(lst)
| true |
d432254f02faa79ac72999be3f4ed5f99c68204b | Bsgn/GlobalAIHubPythonHomework | /homework1.py | 522 | 4.1875 | 4 | val1 = input("Enter 1st value : ")
val2 = input("Enter 2nd value : ")
val3 = input("Enter 3rd value : ") #Taking values from user
val4 = input("Enter 4th value : ")
val5 = input("Enter 5th value : ")
print(f"1st value : {val1}, type : {type(val1)}")
print(f"2nd value : {val2}, type : {type(val2)}")
print(f"3rd value : {val3}, type : {type(val3)}") #Printing values and type of values
print("4th value : {}, type : {}".format(val4, type(val4)))
print("5th value : {}, type : {}".format(val5, type(val5)))
| true |
fb5ec941cf217a945c4a45834c78582ecbb23424 | yaswanthkumartheegala/py | /big and small.py | 251 | 4.125 | 4 | print("enter the numbers=")
a=int(input("enter the a value"))
b=int(input("enter the b value"))
c=int(input("enter the c value"))
if a>b and a>c:
print(a,"is s largest")
elif b>a and b>c:
print(b,"is a largest")
else:
print(c,"is largest") | false |
b0281079f2b91477026c4f22cf77ae7311ddc3a9 | p4dd0n/learning | /rock_paper_scissor_selv.py | 1,301 | 4.28125 | 4 | import random
def userChoice():
user = input("Please choose rock, paper or scissor. Enter exit to quit: ")
while (user != "rock" and user != "paper" and user != "scissor" and user != "exit"):
user = input("Invalid input. Please choose rock, paper or scissor. Enter exit to quit: ")
return user
def computerChoice():
computer = random.randint(1, 3)
if computer == 1:
return "rock"
elif computer == 2:
return "paper"
elif computer == 3:
return "scissor"
def findWinner(user, computer):
print("User: ", user)
print("Computer: ", computer)
if user == computer:
print("Draw")
if user == "rock":
if computer == "paper":
print("Computer wins")
else:
print("Player wins")
if user == "paper":
if computer == "scissor":
print("Computer wins")
else:
print("Player wins")
if user == "scissor":
if computer == "rock":
print("Computer wins")
else:
print("Player wins")
if __name__ == "__main__":
user = userChoice()
while user != "exit":
computer = computerChoice()
findWinner(user, computer)
user = userChoice() | true |
eb4ba9af4318784d954120f15d02d249a9a1fb7f | NataliaPuchkova/Python | /parseAndListMatches.py | 1,518 | 4.28125 | 4 | #!/usr/bin/env python
# encoding: utf
#
# Simple imitation of the Unix find command, which search sub-tree
# for a named file, both of which are specified as arguments.
# Because python is a scripting language, and because python
# offers such fantastic support for file system navigation and
# regular expressions, python is very good at for these types
# of tasks
from sys import argv
from os import listdir
from os.path import isdir, exists, basename, join
def listAllExactMatches(path, filename):
"""Recursive function that lists all files matchingthe specified file name"""
if (basename(path) == filename):
print "%s" % path
if (not isdir(path)):
return
dirlist = listdir(path)
for file in dirlist:
listAllExactMatches(join(path, file), filename)
def parseAndListMatches():
"""Parses the command line, confirming that there are in fact three arguments, confirms that the specified path is actually
the name of a real directory, and then recursively search the file tree rooted at the speci fied directory."""
if (len(argv) != 3):
print "Usage: find <path-to-directory-tree> <filename>"
return
directory = argv[1]
if (not exists(directory)):
print "Specified path \"%s\" does not exist." % directory
return;
if (not isdir(directory)):
print "\"%s\" exists, but doesn't name an actual directory." % directory
filename = argv[2]
listAllExactMatches(directory, filename)
parseAndListMatches()
| true |
77c57206847e08d5516fccf627ab69260b00a096 | mcptr/tutorials | /python/dicts/0-tasks.py | 691 | 4.625 | 5 | colors = {
"green": "GREEN",
"blue": "BLUE",
"red": "RED",
"yellow": "yellow",
}
## Tasks:
# 1. Print all the keys in the dictionary
# 2. Print all values in the dictionary
# 3. Set the value of "red" to "reddish"
# 4. Set all the values to the uppercase form of the corresponding key
# 5. Print a list of tuples in the form: (key, value)
# 6. Check if "brown" is present in the dictionary
# 7. Print the value of "brown", or "No such color" if "brown" is not present
# 8. Add a "black" key with a "BLACK" value
# 9. Modify the dictionary so that "red" is "ROSE" and "yellow" is "SUN".
# 10. Remove "green" from the dictionary
# 11. Remove and print the value of the "blue"
| true |
3e1ba6bce85ec3ca0092647d01dc92fa96afc64e | DeltaForce14/Python_challenges | /Hunderd_years_challenge.py | 1,090 | 4.125 | 4 | '''
Create a program that asks the user to enter their name and their age.
Print out a message addressed to them that tells them the year
that they will turn 100 years old.
Add on to the previous program by asking the user for another number
and printing out that many copies of the previous message.
'''
name = input("What's your name?")
age = input("How old are you?")
def hunderd_age():
return 100 - int(age)
age_sentence = name +", you will be 100 years old in " + str(hunderd_age()) + " years."
print(age_sentence)
def number_check():
try:
global user_number
user_number = int(input("Give me a number from 1 to 10: "))
except ValueError:
print("You need to type a whole number. This is not a whole number.")
else:
if (user_number > 0) and (user_number <=10):
print("You typed:", user_number)
else:
print("This is not a number between 1 and 10. Try it again.")
print(number_check())
for i in range(user_number):
print(str(age_sentence * i))
| true |
cd6cee48c468dc718f6149d57bdce13fbb98ae02 | sambhu-padhan/My_Python_Practice | /03_UserEntry.py | 916 | 4.15625 | 4 | # Receive numbers from users and show it.......
""" # OUTPUTS
print("Enter your number : ")
inpnum = input()
print(inpnum) # 12
print("You entered :", inpnum * 10) # 12121212121212121212(10 times 12)
#print("you entered :", inpnum + 10) # Error(TypeError: can only concatenate str (not "int") to str)
print("You entered :", int(inpnum) + 10) # 22 (typecasting)
"""
# add two numbers and print them..............
print("Enter 1st number : ")
x = input()
print("Enter 2nd number : ")
y = input()
print("The sum of these two numbers is : ",int(x)+int(y))
"""
Enter 1st number :
11
Enter 2nd number :
12
The sum of these two numbers is : 23
""" | true |
665ebd7f9ab4dcc8c1f199f2022bfc0aa314afae | sambhu-padhan/My_Python_Practice | /23_Exersize_3.1.py | 734 | 4.1875 | 4 | # Exersize 3.1 ......Q.I COMPLETED THIS EXERSIZE WITH WRONG WAY.....SO TRY AGAIN WITH ACCURACY
# ......Pattern Printing........
# Input = integer n
# Boolean = True or False
# True n=5
# *
# * *
# * * *
# * * * *
# False n=5
# * * * *
# * * *
# * *
# *
print("Please Enter a number :",end = " ")
num = int (input())
print(num)
x = 1
if num == 5 :
print("True, Number is equal to 5..\n")
while x < num :
print(x * "* ")
x = x + 1
else :
print("False, Number is not equal to 5.\n")
x = 4
while x >= 1 :
print(x * "* ")
x = x-1
"""OUTPUT
Please Enter a number : 12
12
False, Number is not equal to 5.
* * * *
* * *
* *
*
""" | true |
5fdb5ed8c855ed9d161d5698d737eb0b98e76b4e | Abirami33/python-75-hackathon | /type_c2.py | 696 | 4.28125 | 4 | #IMPLICIT TYPE CASTING
in1=23 #int
in2=45 #int
fl1=12.5 #float
print(type(in1))
print(type(in2))
print(type(fl1))
res=in1*in2*fl1 #Int and float gets multiplied and converted as float implicitly
print("Result is:")
print(res)
print(type(res))
#EXPLICIT TYPE CASTING
in0=1000 #int
st1="2000" #string
print("Before typecast:")
print(type(st1))
st1= int(st1) #explicitly typecasted as int
print("After typecast:")
print(type(st1))
print("Add result:")
print(in0+st1)
'''OUTPUT:
stud@HP-246-Notebook-PC:~$ python type_c2.py
<class 'int'>
<class 'int'>
<class 'float'>
Result is:
12937.5
<class 'float'>
Before typecast:
<class 'str'>
After typecast:
<class 'int'>
Add result:
3000
'''
| true |
0b1c42f3da171486b51784dab395df1db9a8e701 | dyeap-zz/CS_Practice | /Sorting/CustomComp.py | 1,149 | 4.3125 | 4 | '''
Given an array of integers arr, write a function absSort(arr),
that sorts the array according to the absolute values of the numbers in arr.
If two numbers have the same absolute value, sort them according to sign,
where the negative numbers come before the positive numbers.
Examples:
input: arr = [2, -7, -2, -2, 0]
output: [0, -2, -2, 2, -7]
a = 2, b = 7 ret -1 left is smaller
a = -7, b = 2 ret 1 right is smaller
a = -2, b = 2 ret -1 left is smaller
a = 2, b = -2 ret 1 right is smaller
a = 2, b = 2 or a = 0, b = 0 either can be used
'''
#custom comparator
#PYTHON DOES NOT HAVE A CMP =, IT USES KEY =
'''
def absSort(arr):
def cmp(a,b):
if abs(a) < abs(b): return -1
if abs(a) > abs(b): return 1
if a < b: return -1
if a > b: return 1
return 0
arr.sort(key = cmp)
#a = sorted(arr,key = cmp)
return arr
arr = [2, -7, -2, -2, 0]
print(absSort(arr))
# custom comparator sort
'''
arr = [[4,2],[1,2],[0,3]]
arr.sort(key=lambda x: x[0])
print(arr)
li = [30,3,34]
class cmp(str):
def __lt__(x, y):
return x+y > y+x
li.sort(key = cmp)
s = [str(num) for num in li]
res = "".join(s)
print(res) | true |
c89949204aaf8273d2a3898dd21901a37ea96cf4 | nikkiwojo/DE-2d1-Dice-Roller | /roll.py | 704 | 4.34375 | 4 | import random
def dice_roll(how_many):
first = random.randint(1,6)
second = random.randint(1,6)
third = random.randint(1,6)
if how_many == 1:
print("You rolled a", first)
elif how_many == 2:
print("First roll:", first, "Second roll:", second)
elif how_many == 3:
print("First roll:", first, "Second roll:", second, "Third roll:", third)
initial_roll = random.randint(1,6)
print("The first roll was a", initial_roll)
roll_again = input("Would you like to roll again? y/n")
while roll_again == "y":
number = input("How many dice would you like to roll?")
dice_roll(int(number))
roll_again = input("Would you like to roll again? y/n")
| false |
4e5e1d89fbfff315cef73b768af28a51dd7fabee | Goyatuzo/python-problems | /project_euler/006/sum_square_difference.py | 1,042 | 4.15625 | 4 | import operator
def difference(n):
"""This problem was optimized for the HackerRank interface. Since there will
be multiple values being passed in, rather than computing the differences for
each and every value, it would be more efficient to compute the difference for
the largest value, then store all intermediate entries in an array and reference
them when returning the final value. This takes up unnecessary space, but is easy
to implement. The more space efficient version would only append to the output list
when the i-th iteration is a value in the input n.
:param n: The list of numbers to evaluate the sum square difference."""
differences = []
# sum of the squares
sum_of_squares = (1 / 6) * n * (1 + n) * (1 + 2 * n)
# square of the sums
sum_base = (1 / 2) * n * (n + 1)
square_of_sums = sum_base ** 2
# Diff between sum of squares and square of the sum
return abs(int(sum_of_squares - square_of_sums))
if __name__ == '__main__':
print(difference(100)) | true |
1c731a184032bba38037491ef62994033e9bdaeb | yosshor/my-repository | /python_course/read_file_and_dosome.py | 1,242 | 4.15625 | 4 |
def sorting(filename):
"""This func sort the file and return the file sorted"""
word = []
with open(filename) as file:
for line in file:
word += line.split()
return ' '.join(sorted(word))
def rev(filename):
"""This func take the file and return it in reverse"""
word = []
with open(filename) as file:
for line in file:
for i in line:
if i in word:
continue
word += line[::-1]
sa = ''.join(word)
print(set(sa))
def last(filename):
"""This func take the file read it, and you need to insert num and
the func will return the file only with this num line"""
word = []
which = int(input("enter a num :"))
with open(filename, 'r') as f:
lines = f.read().splitlines()
for i in lines[which:]:
print(i)
your_input = input("enter your path to the file.txt directory : ")
task = input("enter your task (your options is sort, rev, last) : ")
if task == str('sort'):
r = sorting(your_input)
print(r)
if task == 'rev':
rev(your_input)
if task == 'last':
last(your_input)
| true |
4dba8cdb57e2a7c7b93afd83a0e667d67f499543 | vishwanathj/python_learning | /python_hackerrank/Sets/set_add.py | 1,360 | 4.5625 | 5 | '''
If we want to add a single element to an existing set, we can use the .add() operation.
It adds the element to the set and returns 'None'.
Example
>>> s = set('HackerRank')
>>> s.add('H')
>>> print s
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
>>> print s.add('HackerRank')
None
>>> print s
set(['a', 'c', 'e', 'HackerRank', 'H', 'k', 'n', 'r', 'R'])
Task
Apply your knowledge of the .add() operation to help your friend Rupal.
Rupal has a huge collection of country stamps. She decided to count the total number of distinct country stamps in her
collection. She asked for your help. You pick the stamps one by one from a stack of N country stamps.
Find the total number of distinct country stamps.
Input Format
The first line contains an integer N, the total number of country stamps.
The next N lines contains the name of the country where the stamp is from.
Constraints
0 < N < 1000
Output Format
Output the total number of distinct country stamps on a single line.
Sample Input
7
UK
China
USA
France
New Zealand
UK
France
Sample Output
5
Explanation
UK and France repeat twice. Hence, the total number of distinct country stamps is 5(five).
'''
if __name__ =='__main__':
count = int(raw_input())
stamp_set = set()
for i in range(count):
stamp_set.add(raw_input().strip())
print len(stamp_set)
| true |
8c9207a393423a904b286cc881ea6289dbac99ec | vishwanathj/python_learning | /python_hackerrank/BuiltIns/input.py | 969 | 4.15625 | 4 | '''
This challenge is only forPython 2.
input()
In Python 2, the expression input() is equivalent to eval(raw _input(prompt)).
Code
>>> input()
1+2
3
>>> company = 'HackerRank'
>>> website = 'www.hackerrank.com'
>>> input()
'The company name: '+company+' and website: '+website
'The company name: HackerRank and website: www.hackerrank.com'
Task
You are given a polynomial P of a single indeterminate (or variable), x.
You are also given the values of x and k. Your task is to verify if P(x) = k.
Constraints
All coefficients of polynomial P are integers.
x and y are also integers.
Input Format
The first line contains the space separated values of x and k.
The second line contains the polynomial P.
Output Format
Print True if P(x) = k. Otherwise, print False.
Sample Input
1 4
x**3 + x**2 + x + 1
Sample Output
True
Explanation
P(1) = 1*pow(3)+1*pow(2)+1+1 = 4 = k
Hence, the output is True.
'''
x,k=map(int, raw_input().split())
print (k==input()) | true |
3afb857baa5c9df7a6c143ee447b981f82afca1d | vishwanathj/python_learning | /python_hackerrank/introduction/division.py | 585 | 4.125 | 4 | '''
Task
Read two integers and print two lines. The first line should contain integer division, a//b .
The second line should contain float division, a/b .
You don't need to perform any rounding or formatting operations.
Input Format
The first line contains the first integer, a. The second line contains the second integer, b.
Output Format
Print the two lines as described above.
Sample Input
4
3
sample Output
1
1.3333333333333333
'''
from __future__ import division
if __name__ == '__main__':
a = int(raw_input())
b = int(raw_input())
print a//b
print a/b
| true |
61588ee4a7899c7a68535872bfca1479df20ae7c | vishwanathj/python_learning | /python_hackerrank/regex_and_parsing/validate_roman_numerals.py | 678 | 4.125 | 4 | '''
You are given a string, and you have to validate whether it's a valid Roman numeral. If it is valid, print True. Otherwise, print False. Try to create a regular expression for a valid Roman numeral.
Input Format
A single line of input containing a string of Roman characters.
Output Format
Output a single line containing True or False according to the instructions above.
Constraints
The number will be between 1 and 3999 (both included).
Sample Input
CDXXI
Sample Output
True
'''
import re
thousand = 'M{0,3}'
hundred = '(C[MD]|D?C{0,3})'
ten = '(X[CL]|L?X{0,3})'
digit = '(I[VX]|V?I{0,3})'
print (bool(re.match(thousand + hundred+ten+digit +'$', raw_input()))) | true |
f8ab53bd48eab679ff54b392eed3338e5111c967 | vishwanathj/python_learning | /30_days_of_code_hackerrank/exceptions.py | 1,160 | 4.34375 | 4 | '''
Objective: Get started with exceptions and print custom error message.
Task
Read a string, S, and print its integer value; if S cannot be converted to an integer, print Bad String.
Note: You must use the String-to-Integer and exception handling constructs built into your submission language.
If you attempt to use loops/conditional statements, you will get a 0 score.
Input Format
A single string, S.
Constraints
1 <= |S| <= 6, where |S| is the length of string S.
S is composed of either lowercase letters (a-z) or decimal digits (0-9).
Output Format
Print the parsed integer value of S, or Bad String if S cannot be converted to an integer.
Sample Input 0
3
Sample Output 0
3
Sample Input 1
za
Sample Output 1
Bad String
Explanation
Sample Case 0 contains an integer, so it should not raise an exception when we attempt
to convert it to an integer. Thus, we print the 3.
Sample Case 1 does not contain any integers, so an attempt to convert it to an integer
will raise an exception. Thus, our exception handler prints Bad String.
'''
#!/bin/python
import sys
S = raw_input().strip()
try:
print int(S)
except:
print 'Bad String' | true |
cc37eb7e7fb0a4f4641b29b6da1e661884732ce7 | abhayj-0/Assignments-Acadview- | /Assi3.py | 1,557 | 4.1875 | 4 | #Data Types-1
#ques 1: Create a list with user defined input
g, h, j = input("Enter three numbers").split(",")
list=[]
list.append(g)
list.append(h)
list.append(j)
print(list)
#ques 2:Add the following llist to the above created
given = ["google","apple","facebook","microsoft","tesla"]
list.append(given)
print(list)
#ques 3:count the number of times an object occurs in a list
print(sum(x.count('google') for x in list))
#ques 4:Create a list with numbers and sort it in ascending order
list1=[1,5,7,9,4]
list1.sort()
print(list1)
#ques 5:
a=[1,2,3]
b=[4,5,6]
c=[]
c.append(a)
c.append(b)
c.sort()
print(c)
#ques 6:implementation of stack and queue
#stack
stack=[4,5,2,6]
stack.pop()
print(stack)
A=input("Enter the number you want to add")
stack.append(A)
print(stack)
#queue
queue=[4,5,2,6]
queue.pop(0)
print(queue)
B=input("Enter the number you want to add")
queue.append(B)
print(queue)
#queue using deque module
from collections import deque
d = deque('ghi') #new items added
d.append('j') #appends at the end
d.appendleft('f') #appends at left
print(d)
d.pop() #pops the element at last(right side)
d.popleft() #pops leftmost element
print(d)
#ques 7: count even and odd numbers
countEven = 0
countOdd = 0
for x in range(1,10):
if not x % 2:
print("Even numbers are:"+str(x))
countEven+=1
else:
print("odd numbers are:" + str(x))
countOdd += 1
print("number of even numbers"+str(countEven))
print("number of even numbers"+str(countOdd))
| true |
7ee09a52ac97ca343d268065c4c4a952e9f7caa7 | abhayj-0/Assignments-Acadview- | /Assignment8.py | 1,085 | 4.15625 | 4 | import datetime,time,math,os
from time import gmtime,strftime
#ques1:
print("Time tuple is used to represen time in a way it is easy to understand.And it is stored in tuple.And also that these tuples aree made of nine numbers..")
print("eg:index:0->year...index:1->Month...index:2->Day...index:3->hour...index:4->Minute..index:5->Sec..index:6->Day of Week..index:7->day f year..index:8->Dst")
#quest2:
print("Formitted time:"+time.asctime(time.localtime()))
#ques 3:
print(time.strftime("%b"))
#ques4:
print(time.strftime("%A"))
#ques 5:
dateen=int(input("Enter date"))
yearen=int(input("Enter Year"))
monen=int(input("Enter month"))
dateentered=datetime.date(yearen,monen,dateen)
print(dateentered.strftime("%b"))
#ques 6:
print(strftime("%H:%M:%S", gmtime()))
#ques 7:
x=int(input("Enter your number"))
print("the factorial is"+" "+str(math.factorial(x)))
#ques 8:
a= int(input("Enter 1 numbers"))
b= int(input("Enter 2 numbers"))
print("gcd is:"+str(math.gcd(a, b)))
#ques 9:
print("Current Working Directory"+str(os.getcwd()))
print("User environment"+str(os.environ)) | true |
51485efde3c08738308f3afd406a726b6ab13ace | sourcery-ai-bot/library-python | /concepts/functions/lambda_with_map.py | 443 | 4.15625 | 4 | import math
# Produce a list from 1 to 10 for each of the radii to be processed
radii = [num for num in range(1, 11)]
# Set a function that calculates the area (to 2dp) when given its radius
area_calc = lambda r: round(math.pi * r ** 2, 2)
# Creates an iterator that maps together each of the radii to their respective calculated areas
areas = map(area_calc, radii)
# Casts the 'areas' iterator to a list
areas = list(areas)
print(areas)
| true |
74cdb978e230ab73d5d2bb381746fe317c30e66e | sourcery-ai-bot/library-python | /concepts/exceptions/exception_handling.py | 853 | 4.15625 | 4 | """ The 'try' part of the block is the condition(s) to test.
The 'except' part of the block will be executed if an exception is thrown.
Multiple levels of exceptions can be added to this. The most specific exceptions
should be written at the top with the most general being at the bottom. This is
so the compiler tests, throws and returns those most specific exceptions first.
The 'else' part of the block is executed if an exception is not found.
The 'finally' part of the block will run in any case. A good use case for this
might be closing a database which should be closed down irrespective of whether
an error is thrown."""
try:
f = open('testfile.txt')
except FileNotFoundError:
print("An error has occurred")
raise FileNotFoundError
else:
print(f.read())
f.close()
finally:
print("This line will print in any case")
| true |
855513e40ebc1613ebe0f49bef8824230d3240e1 | sourcery-ai-bot/library-python | /concepts/data_structures/dictionaries.py | 816 | 4.1875 | 4 | students = {
"Alice": ["ID001", 21, "A"],
"Bob": ["ID002", 22, "B"],
"Claire": ["ID003", 23, "C"],
"Dan": ["ID004", 24, "D"],
"Emma": ["ID005", 25, "E"],
}
# An example of using slicers to get the item from the dictionary/list
print(students["Alice"][0])
print(students["Dan"][1:])
# The below uses a dictionary within the students dictionary
students = {
"Alice": {"ID": "ID001", "Age": 21, "Grade": "A"},
"Bob": {"ID": "ID002", "Age": 22, "Grade": "B"},
"Claire": {"ID": "ID003", "Age": 23, "Grade": "C"},
"Dan": {"ID": "ID004", "Age": 24, "Grade": "D"},
"Emma": {"ID": "ID005", "Age": 25, "Grade": "E"},
}
# An example of using slicers to get the item from the dictionary/list
print(students["Bob"]["Age"])
| false |
06b2619d44a80afed09618c26bb608c3574d65b7 | sourcery-ai-bot/library-python | /concepts/iteration/custom_for_loop.py | 1,275 | 4.8125 | 5 | """ Here is an example of a custom for loop that demonstrates how a loop
works in Python. It demonstrates the concepts of iterators and iterables. """
def my_for_loop1(iterable, func):
""" Emulates a for loop accepting an iterable object and a function
object as its arguments """
iterator = iter(iterable)
""" The while True enables the iterator to keep iterating until there
are iterators to continue to work with. Once the loop goes beyond the
final iterator, it tries to run the next function, however throws an
exception and therefore the except statement throws the StopIteration
exception and the 'break' keyword breaks out of the while loop allowing
for the error to pass silently. """
while True:
try:
thing = next(iterator)
except StopIteration:
break
else:
func(thing)
# Demonstrate this by calling the function using several methods
def square(num):
print(num * num)
# Strings are iterable, therefore the elements of the string can be iterated upon
my_for_loop1("The cat sat on the mat", print)
# A list is naturally iterable, therefore its elements can be iterated upon
my_for_loop1([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], square)
| true |
cafea319385df050b37d069ae8936ba56fc1a36e | Priya2120/nested-if-else | /angle .py | 240 | 4.34375 | 4 | angle=int(input("enter first angle"))
angle1=int(input("enter second angle"))
angle2=int(input("enter third angle"))
if angle+angle1+angle2==180:
print("this triangle is possible")
else:
print("this triangle is not possible")
| true |
3be334952f8a5df8aeee717da6abc3f68fcbd0f8 | Priya2120/nested-if-else | /int que.1.py | 290 | 4.1875 | 4 | age=int(input("enter the age"))
if age<2:
print("bady age")
elif age>=2 and age<4:
print("toddler age")
elif age>=4 and age<13:
print("kid age")
elif age>=13 and age<20:
print("teenager age")
elif age>=20 and age<65:
print("adult age")
else:
print("older age")
| false |
6308fbbb250e918e29192027cb43978d0a14b5ee | Priya2120/nested-if-else | /atm que 2.py | 2,731 | 4.125 | 4 | print("welcome to atm")
card=input("insert a card")
if card=="debit card" or card=="atm card":
print("transaction in process")
language=input("select languade")
if language=="english" or "hindi":
print("inprocess")
pin=int(input("enter your pin"))
if pin==6789:
print("please select transaction")
transaction=input("transaction type")
if transaction=="withdrawn":
print("inprocess")
amount=int(input("enter the amount"))
if amount <=5000 :
print("in process")
account=input("enter a account")
if account=="saving account" or "current account":
print("in process")
print("transaction is successfully done")
print("collect your cash")
receipt=input("do you want reciept")
if receipt=="yes":
print("collect your reciept")
print("your remaining balance is",(5000-amount))
print("thank you for transaction")
elif transaction=="pin change":
print("in process")
pin_change=(input("do you want to change pin"))
new_pin=int(input("enter your new pin"))
if pin_change=="yes":
print("your new pin is", new_pin)
elif transaction=="deposit":
print("select your bank")
mobile_number=int(input("enter regester mobile number"))
if mobile_number==9156286294:
print("in processing")
account_num==int(input("enter your account number"))
if account_num==1234567890:
print("transaction in process")
confirm=input=input("you are confirm for process")
if confirm=="yes":
print("enter you cash in machine")
else:
print("sorry")
elif transaction=="balance inquiry":
print("in process")
account=input("select account")
if account=="saving" or account=="current":
print("please wait")
print("your account balance is 5000")
else:
print("as your wish. thank you")
else:
print("check transaction type")
else:
print("please check your pin")
else:
print("try again")
else:
print("your card is not valid")
| true |
ef9c01c7d62edf3c170a2bfb2f79545e9fac4a22 | minbbaevw/multi.plus.py | /main.py | 1,375 | 4.375 | 4 | # Дан массив целых чисел. Нужно найти сумму элементов с четными индексами (0-й, 2-й, 4-й итд), затем перемножить эту сумму и последний элемент исходного массива. Не забудьте, что первый элемент массива имеет индекс 0.
# Для пустого массива результат всегда 0 (ноль).
# Входные данные: Список (list) целых чисел (int).
# Выходные данные: Число как целочисленное (int).
def multi_plus(array):
"""
sums even-indexes elements and multiply at the last
"""
if len(array) == 0:
return False
s = 0
for i in range(len(array)):
if i % 2 == 0:
s = s + array[i]
return s * array[-1]
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
print('Example:')
print(multi_plus([0, 1, 2, 3, 4, 5]))
assert multi_plus([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)*5=30"
assert multi_plus([1, 3, 5]) == 30, "(1+5)*5=30"
assert multi_plus([6]) == 36, "(6)*6=36"
assert multi_plus([]) == 0, "An empty array = 0"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") | false |
bf49f902d661f7426132ec48aee579799b35bb0e | emorri08/ITC110 | /numbers2text.py | 492 | 4.21875 | 4 | #numbers2text.py
# convert a unicode sequence to a string
def main():
print("convert a unicode sequence to a string")
# get the sequence
inString = input("Enter the unicode encoded message: ")
#loop through each substring and build the message
msg = ""
for numStr in inString.split():
codeNum = int(numStr) #converting text digits to a number
msg = msg + chr(codeNum) #concat the char to the message
print("The decoded message is",msg)
main()
| true |
8724d2ebd4aea16903c86b5e725c0ad11b4e9736 | Aduzona/INTRO-TO-PYTHON-DEVELOPMENT | /11 - Collections/ranges.py | 303 | 4.125 | 4 | # We have the ability to grab a range, to grab a smaller
# sub collection of our larger collection
names= ['Susan', 'Christopher', 'Bill', 'Justin']
presenters = names[1:3] # omits the end index
# Start and end index
print(names) # prints every list items
print(presenters) # ['Christopher', 'Bill'] | true |
f07097e8b7015f6e7e5c961e994e307f2ee035f9 | matthewru/PythonLearning | /CTY_Python_Introduction/Unit 5/Assignment5-2_mru1350102.py | 1,727 | 4.25 | 4 | #functions
def total_motel_price(total_travel_distance, travel_distance_per_day, motel_cost_per_night):
return int(total_travel_distance / travel_distance_per_day) * motel_cost_per_night
def total_gas_price(total_travel_distance, car_miles_per_gallon, gas_price_per_gallon):
return (total_travel_distance / car_miles_per_gallon) * gas_price_per_gallon
def print_total_cost(motel_cost, gas_cost):
print("The total cost of the trip is $%.2f" % (motel_cost + gas_cost))
#input
total_travel_distance = int(input("What's the total travel distance (in miles)? "))
total_driving_hours_per_day = float(input("How long will you drive per day (in hours)? "))
miles_per_hour = int(input("How fast will you go during the trip (in miles per hour)? "))
travel_distance_per_day = int(total_driving_hours_per_day) * int(miles_per_hour)
car_miles_per_gallon = int(input("How far can you travel with one gallon of gas in your car (in miles)? "))
gas_price_per_gallon = float(input("How much does gas cost per gallon? "))
motel_cost_per_night = float(input("How much does the motel cost per night? "))
#calling function
print(total_travel_distance)
print(car_miles_per_gallon)
print(gas_price_per_gallon)
print( total_gas_price(total_travel_distance, car_miles_per_gallon, gas_price_per_gallon))
#print(travel_distance_per_day)
#print( int(total_travel_distance / travel_distance_per_day))
print( total_motel_price(total_travel_distance, travel_distance_per_day, motel_cost_per_night))
motel_cost = total_motel_price(total_travel_distance, travel_distance_per_day, motel_cost_per_night)
gas_cost = total_gas_price(total_travel_distance, car_miles_per_gallon, gas_price_per_gallon)
print_total_cost(motel_cost, gas_cost)
| true |
926ddbdb98bfab2a1e6c47b5ab5b2d7297aae4cb | matthewru/PythonLearning | /CTY_Python_Introduction/Unit 10/Activity10-4mru1350102.py | 823 | 4.4375 | 4 | class Flower:
#Class variable flowerCount
flowerCount = 0
def __init__(self, objPetalcount, objSpecies):
self.petals = objPetalcount
self.species = objSpecies
#using class variable by incrementing it by one
#whenever a new object gets created.
Flower.flowerCount += 1
def bloom(self):
print("My %s is blooming!" % self.species)
def wither(self):
print("All %d petals are falling off!" % self.petals)
#main program where we will use the Flower class
#Create several flower objects
flower1 = Flower(10, "daffodil")
flower2 = Flower(7, "anemone")
flower3 = Flower(15, "begonia")
flower4 = Flower(17, "irises")
flower5 = Flower(19, "aster")
#Print the class variable.
print("You've discovered %d different types of flowers!" % Flower.flowerCount)
| true |
4d0f70277d67ecd5886a725b986e1a416cf9cf97 | matthewru/PythonLearning | /AOPS_Intermediate_Python/Week7/ChallengeProblem2.py | 479 | 4.15625 | 4 | # Python Class 1889
# Lesson 7 Problem 2
# Author: madmathninja (272729)
import turtle
def teleport_and_draw(x,y):
carol.pendown()
carol.goto(x, y)
def teleport_and_no_draw(x,y):
carol.penup()
carol.goto(x, y)
# set up window and TT
wn = turtle.Screen()
carol = turtle.Turtle()
# listeners to teleport
wn.onclick(teleport_and_draw,1) # left click
wn.onclick(teleport_and_no_draw,3) # right click
# turn on the listeners and run
wn.listen()
wn.mainloop() | false |
c4134f2cb3c166b8a7b30c758bfb010dee1ac64a | matthewru/PythonLearning | /CTY_Python_Introduction/Unit 5/Activity 5-3_mru1350102.py | 595 | 4.34375 | 4 | #function
def calculate_total_price(product_price, quantity):
return product_price * quantity
#input
product_name = input("What are you buying? ")
product_price = float(input("How much does the product cost per unit? "))
quantity = int(input("How many units of the product are you buying? "))
#FIRST METHOD
total_price = calculate_total_price(product_price, quantity)
print("The total price of %s %s is $%.2f" % (quantity, product_name, total_price))
#SECOND METHOD
#print("The total price of %s %s is $%.2f" % (quantity, product_name, calculate_total_price(product_price, quantity)))
| true |
2c577e2e3f62a13cd336dd400a9ca8f71c6ed626 | matthewru/PythonLearning | /CTY_Python_Introduction/Unit 7/Activity 7-2_mru1350102.py | 618 | 4.21875 | 4 | #This part of the program creates a for loop that counts numbers up to 10 but midway through it asks the user if it wants to continue.
for count in range (1, 11):
print(str(count))
if count == 6:
ask = input("Would you like to continue? ")
if ask == 'No':
break;
#This part of the program has the same functionality as the previous one, except this one uses a for loop and the variable "number"
number = 1
while number <= 10:
print(number)
if number == 6:
ask = input("Would you like to continue? ")
if ask == 'No':
break;
number += 1
| true |
af3b7fff13bb128ed371b2c7271c8042065790b0 | eugennix/chekio | /Ice Base/Pangram/mission.py | 749 | 4.125 | 4 | def check_pangram(text):
'''
is the given text is a pangram.
'''
text_letters = set(text.lower())
a_to_z_pangram = set('abcdefghijklmnopqrstuvwxyz')
# a_to_z_pangram is subset of text_letters or equal it
return a_to_z_pangram <= text_letters
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert check_pangram("The quick brown fox jumps over the lazy dog."), "brown fox"
assert not check_pangram("ABCDEF"), "ABC"
assert check_pangram("Bored? Craving a pub quiz fix? Why, just come to the Royal Oak!"), "Bored?"
print('If it is done - it is Done. Go Check is NOW!')
print(check_pangram("abcdefghijklmnopqrstuvwxyz")) | true |
015649eae94fb3ac5a4946f84a5b9471e41f4318 | Tamoghna2001/Hacktoberfest_2021 | /Python/Implementation of Queue/list_function_queue.py | 859 | 4.21875 | 4 | # Implement Queue using List(Functions)
q=[]
def Enqueue():
if len(q)==size: # check wether the stack is full or not
print("Queue is Full!!!!")
else:
element=input("Enter the element:")
q.append(element)
print(element,"is added to the Queue!")
def dequeue():
if not q:# or if len(stack)==0
print("Queue is Empty!!!")
else:
e=q.pop(0)
print("element removed!!:",e)
def display():
print(q)
size=int(input("Enter the size of Queue:"))
while True:
print("Select the Operation:1.Add 2.Delete 3. Display 4. Quit")
choice=int(input())
if choice==1:
Enqueue()
elif choice==2:
dequeue()
elif choice==3:
display()
elif choice==4:
break
else:
print("Invalid Option!!!")
| true |
9c32c6f04008ee41b782f37db90cf390b63b2ad7 | namesake08/Practice | /Python/Stepic.org.67/1.12/step1/Heron's_formula.py | 778 | 4.125 | 4 | import math
print('Введите целочисленное значение равное первой стороне треугольника:')
a = int(input())
print('Введите целочисленное значение равное второй стороне треугольника:')
b = int(input())
print('Введите целочисленное значение равное третьей стороне треугольника:')
c = int(input())
p = (a + b + c) / 2
print('Полупериметр треугольника равен: ', str(p))
expr = p*(p - a)*(p - b)*(p - c)
print('Площадь треугольника равна корню квадратному числа ' + str(expr))
S = math.sqrt(expr)
print('Ответ: ' + str(S))
| false |
709dcfcec11186f9ef5885e31798ae2f69412040 | namesake08/Practice | /Python/syntaxExamples/str_format.py | 772 | 4.375 | 4 | #!/usr/bin/env python3
age = 25
name = 'Namesake'
print('Возраст {0} -- {1} лет.'.format(name, age))
print('Почему {0} забавляется с этим Python'.format(name))
age = 33
name = "Swaroop"
print("Возраст {} -- {} года.".format(name, age))
print('Почему {} забавляется с этим Python?'.format(name))
# десятичное число (.) с точностью в 3 знака для плавающих:
print('{0:.3}'.format(1/3))
# заполнить подчеркиванием (_) с центровкой текста (^) по ширине 11:
print('{:_^27}'.format('hello'))
# по ключевым словам:
print('{name} написал {book}'.format(name='Swaroop', book="A Byte of Python")) | false |
1bfde749e54bcc71a1ea95bceee4dd69a7ba9140 | wrayta/Python-Coding-Bat | /double_char.py | 316 | 4.21875 | 4 | """"
Given a string, return a string where for every char in the original, there
are two chars.
double_char('The') → 'TThhee'
double_char('AAbb') → 'AAAAbbbb'
double_char('Hi-There') → 'HHii--TThheerree'
"""
def double_char(str):
newStr = ""
for i in str:
newStr += (i + i)
return newStr
| true |
0a2fde8621ce24f4cc61ba358a04d07133d34f59 | HoanVanHuynh/Abstraction_Barriers | /rational_numbers.py | 969 | 4.28125 | 4 | def rational(n, d):
""" Return the rational number with numerator n and denominator d."""
def numer(rat):
""" Return the numerator of the rational number rat."""
def denom(rat):
""" Return the denominator of the rational number rat."""
def mul_rational(rat1, rat2):
""" Multiply rat1 and rat2 and return a new rational number."""
return rational(numer(rat1) * numer(rat2), denom(rat1) * denom(rat2))
# Implementing Rational Numbers
# There are many different ways we could choose to implement rational numbers
# One of the simplest is to use lists
from fractions import gcd # Greatest common divisor
# This is a constructor that allow us to construct new instances of the data type
def rational(n, d):
divisor = gcd(n,d) # Reduce to lowest terms
return [n//divisor, d//divisor]
# This is a selector that allow us to access the different parts of the data type
def numer(rat):
return rat[0]
def denom(rat):
return rat[1] | true |
80fd88a246a67e4727f4cc9c0be1d9bc3431865b | RealRoRo/Python | /lista.py | 830 | 4.34375 | 4 | friends = ["Sandeep", "Dino", "Amal", "Amal", "Terin", "Francis", "Abay", "Adarsh", "Ajith", "Akhil", "Hridik"]
fruits = ["apple", "banana", "orange", "pineapple"]
print("friends :",friends)
print("fruits :",fruits)
print("friends[2:5] :",friends[2:5])
friends.extend(fruits)
print("friends.extend(fruits) : ",friends)
fruits.append("mango") #atlaaast
fruits.insert(2,"chikoo") #at some position
print("add chichkoo at 2 and append mango",fruits)
fruits.remove("pineapple")
print("removed pineapple :",fruits)
fruits.pop();print("popped :",fruits)
#clear() used to cler the list
print("Index of dino",friends.index("Dino"))
print("Count of amal in friends : ",friends.count("Amal"))
friends.sort()
print("sorted list :",friends)
friends.reverse()
print("reversed :",friends)
friends2 = friends.copy()
print("copy : ",friends2) | false |
2b9d4d8320fb4ef055c995faa30eb832b7fe5d25 | raytuck/level3trial | /GUI_Exemplar1.py | 1,017 | 4.5 | 4 | # Program to demonstrate a simple GUI
# user enters name which is displayed on screen
import tkinter as tk
from tkinter import ttk
# create master window
master = tk.Tk()
master.title('GUI Demo')
# functions and handlers
def enterdata():
displaytext.set("My name is " + entrybox_text.get())
# Create widgets and place in window
# label to label the entry textbox
entry_label = ttk.Label(master, text="Please enter your name")
entry_label.grid(row=0, column=0)
# Entry box for user to enter name
entrybox_text = tk.StringVar()
entrybox = ttk.Entry(master, width=50, textvariable=entrybox_text)
entrybox.grid(row=0, column=1)
# user presses button, calls handler to entername
entry_button = ttk.Button(master, text='yes', command=enterdata)
entry_button.grid(row=0, column=2)
# Label to display message including name
displaytext = tk.StringVar()
displaybox = ttk.Label(master, textvariable=displaytext)
displaybox.grid(row=1, column=0, columnspan=3, sticky=tk.W+tk.E)
# main event loop
master.mainloop()
| true |
1df5bcea0716c49719c77184ed0c50f85c6d5ebe | SeniorZhai/Python | /2_2senior.py | 2,323 | 4.21875 | 4 | #!/usr/bin/env python
# -*-coding: utf-8 -*-
#切片
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
print L[0:3]
print L[-2:]
print L[-2:-1]
L = range(100)
print L
#可以通过切片轻松取出某一段数列。比如前10个数:
print L[:10]
#后10个数:
print L[-10:]
#前11-20个数:
print L[10:20]
#前10个数,每两个取一个:
print L[:10:2]
#所有数,每5个取一个:
print L[::5]
#甚至什么都不写,只写[:]就可以原样复制一个list:
print L[:]
#tuple也可以使用切片
#迭代
#给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们成为迭代(Iteration)
#在Python中,迭代是通过for ... in来完成的
print u'迭代dict'
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print key
for ch in d.itervalues():
print ch
for k, v in d.iteritems():
print k
print v
print u'字符串也可以迭代'
for ch in 'ABC':
print ch
print u'判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断'
#print isinstance('abc',Iterable)
#print isinstance([1,2,3],Iterable)
#print isinstance(123,Iterable)
for i, value in enumerate(['A', 'B', 'C']):
print i, value
#列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式
print range(1,11)
print [x * x for x in range(1,11)]
print [x * x for x in range(1,11) if x % 2 ==0]
# 生成全排列
print [m + n for m in 'ABC' for n in'XYZ']
#dict的iteritems()可以同时迭代key和value
d = {'x':'A','y':'B','z':'C'}
for k,v in d.iteritems():
print k,'=',v
#也可以用列表生成式
print [k + '=' + v for k,v in d.iteritems()]
print [s.lower() for s in d]
#Python中,这种一边循环一边计算的机制,称为生成器(Generator)
g = (x*x for x in range(10))
i = 0
while i < 10:
i = i + 1
print g.next()
def fab(max):
n,a,b = 0,0,1
while n < max:
print b
a,b = b,a+b
n = n + 1
fab(10)
def fab2(max):
n,a,b = 0,0,1
while n < max:
yield b
a,b = b,a+b
n = n + 1
#generator的另一种方法,yield
#yield作用每次调用函数是,遇到yield返回,再次执行时从上次返回的yield语句处继续执行
def odd():
print 'step 1'
yield
print 'step 2'
yield
print 'step 3'
yield
o = odd()
o.next()
o.next()
o.next() | false |
99c51dff7bbd41923b3453767e415a48216f6c0b | iamzubairnaseer/Simple-Calculator | /hyperf.py | 481 | 4.125 | 4 | def hyper():
print('Which Hyperbolic function you want to use?:')
trig=input('a)sinhx\t\tb)coshx\t\tc)tanhx\n')
angle=int(input('Enter the angle:'))
e=2.718281828459045
sinhx=((e**angle)-(e**(-angle)))/2
coshx=((e**angle)+(e**(-angle)))/2
if trig=='a':
print(sinhx)
print('')
elif trig=='b':
print(coshx)
print('')
elif trig=='c':
tanhx=sinhx/coshx
print(tanhx)
print('')
| false |
794a199f2674339116b08df78067944a4213d2c2 | outofboundscommunications/courserapython | /7Files/assignment7_2.py | 1,117 | 4.4375 | 4 | '''
7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for
lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those
values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.
You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt when you are testing below
enter mbox-short.txt as the file name.
'''
myCounter = 0
myTotal = 0
# Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") :
continue
#increment the counter
myCounter += 1
#parse out the numeric portion
zeropos = line.find('0')
numText = line[zeropos:]
numFloat = float(numText)
#print numFloat
#add value to sum
myTotal = myTotal + numFloat
#calculate average
myAverage = float(myTotal/myCounter)
print 'Average spam confidence:', myAverage
| true |
52a0597bcaefbdfc349399605d79fda5fc9a28ff | FrankYanCheng/Python | /LearnPythonTheHardWay/ex32.py | 510 | 4.5 | 4 | #Loops and Lists
the_count=[1,2,3,4,5]
fruits=['apple','oranges','pears','apricots']
change=[1,'pennies',2,'dimes',3,'quarters']
#this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
#same as above
for fruit in fruits:
print "A fruit of type: %r" % fruit
for i in change:
print "I got %r" % i
elements=[]
for i in range(0,6):
print "Adding %d to the list." % i
elements.append(i)
for i in elements:
print "Element was: %d" % i
| true |
ff96801e618db6170a24258fc1ad8023dc96d23d | TimurNurlygayanov/CatBoostExamples | /predict_number/predict.py | 1,338 | 4.125 | 4 | # This code shows how we can use CatBoot lirary to classify
# some objects and identify the object
#
# How to run:
# python predict.py
#
import numpy as np
from catboost import CatBoostClassifier
# Train data which will be used to train our NeuronNet.
# Here [0, 0, 0, 0, 1] means '1', [0, 0, 1, 0, 1] means 5 and etc.
# so we just define the correct data to teach our AI:
train_data = [[0, 0, 0, 0, 1], [0, 0, 0, 1, 0], [0, 0, 0, 1, 1],
[0, 0, 1, 0, 0], [0, 0, 1, 0, 1], [0, 0, 1, 1, 0]]
train_label = ['1', '2', '3', '4', '5', '6']
# Some test data which we want to classify somehow. Let's imagine
# that we don't know what [0, 0, 0, 0, 1] means. And let's ask AI
# to recognize this object for us:
test_data = [[1, 0, 1, 0, 1]]
# Specify the training parameters:
model = CatBoostClassifier(iterations=1000, thread_count=16,
loss_function='MultiClass',
verbose=True)
# Train the model using prepared right data:
model.fit(train_data, train_label, verbose=True)
# Save the model and restore model from file:
model.save_model('catboost_model.dump')
model.load_model('catboost_model.dump')
# Make the prediction using the resulting model
preds_class = model.predict(test_data)
# Print the prediction:
print('This object is {0}'.format(preds_class[0][0]))
| true |
a521df6a3a2698f8a477406e100e77099a766392 | Pratistha13/Python | /Calculator.error.py | 1,367 | 4.15625 | 4 | import math
print("Calculator")
def calculator():
while True:
try:
number = int(input("Give a number"))
return number
except(TypeError, ValueError):
print("This input is invalid.")
options = True
while True:
if options:
firstnumber = calculator()
secondnumber = calculator()
options = False
print("(1) +\n(2) -\n(3) *\n(4) /\n(5)sin(number1/number2)\n(6)cos(number1/number2)\n(7)Change numbers\n(8)Quit")
print("Current numbers: ", firstnumber, secondnumber)
select = int(input("Please select something (1-6): "))
if select == 1:
sum = firstnumber + secondnumber
print("The result is: ", sum)
elif select == 2:
sub = firstnumber - secondnumber
print("The result is: ", sub)
elif select == 3:
mul = firstnumber * secondnumber
print("The result is: ", mul)
elif select == 4:
div = firstnumber / secondnumber
print("The result is: ", div)
elif select == 5:
print("The result is: ", math.sin(firstnumber / secondnumber))
elif select == 6:
print("The result is: ", math.cos(firstnumber / secondnumber))
elif select == 8:
print("Thank you!")
break
elif select == 7:
options = True
else:
print("Nothing to show")
| true |
d12e5984c887b4facd9ba49df50313acf7306dd8 | shubham22121998/python-oop | /inheritance 19.py | 1,156 | 4.15625 | 4 | #multiple inheritance
class Phone:
def __init__(self,brand,price):
self.brand=brand
self.price=price
def buy(self):
print("buying the phone")
def return_product(self):
print("return the product")
class Product:
def review(self):
print("give your review to product")
class smart_phone(Phone,Product):
pass
s=smart_phone("appel",120000)
s.buy()
s.review()
'''
When a child is inheriting from multiple parents, and if there is a common behavior to be inherited, it inherits the method in
Parent class which is first in the list. In our example, the buy() of Product is inherited as it appears first in the list
'''
print("---------------------------------------------------------------------------------")
class Phone:
def __init__(self,brand,price):
self.brand=brand
self.price=price
def buy(self):
print("buying the phone")
def return_product(self):
print("return the product")
class Product:
def review(self):
print("give your review to product")
class smart_phone(Product,Phone):
pass
s=smart_phone("appel",120000)
s.buy()
s.review() | true |
f38f6333a4d989c19f115f3bc7b638d56107b891 | indraaani/LPTHW | /exercises/ex19.py | 1,184 | 4.15625 | 4 | # Ex19: Functions & Variables
# uses the *args function definition, applying
# two variables cheese_count, boxes_of_crackers to cheese_and_crackers
def cheese_and_crackers(cheese_count, boxes_of_crackers):
# stores the strings that will be printed when cheese_and_crackers is used
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
# gives two numerical values to cheese_count and boxes_of_crackers respectively
print "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)
# assigns values to variables and uses them in cheese_and_crackers
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
# gives a sum which will be added up once printed
print "We can even do the math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)
# gives the fuction def a combination of variables and numbers
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
| true |
b9a0684e8b3d0e5f68c86183bcf22a3d328147f6 | brandeil/python_tutorial | /lists.py | 2,212 | 4.40625 | 4 | # Lists: ordered , mutable, allows duplicate elements
mylist = ["banana", "cherry", "apple"]
print(mylist)
mylist2 = list()
print(mylist2)
# list can have different data types
mylist3= [5, True, "apple"]
print(mylist3)
# access element by index (start at 0)
item = mylist[0]
print(item)
last_item = mylist[-1] #-1 is the last item
print(last_item)
# iterate over a list with for loop
for i in mylist3:
print(i)
# check if item exists
if "apple" in mylist3:
print("yes")
else:
print("no")
# check number of elements in a list with len method
print(len(mylist3))
# append items to end of list
mylist3.append("lemon")
print(mylist3)
# insert in specific position
mylist3.insert(1, "blueberry")
print(mylist3)
# remove last item with pop method
item = mylist3.pop()
print(item)
print(mylist3)
#remove specific element with remove method
item = mylist3.remove("blueberry")
print(mylist3)
# remove all elements with clear method
item = mylist2.clear()
print(mylist2)
# reverse a list
mylist3.reverse()
print(mylist3)
# sort a list
numberlist = [2 , 7, 3, 2, 5,6 , 11, 5]
print(numberlist)
numberlist.sort()
print(numberlist)
new_list = sorted(mylist) # won't change the original list
# concat 2 lists with + operator
list1 = ["apple", "bear"]
list2 = ["dinosaur", "rat"]
list3 = list1 + list2
print(sorted(list3))
# slice for access subparts of a list
list_a = [1, 2, 3, 4, 5,6 ,7 ,8,9]
a= list_a[1:5]
print(a)
a=list_a[3:] # gets everything from index 3 to the end
print(a)
# copy a list
list_orig = ["apple", "banana", "cherry"]
list_copy = list_orig.copy()
list_copy = list(list_orig)
list_copy = list_orig[:] # [:] gets everything from list
print(list_copy)
# count number of elements in a list
names = ["John", "John", "Roger"]
print(names.count("John"))
# find the index of an item in a list
print(names.index("Roger"))
# unpacking a list
person = "Max", 28, "Boston"
name, age, city = person # number of elements on left side must match number of elements on right side
print(city)
print(age)
# unpacking a list with a wildcard
letters = ["a", "d", "x", "y", "z", "t"]
i1, *i2, i3 = letters
print(i1) # "a"
print(i2) # returns list ["d", "x", "y", "z"]
print(i3) # "t" | true |
22540d6fcd34fc29f0d39a8c4b9cb76d1dfe2e01 | foxcodenine/tutorials | /udemy_courses/Intro_To_SQLite_Databases_for_Python/Using SQLite With Python/db3-updating.py | 1,578 | 4.1875 | 4 | import sqlite3
connection = sqlite3.connect('customer.db')
c = connection.cursor()
def LINE():
print('--------------------')
LINE()#_________________________________________________________________
# Print database
c.execute("SELECT rowid, * FROM customers")
customer_db = c.fetchall()
for x in customer_db:
print(x)
LINE()#_________________________________________________________________
# 9. Update Records
c.execute(
"""
UPDATE customers SET first_name = 'Roderick'
WHERE last_name = 'Cassar'
"""
)
# reprint
c.execute('SELECT rowid, * FROM customers')
customer_db = c.fetchall()
for x in customer_db:
print(x)
# Here we have update a record first_name by selecting with last_name
# However if here will be multiple records with the same name
# they all will be changed
LINE()#_________________________________________________________________
# Updating with rowid:
c.execute(
"""
UPDATE customers SET first_name = 'Dorothy'
WHERE rowid = 4
"""
)
# reprint
c.execute('SELECT rowid, * FROM customers')
customer_db = c.fetchall()
for x in customer_db:
print(x)
LINE()#_________________________________________________________________
# 10. Delete Records
c.execute("DELETE FROM customers WHERE rowid = 8")
# Here we have delete 'Roderick' row 8 from our database
c.execute("SELECT rowid, * FROM customers")
customer_db = c.fetchall()
for x in customer_db:
print(x)
LINE()#_________________________________________________________________
connection.commit()
connection.close() | true |
46826bda48ce1224bb4db5c90f6ea0d42a644dc4 | theknight374121/PythonDataStructures | /Stack.py | 2,297 | 4.25 | 4 | class Node(object):
'''
Node Class for SingleLinkedList class
'''
def __init__(self, data=0):
'''
Constructor for Node Class
'''
self.__value = data
self.__next = None
def getValue(self):
'''
Returns the Value of the Node
'''
return self.__value
def setValue(self, data):
'''
Sets the Value of the Node
'''
self.__value = data
def getNext(self):
'''
Returns the NextPtr of the Node
'''
return self.__next
def setNext(self, node_obj):
'''
Sets the NextPtr of the Node
'''
self.__next = node_obj
class Stack(object):
'''
Python 2.7 implementation of Single Linked List
'''
def __init__(self):
'''
Constructor of SingleLinkedList class
'''
self.head = None
self.tail = None
self.size = 0
def length(self):
'''
Function returns the size of the LinkedList
'''
return self.size
def push(self, data):
'''
Adds new Node to the end of the Stack
'''
if (self.size == 0):
#If there exists no Nodes in the Stack
new_node = Node(data)
self.head = new_node
self.tail = self.head
else:
new_node = Node(data)
self.tail.setNext(new_node)
self.tail = new_node
#Increment size of the List
self.size += 1
def pop(self):
if(self.size == 0):
print "No elements in the stack"
return -1
else:
#Travel to the tail
tmp_node = self.head
while(tmp_node.getNext() != self.tail):
tmp_node = tmp_node.getNext()
#Save the previous node to tail
tail_value = self.tail.getValue()
del(self.tail)
self.tail = tmp_node
#Decrement the size of the list
self.size -= 1
return tail_value
def peek(self):
if(self.size == 0):
print "No elements in the stack"
return -1
else:
return self.tail.getValue()
def printStack(self):
print "Printing Stack"
tmp_head = self.head
if (self.size == 0):
print "Stack is empty!"
else:
tmp_size = self.size
while (tmp_size > 0):
print '{} '.format(tmp_head.getValue()),
tmp_head = tmp_head.getNext()
tmp_size -= 1
print ""
def main():
'''
Main funciton to test the class
'''
mystack = Stack()
mystack.push(4)
mystack.push(2)
mystack.push(-1)
mystack.printStack()
print mystack.pop()
print mystack.peek()
if __name__ == "__main__":
main() | true |
564ba5c459cb77fa8e27cc20d13eec07139ec164 | GokulHunt/Codes_For_Fun | /tower_of_hanoi.py | 820 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 13 20:43:29 2021
@author: gokul
"""
#printing each move
def print_move(ring, fr, to):
print("Move ring "+str(ring)+" from "+str(fr)+" to "+str(to))
#function containing recursive calls to move all the rings from one spike to another
def move_rings(rings, n, fr, to, spare):
if n == 1:
if type(rings) == list:
rings = rings[0]
print_move(rings, fr, to)
else:
move_rings(rings[0:n-1], n-1, fr, spare, to)
move_rings(rings[-1], 1, fr, to, spare)
move_rings(rings[0:n-1], n-1, spare, to, fr)
def tower_of_hanoi(rings, n, fr, to, spare):
move_rings(rings, n, fr, to, spare)
return "Moved all the rings from "+str(fr)+" to "+str(to)
#function call
print(tower_of_hanoi([1,2,3,4], 4, 'P1', 'P2', 'P3')) | false |
4192f0f5653cfec689bf27fd9d710a8aebc476f9 | sonamk15/pythonFromSaral | /more_exercise_q4.py | 375 | 4.1875 | 4 | number1=int(raw_input("enter a number\n"))
number2=int(raw_input("enter another number\n"))
number3=int(raw_input("enter another number\n"))
if number1>number2 and number1>number3:
print number1,"is bigger than",number2,number3
elif number2>number3 and number2>number1:
print number2,"is bigger than",number1,number3
else:
print number3,"is bigger than",number1,number2
| true |
d13eb9916a1cb722c401d5e3685bf640851449e0 | sonamk15/pythonFromSaral | /more_exercise_q3.py | 564 | 4.1875 | 4 | user=raw_input("enter your password\n")
if len(user)<6:
print "weak password"
print "password must be more than 6 character"
elif len(user)>16:
print "weak password"
print "password is less than 16 character"
elif "$" not in user:
print "weak password"
print "password must have special character $"
elif "2" not in user and "8" not in user:
print "weak password"
print "password must have 2 or 8 number"
elif "A" not in user and "Z" not in user:
print "weak password"
print "password must have capital character A or Z"
else:
print "strong password"
| true |
16a0d515cb36facd6d5d24cdc7f2523a2b2fee27 | vincenzo-scotto001/Python | /Daily Coding Problems/Problem2Uber.py | 571 | 4.28125 | 4 | # Given an array of integers,
# return a new array such that each element at index i of the
# new array is the product of all the numbers in the original array except the one at i.
# For example, if our input was [1, 2, 3, 4, 5],
# the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1],
# the expected output would be [2, 3, 6]
def array(uber):
product = 1
for n in uber:
product *= n
for i in range(len(uber)):
uber[i] = product / uber[i]
uber = [1, 2, 3, 4, 5]
array(uber)
print(uber) | true |
ddb768ff12b7819929ec67c5e58aa7325dc8e9b2 | vincenzo-scotto001/Python | /Random/sco.analysisprob3.py | 621 | 4.1875 | 4 | # Analysis worksheet problem III by vincenzo scotto di uccio
course = int(input("Please enter the credits amount this course is: "))
grade = int(input(" Please enter the grade you got in that class 1-4 is d-a respectively: "))
a = 4
b = 3
c = 2
d = 1
if grade == a:
print ("Your gpa is: ", course * grade / course)
if grade == b:
print ("Your gpa is: ", course * grade / course)
if grade == c:
print ("Your gpa is: ", course * grade / course)
if grade == d:
print ("Your gpa is: ", course * grade / course)
if grade !=a or grade !=b or grade !=c or grade !=d:
print ("Error")
| false |
b63cabc3b17414b83486d4f01fbd262e2ed49660 | vincenzo-scotto001/Python | /Daily Coding Problems/Problem13Amazon.py | 1,417 | 4.15625 | 4 | # Given an integer k and a string s,
# find the length of the longest substring that contains at most k distinct characters.
# For example,
# given s = "abcba" and k = 2,
# the longest substring with k distinct characters is "bcb".
#first I will be asking the user for input
amazon = input('Please give me a string: ')
k = int(input('Please give me an integer: '))
#for ease I will be putting the length of the string into a variable
length = len(amazon)
def amazon1(string, integer):
#need a counter
count = 0
#for every i in the range of 1 and the length of the string plus 1
for i in range(1,length+1):
# for every j in the range of i
for j in range(i):
#if the length of the unique characters in the string from starting index j
# to the length of the of the string minus i plus j plus 1 is less than or equal to the k integer given
if len(set(amazon[j:length-i+j+1])) <= k:
#the substring with the maximum distinct values has been found so the substring is equal to the above
substring = amazon[j:length-i+j+1]
#increase the count to one
count = 1
break
#breaks the for loop
if count == 1:
break
#prints the substring
print(f'substring: {substring}')
amazon1(amazon,k) | true |
b58dc89ba50b96316126f96b41a7244cd0b58912 | vincenzo-scotto001/Python | /Random/validator_for_integers_or_floats.py | 1,331 | 4.34375 | 4 | #Sum of Numbers - by Cindy Ireland
# program accepts a positive integer and validates the input and
# prints back the number
def main():
print ('Echo of Numbers after validation by Cindy Ireland')
theInput = input("Enter a numeric value greater than or = to zero: ")
theInput = input_validator(theInput)
print ('The number entered is: ', theInput)
def input_validator(aString):
valueSwitch = 0
errorSwitch = 0
make_a_float = 0
while valueSwitch == 0:
errorSwitch = 0
for aChar in aString:
if (aChar >= '0' and aChar <= '9'):
errorSwitch = 0
elif aChar == '.':
make_a_float = 1
else:
errorSwitch = 1
break
#end of for loop
if errorSwitch > 0:
aString = input('ERROR! Enter a numeric value greater than or = to zero: ')
errorSwitch = 0
else:
valueSwitch = 1
if make_a_float == 1:
return float(aString)
else:
return int(aString)
# your program will actually start here.
main()
| true |
251c6ae84115bcf126c2cec00419d99f192311c8 | vincenzo-scotto001/Python | /chp 4 problems/sco.chp4prob8.py | 265 | 4.1875 | 4 | #Chapter IV problem VIII sum of numbers by Vincenzo Scotto Di Uccio
pos_num = 0
total = 0
while pos_num >=0:
pos_num = float(input(" Please put in a positive number: "))
if pos_num >= 0:
total = total + pos_num
print( " Your total is: ", total)
| true |
7cafa597becb1329162b09468f119dba98f39052 | HardBlaster/ML_linear_regression | /src/utils/plot_data.py | 918 | 4.125 | 4 | import matplotlib.pyplot as plt
# PLOTDATA Plots the data points x and y into a new figure
# PLOTDATA(x,y) plots the data points and gives the figure axes labels of
# population and profit.
def plot_data(x, y):
# ===================== Your Code Here =====================
# Instructions : Plot the training data into a figure using the matplotlib.pyplot
# "plt.scatter" function. Set the axis labels using "plt.xlabel"
# and "plt.ylabel". Assume the population and revenue data have
# been passed in as the x and y.
# Hint : You can use the 'marker' parameter in the "plt.scatter" function to change
# the marker type (e.g. "x", "o").
# Furthermore, you can change the color of markers with 'c' parameter.
# ===========================================================
plt.figure() # open a new figure window
| true |
8693657e8ecf0bc4a01ebcb28565d80b8da874b8 | jeanch325/MSU-St.-Andrews-Python | /ex03.py | 1,908 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 24 12:59:12 2020
@author: jeancho
"""
#ex03.py
#Part A
def leap_year(year):
'''
Leap year calculator
Value: integer input
Returns: True or False
'''
if int(year) % 400 == 0:
return True
elif int(year) % 4 == 0 and year % 100 != 0:
return True
else:
return False
#Part B
def rotate(s,n):
'''
Rotates string
Value: string input s, integer input n
Returns: rotated string; last n characters moved to beginning
'''
n = int(n)
s = str(s)
if len(s) <= 1:
return s
elif n > 0 and n <= len(s):
return s[len(s) - n :] + s[:len(s) - n]
else:
print('Input larger than string length')
#Part C:
def digit_count(num):
'''
Counts digits
Value: int or float
Returns: count of even & odd digits and zeros left of decimal point
'''
evens = 0
odds = 0
zeroes = 0
num = int(num)
for i in str(num):
if i != '.':
if int(i) % 2 == 0 and int(i) != 0:
evens += 1
elif int(i) == 0:
zeroes += 1
else:
odds += 1
return(evens, odds, zeroes)
#Part D:
def float_check(digits):
'''
Checks for floats
Value: integers or floats with digits
Returns: True or False
'''
dotcount = 0
digits = str(digits)
if digits.isdigit():
return True
for i in digits:
if i == '.':
dotcount += 1
elif not i.isdigit() and i != '.':
return False
if dotcount > 1:
return False
return True
#Code start:
if __name__ == '__main__':
print(leap_year(1896))
print(rotate('abcdefgh', 3))
print(digit_count(0.123))
print(float_check('123.45'))
| true |
eaf80a7ff3c8f7a00e09e6ae859ab53019c04886 | KuldeepChaturvedi/100_Days_Of_Python | /Getting Started With Python/string_operations.py | 1,090 | 4.59375 | 5 | #!/usr/bin/python
'''
'''
# Declaring a string variable and assigning value to it.
name = 'Test String'
# This will print the value of name
print('--------'*4)
print('Printing the string variable.')
print(name)
# Lets try to concat the name with Hello World.
print('--------'*4)
print('Concatination of string variable wiht Hello Wolrd.')
print(name + ' Hello World')
# Lets try to print first letter of our name variabe. Indexing starts with 0 so we will takes the o for our first letter
print('--------'*4)
print('Printing the first letter of string variable.')
print(name[0])
# Lets try to print last letter of our name variabe. We can take last letter using negative index.
print('--------'*4)
print('Printing the last letter of string variable.')
print(name[-1])
# Lets try to print using range.
print('--------'*4)
print('Printing letter which index is 2 upto index 10.')
print(name[2:10])
print('Printing letter which index is 5 upto unknown index which is last.')
print(name[5:])
print('Printing letter which last index is 7 from unknown index which is first.')
print(name[:7])
| true |
3385164a9f0fbba64ee9b93b0886a3422dd6bb46 | Vipexi/python_course_2021 | /counter/task7_counter_easy.py | 1,048 | 4.40625 | 4 | #! /usr/bin/python3
# original author: Ville Vihtalahti
# I the author grant the use of this code for teaching: yes
# Easy task: Build a calculator, which asks the user for a number,
# and calculates the sum of all numbers from 0 to the usergiven input using for loop.
# For example if given number is 5, then the program counts 0+1+2+3+4+5=15
# or 7 0+1+2+3+4+5+6+7=28.
def counter():
number=int(input("Give a number:"))
sum_of_numbers = 0
for i in range(number):
sum_of_numbers += i
print("The sum was:",sum_of_numbers)
counter()
#OR
def counter2():
number=int(input("Give a number:"))
sum_of_numbers = 0
for i in range(number):
sum_of_numbers = sum_of_numbers + i
print("The sum was:",sum_of_numbers)
counter2()
# Solution:
# First I asked the user to give an number as an input.
# Then I made a variable that has 0 in it
# Then use for loop for times given by the user.
# +=i makes the counter add the number for each turn inside the variable
# The later example explains better what the +=i does
| true |
41b7df7d1479dd1fa6fb6b3606c1e76d6defe85f | zhangchaowei/Study-Notes | /Algorithms/Search_Algorithms/Linear_Search.py | 839 | 4.15625 | 4 | """
linear search
complexity O(n)
Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
If x matches with an element, return the index.
If x doesn’t match with any of elements, return -1.
"""
def linearSearch(arr, n, x):
for i in range(0, n):
if arr[i] == x:
return i
return -1
str_arr = input('Input an array with number and space (ex: XXX XX XX XXX): ').split(' ')
int_arr = list(map(int, str_arr))
target = input('The number you are searching for: ')
print('----------------------------')
print('Your array will be: ', int_arr)
print('Your target will be: ', target)
result = linearSearch(int_arr, len(int_arr), target)
if result == -1:
print('The number you are looking for is not in array')
else:
print('Found at index: ', result)
| true |
e12ad2524f9e3916e3d2428f5ed23363967eaa56 | SimranParajuli/assignment_II | /no6.py | 435 | 4.34375 | 4 | #Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.
#Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
#Expected Output : ['Green', 'White', 'Black']
list = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow','Purple','Blue']
print("The list is",list)
list.pop(0)
list.pop(4)
list.pop(5)
print("The list after removing the0th 4th and 5th element is: ",list)
| true |
195f557ce6f1c338a5be40fd32f0b2dfff0e9cb9 | siddharth456/Python_Scripts_1 | /identity_matrix.py | 238 | 4.15625 | 4 | '''Prints an identity matrix'''
x=int(input("Enter a number:"))
for i in range(0,x):
for j in range(0,x):
if i==j:
print("1",sep=" ",end=" ")
else:
print("0",sep=" ",end=" ")
print()
| false |
daf5ed34772781b1f30d0f32e3ba065dfbf20813 | siddharth456/Python_Scripts_1 | /union_of_3_lists.py | 242 | 4.21875 | 4 | # Program demonstrates union of two or more lists
def union(lst1,lst2,lst3):
final_list=list(set().union(lst1,lst2,lst3))
return final_list
# Driver Code
lst1=[1,2,3]
lst2=[4,5,6,7]
lst3=[8,9,10]
print(union(lst1,lst2,lst3)) | true |
4228a53c3f350ece314275501470874289553f3c | siddharth456/Python_Scripts_1 | /intersection_of_2_lists.py | 493 | 4.125 | 4 | # Program to illustrate the intersection of two lists
# Method-1
#def intersection(lst1,lst2):
# lst3=[i for i in lst1 if i in lst2]
# return lst3
# Method-2
#def intersection(lst1,lst2):
# lst3=list(set(lst1) & set(lst2))
# return lst3
# Method-3
def intersection(lst1,lst2):
lst3=set(lst1).intersection(lst2)
return lst3
#Driver Code
lst1=[1,4,7,11,15,19,23,27,31,35,39,43,47]
lst2=[1,3,5,7,21,23,41,35,39,47,50]
print(intersection(lst1,lst2))
| false |
04127486008fc51b4a2a2a466944d7dc9bae818d | johnehunt/PythonCleanCode | /07-interfaces/polymorphism/night_out.py | 942 | 4.4375 | 4 | # Example Illustrating Polymorphism
class Person:
def eat(self): print('Person - Eat')
def drink(self): print('Person - Drink')
def sleep(self): print('Person - Sleep')
class Employee(Person):
def eat(self): print('Employee - Eat')
def drink(self): print('Employee - Drink')
def sleep(self): print('Employee - Sleep')
class SalesPerson(Employee):
def eat(self): print('SalesPerson - Eat')
def drink(self): print('SalesPerson - Drink')
class Dog:
def eat(self): print('Dog - Eat')
def drink(self): print('Dog - Drink')
def sleep(self): print('Dog - Sleep')
def night_out(p):
p.eat()
p.drink()
p.sleep()
# Create instances of each type
p = Person()
e = Employee()
s = SalesPerson()
d = Dog()
# Now use the function night_out
# with each type of object
print('-' * 25)
night_out(p)
print('-' * 25)
night_out(e)
print('-' * 25)
night_out(s)
print('-' * 25)
night_out(d)
| false |
f436adc2f7754e5f5dbf47c803b511c1c9b1fa0f | swilsonmfc/oop4ds | /13_scoping.py | 2,264 | 4.125 | 4 | # %% [md]
# # Scoping - Instance, Class & Static Methods
# %% [md]
# # Instance Methods
# * A method available to the instance
# * Has a reference to self
# * With a reference to self, it has access to the instance state
# %% codecell
class MyClass():
def instanceWork(self):
print('Instance Method - Work')
# %% codecell
my = MyClass()
my.instanceWork()
# %% [md]
# # Class Methods
# To attach a method to a class, use the @classmethod annotation and
# rather than self, use cls as the first parameter
# %% codecell
class MyClass():
def instanceWork(self):
print('Instance Method - Work')
print(self)
@classmethod
def classWork(cls):
print('Class Method - Work')
print(cls)
# %% [md]
# You can call class methods using your reference to the class instance
# %% codecell
my = MyClass()
my.instanceWork()
my.classWork()
# %% [md]
# You can also call class methods using the class name
# %% codecell
MyClass.classWork()
# %% [md]
# # Usage : Alternative Constructors
# Class methods are great for creating alternative Constructors
# %% codecell
from datetime import date
# %% codecell
class Customer():
def __init__(self, firstName:str, lastName:str, age:int):
self.firstName = firstName
self.lastName = lastName
self.age = age
def output(self):
print(self.firstName, self.lastName, self.age)
@classmethod
def fromFullName(cls, fullName:str, age:int):
firstName, lastName = fullName.split(' ')
return cls(firstName, lastName, age)
# %% codecell
c1 = Customer('Anne', 'Smith', 30)
c2 = Customer.fromFullName('Cindy Williams', 50)
c1.output()
c2.output()
# %% [md]
# # Static Methods
# Convenient for grouping methods that logically make sense in a class
# but do not require an object. Helper methods are good candidates for
# staticmethods in classes.
# %% codecell
class MyClass():
def instanceWork(self):
print('Instance Method - Work')
print(self)
@classmethod
def classWork(cls):
print('Class Method - Work')
print(cls)
@staticmethod
def staticWork():
print('Static Method - Work')
# %% codecell
c = MyClass()
c.staticWork()
# %% codecell
MyClass.staticWork() | true |
4ddad6d54a66b30a1cf2b3ee85268ba857c1dd60 | rodlewis360/learntocodepython | /learntocodepython2.py | 1,636 | 4.3125 | 4 | def learn():
from time import sleep()
print("Learn to code python with this interactive tutorial!")
print("===================TUTORIAL2=========================")
sleep(5)
print("Remember What we did in the last tutorial?")
sleep(2.5)
print("But let's put this in a function. We are going to call it \"hello\".")
print("Type exactly what you see:")
print("def hello():")
print(" print(\"Hello, World!\")
stuff = []
while stuff != ["def hello():", " print(\"Hello, World!\")"]:
stuff.append(input())
stuff.append(input())
print("Good job! Now lets do something useful:")
print("def count():")
print(" n = 0")
print(" a = input(\"What number?\)")
print(" while n < a:")
print(" print(n)")
print(" n += 1")
print(" print(\"done!\"))
print("Remember that each indent is four spaces.")
while inputstuff != ["def hello():", " n = 0", " a = input(\"What number?\")", " while n < a:", " print(n)", " n += 1", " print(\"done!\")"]:
inputstuff = []
inputstuff.append(input())
inputstuff.append(input())
inputstuff.append(input())
inputstuff.append(input())
inputstuff.append(input())
inputstuff.append(input())
inputstuff.append(input())
inputstuff.append(input())
print("Remember that each indent is four spaces.")
print("Now type \"hello()\".")
def hello():
n = 0
a = input("What number?")
while n < a:
print(n)
n += 1
print("done!")
| true |
aa5f77feb42e1de28dc1cf3989c242f00f9fdcc2 | amruthasanthosh0/python | /reversellist.py | 846 | 4.125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class linkedlist:
def __init__(self): #head
self.head=None
def printlist(self):
temp=self.head
while(temp):
print (temp.data)
temp=temp.next
def reverse(self):
prev=None
current=self.head
while(current is not None):
next=current.next
current.next=prev
prev=current
current=next
self.head=prev
def push(self,new_data):
new_node=Node(new_data)
new_node.next=self.head
self.head=new_node
n=int(input("enter the number of elements"))
llist=linkedlist()
print("enter the elements")
for i in range(0,n):
l=int(input())
llist.push(l)
llist.reverse()
print ("reversed linkedlist is")
llist.printlist()
| true |
4b4f4a02d9220e1200b479a45b232490f145fdcb | amruthasanthosh0/python | /secondlarge.py | 309 | 4.15625 | 4 | import array as arr
import numpy as np
def secondlarge(x):
x=np.sort(x)
return x[len(x)-2]
array=arr.array('i',[])
n=int(input("enter the number of elements: "))
for i in range (0,n):
ele=int(input())
array.insert(i,ele)
print(f"""the second largest number of array is : {secondlarge(array)}""")
| true |
5b0826b07fe85420f8d3539d0934c8a9bd8fd65c | RichardCharczenko/SU_Bio | /evo/SimClimate.py | 2,203 | 4.125 | 4 | '''
file: SimClimate.py
Author: Richard Charczenko
See: Seattle University Biology Department
'''
import random
class Simulate_Climate():
'''simulates climate for a given number of years and if desired change'''
def __init__(self, change, yrs):
self.climate = change
self.years = yrs
def generate_climate(self):
count = 0
weekStart = random.choice([21, 22, 23, 24, 25, 26, 27, 28])
week = weekStart
outPut = {}
if self.climate == "change":
while count < self.years: #generates climate change, plunging week of snow thaw
count += 1
b = random.choice(range(100))
o = weekStart - week
p = weekStart + 1
if o > 13:
week = week + 2
outPut[count] = week
elif week == weekStart:
y = random.choice(range(100))
if y < 51:
week = week - 2
outPut[count] = week
else:
outPut[count] = week
elif week >= p:
week = week - 2
outPut[count] = week
else:
if b <= 10:
c = random.choice(range(100))
if c < 40 or c == 40:
week = week - 2
else:
week = week - 1
outPut[count] = week
elif b in [11, 12, 13, 14]:
d = random.choice(range(100))
if d < 10 or d == 10:
week = week + 2
else:
week = week + 1
outPut[count] = week
else:
outPut[count] = week
else:
for i in range(self.years):
outPut[i+1] = week - random.choice([-1,0,1])
return outPut
| false |
e9a28eaaa5d55c0b186a4cd7f143620549047bed | shubin-denis/Python | /Lesson_2/task_3.py | 1,812 | 4.4375 | 4 | # Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
# Напишите решения через list и через dict.
number_of_month = int(input('Введите номер месяца: '))
# 1) Решение через list
# list_of_seasons = ['зима', 'весна', 'лето', 'осень']
#
# if 0 < number_of_month <= 2 or 11 < number_of_month < 13:
# print(f'Такой месяц относится к времени года "{list_of_seasons[0]}"')
# elif 3 <= number_of_month <= 5:
# print(f'Такой месяц относится к времени года "{list_of_seasons[1]}"')
# elif 6 <= number_of_month <= 8:
# print(f'Такой месяц относится к времени года "{list_of_seasons[2]}"')
# elif 9 <= number_of_month <= 11:
# print(f'Такой месяц относится к времени года "{list_of_seasons[3]}"')
# else:
# print('Такого месяца не существует!')
# Решение через dict
dict_of_seasons = {'зима': [1, 2, 12],
'весна': [3, 4, 5],
'лето': [6, 7, 8],
'осень': [9, 10, 11]
}
if number_of_month <= 0 or number_of_month > 12:
print('Такого месяца не существует!')
else:
for el, month in dict_of_seasons.items():
month_list = list(month)
i = 0
while i < len(month_list):
if number_of_month == month_list[i]:
print(f'Такой месяц относится к времени года "{el}"')
i += 1
| false |
13c08a651fd181a26adad1325f9ef40452bd6a1f | shubin-denis/Python | /Lesson_1/task_6.py | 1,374 | 4.1875 | 4 | # Спортсмен занимается ежедневными пробежками. В первый день его результат составил a
# километров. Каждый день спортсмен увеличивал результат на 10 % относительно
# предыдущего. Требуется определить номер дня, на который результат спортсмена составит
# не менее b километров. Программа должна принимать значения параметров a и b и выводить
# одно натуральное число — номер дня.
# Например: a = 2, b = 3.
# Результат:
# 1-й день: 2
# 2-й день: 2,2
# 3-й день: 2,42
# 4-й день: 2,66
# 5-й день: 2,93
# 6-й день: 3,22
# Ответ: на 6-й день спортсмен достиг результата — не менее 3 км.
start = 2
finish = 4
day = 1
print('Результат: ')
while start < finish:
print(f'{day}-й день: {start}')
start = round(start + (start * 0.1), 2)
day += 1
if start > finish:
print(f'{day}-й день: {start}')
print(f'На {day}-й день спортсмен достиг результата — не менее {finish} км.')
break
| false |
8093e031b5b9ebc2edaea87a41e7826c3d2480e7 | amararias/CodeFights | /arcade/06_RainsOfReason/CF26_evenDigitsOnly.py | 330 | 4.28125 | 4 | # Check if all digits of the given integer are even.
# Example
# For n = 248622, the output should be
# evenDigitsOnly(n) = true;
# For n = 642386, the output should be
# evenDigitsOnly(n) = false.
def evenDigitsOnly(n):
return sum([int(x)%2 for x in str(n) if int(x)%2!=0])==0
n = 248623
print(
evenDigitsOnly(n)
) | true |
102ab001e7d50901d3c610a67cfbeefca23731d6 | amararias/CodeFights | /arcade/02_EdgeOfTheOcean/CF07_almostIncreasingSequence.py | 1,536 | 4.34375 | 4 | # Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
# Example
# For sequence = [1, 3, 2, 1], the output should be
# almostIncreasingSequence(sequence) = false;
# There is no one element in this array that can be removed in order to get a strictly increasing sequence.
# For sequence = [1, 3, 2], the output should be
# almostIncreasingSequence(sequence) = true.
# You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].
def first_bad_pair(sequence):
"""Return the first index of a pair of elements where the earlier
element is not less than the later elements. If no such pair
exists, return -1."""
for i in range(len(sequence)-1):
if sequence[i] >= sequence[i+1]:
return i
return -1
def almostIncreasingSequence(sequence):
"""Return whether it is possible to obtain a strictly increasing
sequence by removing no more than one element from the array."""
j = first_bad_pair(sequence)
if j == -1:
return True # List is increasing
if first_bad_pair(sequence[j-1:j] + sequence[j+1:]) == -1:
return True # Deleting earlier element makes increasing
if first_bad_pair(sequence[j:j+1] + sequence[j+2:]) == -1:
return True # Deleting later element makes increasing
return False # Deleting either does not make increasing
| true |
2456da96fc78032085db3915540fb19609403325 | SquaredSee/CLRS | /chapter_02/insertion_sort.py | 886 | 4.3125 | 4 | #!/usr/bin/env python3
def insertion_sort(A):
""" iterates through the array one item at a time, placing in the correct location """
if type(A) is not list:
raise TypeError('provided input is not a list')
for j in range(1, len(A)):
# key is the item currently being sorted
key = A[j]
i = j - 1
# compare key with all items to the left
while i >= 0 and A[i] > key:
# move items right if they are greater than key
A[i + 1] = A[i]
# decrement i to move left through the list
i = i - 1
A[i + 1] = key
if __name__ == '__main__':
import sys
try:
input_list = sys.argv[1]
except IndexError:
sys.exit('Usage: insertion_sort.py [1,2,3,4]')
input_list = input_list.strip('[]').split(',')
insertion_sort(input_list)
print(input_list)
| true |
9fd36ef0b357bb0feb709a000f939658222c63a5 | muratck86/GlobalAIHubCourse | /Homeworks/Day-3/HW3.py | 1,147 | 4.3125 | 4 | """
Day - 3
User login application:
-Get Username and Password values from the user.
-Check the values in an if statement and tell the user if they were successful.
Extra:
-Try building the same user login application but this time, use a dictionary.
"""
# Without dictionary...
# A sample user login information
username = "Murat"
password = "12345"
# the user has 3 try rights (for password)
counter = 3
while counter > 0: # if the user has no tries end the loop
try_name = input("Enter username: ") # get username
if try_name.capitalize() != username: # check the username (case insensitive)
print("User not found")
continue # If the username not found, don't run the rest of the code for this turn and restart the loop
try_pass = input("Enter password for " + username + ": ")
if try_pass != password:
counter -= 1 # if the passsword is wrong, decrease the counter
print("Wrong password. You have", counter, "tries remaining.")
else:
print("Login successful.")
break
if counter == 0:
print("User blocked, please contact administrator.")
| true |
6f5b169e668f94c50ff2c5511c4a687e0e55c684 | DeVilhena-Paulo/Geocoding | /geocoding/similarity.py | 2,979 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""String similarity methods.
This module defines the class used for computing the score of similarity
between two strings. Even with the ideas for computing this score are well know
(ngrams), the exactly method is not and that`s why an own implementation was
needed.
"""
class Similarity():
"""Class defining the string similarity methods using uni and bigrams.
One object of this class will have a set of uni and bigrams of a string s
as an attribute. The string s is an argument of __init__ and this set is
used in the score method to compute the score of similarity between s and
one second string t, for example.
Attributes:
slice_set (:obj:`set` of :obj:`str`): The set of uni and bigrams.
slice_set_score (int): The score of the attribute slice_set, that is,
the sum of the length of the strings in that set.
"""
def __init__(self, s):
"""
Args:
s (str): The string to compute the 1 and 2 grams set.
"""
self.slice_set = set(list(s) + self.k_letters_list(s, 2))
self.slice_set_score = self.set_score(self.slice_set)
def k_letters_list(self, s, k):
"""List of all the strings formed by k consecutive letters of s.
Divide a string s into a list of strings, where each string is formed
by k consecutive letters of s.
Args:
s (str): The string to divide.
k (int): The number of consecutive letters.
Returns:
(:obj:`list` of :obj:`str`): The list of strings with k consecutive
letters of s.
"""
return [s[i:(i + k)] for i in range(0, len(s) - (k - 1))]
def set_score(self, words_set):
"""Sum of the lentgh of all elements from a set of strings.
"""
return sum([len(word) for word in words_set])
def score(self, t):
"""String similarity score.
The score of similarity between two strings s and t is defined as the
score of the intersection over the score of the union of two sets: the
set of unigrams and bigrams of s and t.
Args:
t (str): The string to compare.
Returns:
(float): The score of similarity between t and the string s passed
as argument in the initialization of the class.
"""
# Union of the unigram and bigram of t
slice_set = set(list(t) + self.k_letters_list(t, 2))
slice_set_score = self.set_score(slice_set)
# The intersection between the slice_set of s and t.
intersection = slice_set & self.slice_set
intersection_score = self.set_score(intersection)
union_score = slice_set_score + self.slice_set_score - \
intersection_score
# The union_score is zero only if both s and t are empty
if union_score == 0:
return 0
return intersection_score / union_score
| true |
948770bf0951b39ca80ba39725a202808cc6279f | pradeepsinngh/A-Problem-A-Day | /by-data-structure/strings/medium/002-camelcass_matching.py | 926 | 4.1875 | 4 | # Prob: Camelcase Matching -- https://leetcode.com/problems/camelcase-matching/
```
A query word matches a given pattern if we can insert lowercase letters to the pattern word so that it equals the query. (We may insert each character at any position, and may insert 0 characters.)
Given a list of queries, and a pattern, return an answer list of booleans, where answer[i] is true if and only if queries[i] matches the pattern.
```
class Solution:
def camelMatch(self, queries, pattern):
res = []
for query in queries:
res.append(self.patt_match(query, pattern))
return res
def patt_match(self, query, pattern):
j = 0
for char in query:
if j < len(pattern) and char == pattern[j]:
j += 1
elif ord('Z') >= ord(char) >= ord('A'):
return False
print(j)
return len(pattern) == j
| true |
847f7e4698f396bd1ff7add696670f950f7d0d90 | pmaywad/DataStructure-Algo | /Queue/queueDeque.py | 280 | 4.125 | 4 | """
Implementation of Queue in python using deque
"""
from collections import deque
queue = deque()
queue.append(10)
queue.append(5)
queue.append(6)
print("Queue is ", queue)
#dequeue first element
print("Popped item is:", queue.popleft())
print("Remaining queue is:", queue)
| true |
b47f0b4108e3899298ca5713bec1d8422b9aa927 | Amilina/Project-App | /Mode3.py | 1,710 | 4.1875 | 4 | import click
print(" ")
print(10*"-", "GRAMMAR", 10*"-")
print("\nIn this mode we will train some basic german grammar.")
print("This means you type in some german text that consists of several sentences.")
print("The sentences should only contain a pronoun, the verb 'to be' and an adjective.")
print("Okay, so lets go!\n")
while True:
user_text = input("Type some German sentences: ")
#slice user input into sentences
sliced_text = user_text.split('. ')
word_list = ['Ich', 'Du', 'Er', 'Sie', 'Es', 'Wir', 'Ihr', 'Sie']
word_list_2 = ['Ich bin', 'Du bist', 'Er ist', 'Sie ist', 'Es ist', 'Wir sind', 'Ihr seid', 'Sie sind']
new_string = ''
for sentence in sliced_text:
sentence = sentence.replace(".", "")
first_word = sentence.split()
first_word = first_word[0]
if first_word in word_list:
new_string = sentence.split()
first_two_words = new_string[0] + ' ' + new_string[1]
if first_two_words in word_list_2:
print('\n%s: correct' % sentence)
else:
print('\n%s: wrong' % sentence)
if new_string[0] in word_list:
pos = word_list.index(new_string[0])
correct_type = word_list_2[pos]
last_word = new_string[-1]
print('Correct would be:', correct_type, last_word)
else:
print("\n%s: This is not a valid input." % sentence)
if click.confirm('\nDo you want to do another test?'):
print('\nOkay, here we go!')
else:
input('\nOkay! Hit enter to go back to the main menu')
click.clear()
break | true |
c520f9fb3717a192d13094ca09febb9168e75485 | vlcgreen/DigitalCrafts | /Python/Homework/W1D2/Day2HW_Problem1.py | 1,579 | 4.46875 | 4 | #Day 2 Homework Assignment
# PROBLEM 1. TIP CALCULATOR
# This is to get the input for the total bill
# total_bill_amount = float(input("Your total bill >> "))
# Verifying they put the correct type of data
while True:
try:
total_bill_amount = float(input("Your total bill >> "))
break
except ValueError:
print("Please only enter numbers")
print(total_bill_amount)
#Find out how service was to define service tip amount to be used
service_level = input("How was your service? \n1 - good, 2 - fair, or 3 - bad? ")
#Trying to get the correct input from user
while service_level != '1' or '2' or '3':
print("Please only input options 1, 2, or 3 for your quality of service")
service_level = input("How was your service? \n1 - good, 2 - fair, or 3 - bad? ")
if service_level == '1' or '2'or '3':
break
#Calculating based on service level answer
if service_level == '1':
tip_amount = total_bill_amount * .2
final_bill = tip_amount + total_bill_amount
print(f"Your tip amount: ${tip_amount} /nYour total amount: ${final_bill} ")
elif service_level == '2':
tip_amount = total_bill_amount * .15
final_bill = tip_amount + total_bill_amount
print(f"Your tip amount: ${tip_amount} /nYour total amount: ${final_bill} ")
elif service_level == '3':
tip_amount = total_bill_amount * .10
final_bill = tip_amount + total_bill_amount
print(f"Your tip amount: ${tip_amount} /nYour total amount: ${final_bill} ")
# else:
# print("Please only input options 1, 2, or 3 for your quality of service")
| true |
3e3ae641b35de427f618059a95ad3de48f81c903 | esnevin/test-repository | /challenge9cards.py | 515 | 4.25 | 4 | '''Write a program that will generate a random playing card e.g. ‘9 Hearts’, ‘Queen Spades’ when the return key is pressed. Rather than generate a random number from 1 to 52. Create two random numbers – one for the suit and one for the card. '''
import random
suit = ["Hearts", "Spades", "Clubs", "Diamonds"]
card = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"]
random_card = random.choice(card)
random_suit = random.choice(suit)
print("Your card is {} of {}".format(random_card, random_suit))
| true |
661dea113e7aca6078053a504bdf71c37bb7d358 | tizhad/python-tutorials | /oddevencomplex/oddevencomplex.py | 569 | 4.40625 | 4 | # Get an integer from user, n, perform the following conditional actions:
# If n is odd, print <n> Is Weird
# If n is even and in the inclusive range of 2 to 5, print <n> Is Not Weird
# If n is even and in the inclusive range 5 of to 20, print <n> Is Weird
# If n is even and greater than 20, print <n> Is Not Weird
# Instead of <n>, you should print the input number.
number = int(input())
remain = number %2
if 0 <= number <= 5 or number > 20 and remain == 0:
print(number , " Is Not Weird ")
elif 5 <= number <= 20:
print(number , "Is Weird")
| true |
6a8085d49aa18f3652a96b9055a586e0e1194035 | notionparallax/pyInRealLife | /strings.py | 965 | 4.21875 | 4 | print ("my {0} string: {1}".format("cool", "Hello there!"))
madlib = "I {verb} the {object} off the {place} ".format(verb="took", object="cheese", place="table")
print(madlib)
name = "Spongebob Squarepants"
print ("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
point1 = {'x': 0.00000100000, 'y': 39, 'name': "Pineapple"}
print ("point is at {point1!s}.".format(**locals()) )#no good!
print ("point is at {x}, {y} and is called {name}".format(**point1)) #no good!
print ("point is at {x:.4f}, {y} and is called {name}".format(**point1)) #no good!
print ("\n")
point2 = {'x': 0.00000100000, 'y': 39, 'name': "Pineapple"}
point3 = {'x': 0.00001100000, 'y': 29, 'name': "Orange"}
point4 = {'x': 0.00011100000, 'y': 19, 'name': "Pam"}
allPoints = [point1,point2,point3,point4]
for p in allPoints:
print "point is at {x:.6f}, {y:.6f} and is called {name}".format(**p)
#read about this stuff here: https://mkaz.github.io/2012/10/10/python-string-format/ | false |
785b97fe53f7a142ca53ee2a413a887103fec566 | HeardLibrary/digital-scholarship | /code/pylesson/challenge4/schools_a.py | 1,520 | 4.3125 | 4 | import csv
fileObject = open('Metro_Nashville_Schools.csv', 'r', newline='', encoding='utf-8')
fileRows = csv.reader(fileObject)
schoolData = []
for row in fileRows:
schoolData.append(row)
inputSchoolName = input("What's the name of the school? ")
found = False
for school in range(1, len(schoolData)):
if inputSchoolName.lower() in schoolData[school][3].lower(): # column 3 has the school name
found = True
# this section adds up the students in all of the grades
totalEnrollment = 0
# the grade enrollments are in columns 6 through 21
for grade in range(6, 21):
enrollment = schoolData[school][grade]
# only add the column if it isn't empty
if enrollment != '':
totalEnrollment += int(enrollment) # csv.reader reads in numbers as strings, so convert to integers
print(schoolData[school][3] + ' has a total of ' + str(totalEnrollment) + ' students.')
for category in range(22, 32):
if schoolData[school][category] != '':
# turn strings into floating point numbers
numerator = float(schoolData[school][category])
# find fraction, get the percent, and round to 1 decimal place
value = round(numerator/totalEnrollment*100, 1)
print(schoolData[0][category] + ': ' + str(value) + '%')
print() # put this here to separate multiple school results
if not found:
print("Didn't find that school")
| true |
390a6996495457bd8bd39181579aeae10df8fcdb | amingad/Codings- | /python/class/class.py | 526 | 4.1875 | 4 | # creates a class named MyClass
class MyClass:
# assign the values to the MyClass attributes
number = 0
name = "noname"
def Main():
# Creating an object of the MyClass.
# Here, 'me' is the object
me = MyClass()
# Accessing the attributes of MyClass
# using the dot(.) operator
me.number = 1337
me.name = "Harssh"
# str is an build-in function that
# creates an string
print(me.name + " " + str(me.number))
# telling python that there is main in the program.
if __name__=='__main__':
Main()
| true |
b9aa2983721b5dba4a023e01d84dd1902ce2997a | Palani717/Palani717 | /BMI Calculator.py | 222 | 4.15625 | 4 | # bmi calculator
weight = input('what is your weight (kgs)?')
height = input('What is your height (m)? ')
square_of_the_height = float(height) * float(height)
bmi = int(weight) / int(square_of_the_height)
print(bmi)
| false |
92dad61bd2021e270daa299bea88002ed6942242 | SandraV451/portfolio | /groceryList.py | 688 | 4.21875 | 4 | #groceryList = ["cake", "juice", "lunchables", "cookies", "avocado"]
#for item in groceryList:
#print(item)
groceryList = []
add = True
while add == True:
print("Do you want to add something to your grocery list?(y/n)")
answer = input()
if answer == "y":
print("What would you like to add to your list?")
item = input()
groceryList.append(item)
print("Here is your grocery list.")
for item in groceryList:
print(item)
elif answer == "n":
add == False
print("Ok then, have a great day.")
exit()
else:
print("Please choose the options given.")
| true |
5626c86cea0b545947f09ff6b3e4b000c5796572 | moyales/Python-Crash-Course | /5_if_statements/5-5_alien_colors_3.py | 827 | 4.28125 | 4 | #Exercise 5.5: Alien Colors 3
#Turn the if-else chain into an if-elif-else chain.
print("There's a green alien in front of you!")
alien_color = "green"
if alien_color == "green":
print("You just earned 5 points!")
elif alien_color == "yellow":
print("You just earned 10 points!")
else:
print("You just earned 15 points!")
print("\nThere's a yellow alien in front of you!")
alien_color_2 = "yellow"
if alien_color_2 == "green":
print("You just earned 5 points!")
elif alien_color_2 == "yellow":
print("You just earned 10 points!")
else:
print("You just earned 15 points!")
print("\nThere's a red alien in front of you!")
alien_color_3 = "red"
if alien_color_3 == "green":
print("You just earned 5 points!")
elif alien_color_3 == "yellow":
print("You just earned 10 points!")
else:
print("You just earned 15 points!")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.