blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
78c6cd735ab26eabf91d6888118f9e5ec1320ccf | denrahydnas/SL9_TreePy | /tree_calc.py | 746 | 4.28125 | 4 | # Step 1
# Ask the user for their name and the year they were born.
name = input("What is your name? ")
ages = [25, 50, 75, 100]
from datetime import date
current_year = (date.today().year)
while True:
birth_year = input("What year were you born? ")
try:
birth_year = int(birth_year)
except ValueError:
continue
else:
break
current_age = current_year - birth_year
# Step 2
# Calculate and print the year they'll turn 25, 50, 75, and 100.
for age in ages:
if age > current_age:
print("Congrats, Sandy! You will be {} in {}.".format(age, (birth_year+age)))
# Step 3
# If they're already past any of these ages, skip them.
print("You will turn {} this calendar year.".format(current_age)) | true |
528a622f441ed7ac306bc073548ebdf1e399271e | prabhus489/Python_Bestway | /Length_of_a_String.py | 509 | 4.34375 | 4 | def len_string():
length = 0
flag = 1
while flag:
flag = 0
try:
string = input("Enter the string: ")
if string.isspace()or string.isnumeric():
print("Enter a valid string")
flag = 1
except ValueError:
print("Enter a Valid input")
flag = 1
for x in string:
length += 1
return length
str_length = len_string()
print("The length of the string is: ", str_length) | true |
604a599edc09ff277520aadd1bb79fb8157272ee | pallu182/practise_python | /fibonacci_sup.py | 250 | 4.125 | 4 | #!/usr/bin/python
num = int(raw_input("Enter the number of fibonacci numbers to generate"))
if num == 1:
print 1
elif num == 2:
print 1,"\n", 1
else:
print 1
print 1
a = b = 1
for i in range(2,num):
c = a + b
a = b
b = c
print c
| true |
ca5d8a47171f6b1fbc2d53f6648da8f0a6b9e900 | km1414/Courses | /Computer-Science-50-Harward-University-edX/pset6/vigenere.py | 1,324 | 4.28125 | 4 | import sys
import cs50
def main():
# checking whether number of arguments is correct
if len(sys.argv) != 2:
print("Wrong number of arguments!")
exit(1)
# extracts integer from input
key = sys.argv[1]
if not key.isalpha():
print("Wrong key!")
exit(2)
# text input from user
text = cs50.get_string("plaintext: ")
print("ciphertext: ", end = "")
# cursor for key
cursor = 0
# iterating over all characters in string
for letter in text:
# if character is alphabetical:
if letter.isalpha():
# gets number for encryption from key
number = ord(key[cursor % len(key)].upper()) - ord('A')
cursor += 1
# if character is uppercase:
if letter.isupper():
print(chr((ord(letter) - ord('A') + number) % 26 + ord('A')), end = "")
# if character is lowercase:
else:
print(chr((ord(letter) - ord('a') + number) % 26 + ord('a')), end = "")
# if character is non-alphabetical:
else:
print(letter, end = "")
# new line
print()
# great success
exit(0)
# executes function
if __name__ == "__main__":
main()
| true |
b87e9b3fa5910c2f521321d84830411b624e0c39 | SDSS-Computing-Studies/005a-tuples-vs-lists-AlexFoxall | /task2.py | 569 | 4.15625 | 4 | #!python3
"""
Create a variable that contains an empy list.
Ask a user to enter 5 words. Add the words into the list.
Print the list
inputs:
string
string
string
string
string
outputs:
string
example:
Enter a word: apple
Enter a word: worm
Enter a word: dollar
Enter a word: shingle
Enter a word: virus
['apple', 'worm', 'dollar', 'shingle', 'virus']
"""
t1 = input("Enter a word").strip()
t2 = input("Enter a word").strip()
t3 = input("Enter a word").strip()
t4 = input("Enter a word").strip()
t5 = input("Enter a word").strip()
x = [t1, t2, t3, t4, t5]
print(x) | true |
25e432397ff5acb6a55406866813d141dc3ba2c2 | jyu001/New-Leetcode-Solution | /solved/248_strobogrammatic_number_III.py | 1,518 | 4.15625 | 4 | '''
248. Strobogrammatic Number III
DescriptionHintsSubmissionsDiscussSolution
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high.
Example:
Input: low = "50", high = "100"
Output: 3
Explanation: 69, 88, and 96 are three strobogrammatic numbers.
Note:
Because the range might be a large number, the low and high numbers are represented as string.
'''
class Solution:
def findallStro(self, n):
if n==0: return []
if n==1: return ['1','0','8']
if n==2: return ['00',"11","69","88","96"]
res = []
if n>2:
listn = self.findallStro(n-2)
for s in listn:
res.extend(['1'+s+'1', '0'+s+'0', '6'+s+'9','9'+s+'6','8'+s+'8'])
return res
def strobogrammaticInRange(self, low, high):
"""
:type low: str
:type high: str
:rtype: int
"""
n = len(high)
numl, numh = int(low), int(high)
res = []
for i in range(n+1): res.extend(self.findallStro(i))
#newres = []
count = 0
for s in res:
if len(s)!= 1 and s[0] == '0': continue
num = int(s)
#print(s, numl, numh)
if num >= numl and num <= numh:
#newres.append(s)
count += 1
#print (count, newres)
return count
| true |
f73472838e6ab97b564a1a0a179b7b2f0667a007 | Namrata-Choudhari/FUNCTION | /Q3.Sum and Average.py | 228 | 4.125 | 4 | def sum_average(a,b,c):
d=(a+b+c)
e=d/3
print("Sum of Numbers",d)
print("Average of Number",e)
a=int(input("Enter the Number"))
b=int(input("Enter the Number"))
c=int(input("Enter the Number"))
sum_average(a,b,c) | true |
b6c0dc8523111386006a29074b02d1691cf1e054 | shivigupta3/Python | /pythonsimpleprogram.py | 1,709 | 4.15625 | 4 | #!/usr/bin/python2
x=input("press 1 for addition, press 2 to print hello world, press 3 to check whether a number is prime or not, press 4 for calculator, press 5 to find factorial of a number ")
if x==1:
a=input("enter first number: ")
b=input("enter second number: ")
c=a+b
print ("sum is ",c)
if x==2:
print("Hello World")
if x==3:
num=int(input("enter a number to check whether its prime or not"))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
if x==4:
print("CALCULATOR")
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = int(input("Enter choice(1/2/3/4):"))
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print "invalid input"
if x==5:
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
| true |
9aa1b81bcb80494ea9b0c0b4a728a3981723fa43 | eecs110/winter2019 | /course-files/practice_exams/final/dictionaries/01_keys.py | 337 | 4.40625 | 4 | translations = {'uno': 'one', 'dos': 'two', 'tres': 'three'}
'''
Problem:
Given the dictionary above, write a program to print
each Spanish word (the key) to the screen. The output
should look like this:
uno
dos
tres
'''
# option 1:
for key in translations:
print(key)
# option 2:
for key in translations.keys():
print(key) | true |
0fa9fae44540b84cb863749c8307b805e3a8d817 | eecs110/winter2019 | /course-files/lectures/lecture_03/demo00_operators_data_types.py | 327 | 4.25 | 4 | # example 1:
result = 2 * '22'
print('The result is:', result)
# example 2:
result = '2' * 22
print('The result is:', result)
# example 3:
result = 2 * 22
print('The result is:', result)
# example 4:
result = max(1, 3, 4 + 8, 9, 3 * 33)
# example 5:
from operator import add, sub, mul
result = sub(100, mul(7, add(8, 4)))
| true |
b485405967c080034bd232685ee94e6b7cc84b4f | eecs110/winter2019 | /course-files/practice_exams/final/strings/11_find.py | 1,027 | 4.28125 | 4 | # write a function called sentence that takes a sentence
# and a word as positional arguments and returns a boolean
# value indicating whether or not the word is in the sentence.
# Ensure that your function is case in-sensitive. It does not
# have to match on a whole word -- just part of a word.
# Below, I show how I would call your function and what it would
# output to the screen.
def is_word_in_sentence(sentence, char_string):
if char_string.lower() in sentence.lower():
return True
return False
def is_word_in_sentence_1(sentence, char_string):
if sentence.lower().find(char_string.lower()) != -1:
return True
return False
print('\nMethod 1...')
print(is_word_in_sentence('Here is a fox', 'Fox'))
print(is_word_in_sentence('Here is a fox', 'bird'))
print(is_word_in_sentence('Here is a fox', 'Ox'))
print('\nMethod 2...')
print(is_word_in_sentence_1('Here is a fox', 'Fox'))
print(is_word_in_sentence_1('Here is a fox', 'bird'))
print(is_word_in_sentence_1('Here is a fox', 'Ox'))
| true |
40c91a64b489ecc92af2ee651c0ec3b48eba031e | amandameganchan/advent-of-code-2020 | /day15/day15code.py | 1,999 | 4.1875 | 4 | #!/bin/env python3
"""
following the rules of the game, determine
the nth number spoken by the players
rules:
-begin by taking turns reading from a list of starting
numbers (puzzle input)
-then, each turn consists of considering the most recently
spoken number:
-if that was the first time the number has been spoken,
the current player says 0
-otherwise, the number had been spoken before; the
current player announces how many turns apart the number
is from when it was previously spoken.
"""
import sys
import re
from collections import defaultdict
def solution(filename,final_turn):
# read in input data
data = []
with open(filename) as f:
for x in f:
data.append(x.strip().split(','))
return getTurn(data,int(final_turn))
def getTurn(data,final_turn):
"""
simulate playing the game to
determine the number spoken at turn
final_turn
Args:
data (list): first starting numbers
final_turn (int): desired turn to stop at
Returns:
int: number spoken aloud at that turn
"""
finalTurns = []
# do for each set in data
for starterset in data:
# get number of nums in starter set
nums = len(starterset)
# keep track of:
# current turn number
turn = 0
# last 2 turns any number was spoken on (if any)
lastTurn = {}
nextTurn = {}
lastVal = -1
# iterate until desired turn
while turn < final_turn: # part 1: 2020, part 2: 30000000
# first starting numbers
if turn < nums: currVal = int(starterset[turn])
# subsequent turns
else: currVal = nextTurn[lastVal]
if currVal in lastTurn.keys(): nextTurn[currVal] = turn-lastTurn[currVal]
else: nextTurn[currVal] = 0
lastTurn[currVal] = turn
lastVal = currVal
turn += 1
finalTurns.append(lastVal)
return finalTurns[0]
if __name__ == '__main__':
if len(sys.argv) < 3:
print("Usage: python3 day15code.py <data-file> <turn-number>")
sys.exit(1)
number = solution(sys.argv[1],sys.argv[2])
print("{} will be the {}th number spoken".format(number,sys.argv[2])) | true |
1321c47e1ea033a5668e940bc87c8916f27055e3 | Tejjy624/PythonIntro | /ftoc.py | 605 | 4.375 | 4 | #Homework 1
#Tejvir Sohi
#ECS 36A Winter 2019
#The problem in the original code is that 1st: The user input must be changed
#into int or float. Float would be the best choice since there are decimals to
#work with. The 2nd problem arised due to an extra slash when defining ctemp.
#Instead of 5//9, it should be 5/9 to show 5 divided by 9
#User enters temp in fahrenheit
ftemp = float(input("Enter degrees in Fahrenheit:"))
#Formula calculates the temp in degrees C
ctemp = (5/9)*(ftemp - 32)
#Summarizes what the temps are
print(ftemp, "degrees Fahrenheit is", ctemp, "degrees centigrade")
| true |
4b11d8d1ea2586e08828e69e9759da9cd60dda23 | petermooney/datamining | /plotExample1.py | 1,798 | 4.3125 | 4 | ### This is source code used for an invited lecture on Data Mining using Python for
### the Institute of Technology at Blanchardstown, Dublin, Ireland
### Lecturer and presenter: Dr. Peter Mooney
### email: peter.mooney@nuim.ie
### Date: November 2013
###
### The purpose of this lecture is to provide students with an easily accessible overview, with working
### examples of how Python can be used as a tool for data mining.
### For those using these notes and sample code: This code is provided as a means of showing some basic ideas around
### data extraction, data manipulation, and data visualisation with Python.
### The code provided could be written in many different ways as is the Python way. However I have tried to keep things simple and practical so that students can get an understanding of the process of data mining rather than this being a programming course in Python.
###
### If you use this code - please give me a little citation with a link back to the GitHub Repo where you found this piece of code: https://github.com/petermooney/datamining
import matplotlib.pyplot as plt
# this is a simple example of how to draw a pie chart using Python and MatplotLib
# You will need matplotlit installed for this to work.
def drawSamplePieChartPlot():
# we have 5 lecturers and we have the number of exam papers which
# each of the lecturers have had to mark.
lecturers = ['Peter','Laura','James','Jennifer','Patrick']
examPapersMarked = [14, 37, 22, 16,80]
colors = ['purple', 'blue', 'green', 'yellow','red']
plt.pie(examPapersMarked, labels=lecturers, colors=colors,autopct='%1.1f%%',startangle=90)
plt.axis('equal')
# We are going to then save the pie chart as a PNG image file (nice for the web)
plt.savefig("PieChartExample.png")
def main():
drawSamplePieChartPlot()
main()
| true |
6187d788dd3f6fc9b049ded6d08189e6bb8923ed | lflores0214/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,583 | 4.34375 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
# loop through n-1 elements
print(arr)
for i in range(0, len(arr) - 1):
# print(f"I: {i}")
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for j in range(cur_index, len(arr)):
# check if the array at j is less than the current smallest index
# print(f"J: {j}")
# print(arr)
if arr[j] < arr[smallest_index]:
# if it is j becomes the smallest index
smallest_index = j
# TO-DO: swap
arr[cur_index], arr[smallest_index] = arr[smallest_index], arr[cur_index]
# print(arr)
return arr
my_arr = [1, 5, 8, 4, 2, 9, 6, 0, 7, 3]
# print(selection_sort(my_arr))
# TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
# loop through array
# print(arr)
for i in range(len(arr)-1):
# check if the element at current index is greater than the element to the right
# print(arr)
for j in range(len(arr)-1):
if arr[j] > arr[j+1]:
# if it is than swap the two elements
arr[j], arr[j+1] = arr[j+1], arr[j]
# run loop again until they are all sorted
print(arr)
# bubble_sort(arr)
return arr
print(bubble_sort(my_arr))
# print(f"bubble: {bubble_sort(my_arr)}")
# STRETCH: implement the Count Sort function below
def count_sort(arr, maximum=-1):
return arr
| true |
34517c82223ec7e295f5139488687615eef77d56 | devineni-nani/Nani_python_lerning | /Takung input/input.py | 1,162 | 4.375 | 4 | '''This function first takes the input from the user and then evaluates the expression,
which means Python automatically identifies whether user entered a string or a number or list.
If the input provided is not correct then either syntax error or exception is raised by python.'''
#input() use
roll_num= input("enter your roll number:")
print (roll_num)
'''
How the input function works in Python :
When input() function executes program flow will be stopped until the user has given an input.
The text or message display on the output screen to ask a user to enter input value is optional i.e.
the prompt, will be printed on the screen is optional.
Whatever you enter as input, input function convert it into a string.
if you enter an integer value still input() function convert it into a string. You need to explicitly convert it into an integer in your code using typecasting.
for example:
'''
num=input("enter an number:")
print (num)
name = input ("enter your name:")
print (name)
#Printing type of input value
print ("type of num", type(num))
print ("type of name:", type(name))
num1=type(num)
print ("after typecasting num type:", type(num1))
| true |
75b4292c4e85d8edd136e7bf469c60e9222e383f | Dragonriser/DSA_Practice | /Binary Search/OrderAgnostic.py | 847 | 4.125 | 4 | """
Given a sorted array of numbers, find if a given number ‘key’ is present in the array. Though we know that the array is sorted, we don’t know if it’s sorted in ascending or descending order. You should assume that the array can have duplicates.
Write a function to return the index of the ‘key’ if it is present in the array, otherwise return -1.
Example 1:
Input: [4, 6, 10], key = 10
Output: 2
"""
#CODE:
def orderAgnostic(arr, target):
length = len(arr)
ascending = False
if arr[0] < arr[length - 1]:
ascending = True
lo, hi = 0, length - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if arr[mid] == target:
return mid
else:
if ascending:
if arr[mid] < target:
lo = mid + 1
else:
hi = mid - 1
else:
if arr[mid] < target:
hi = mid - 1
else:
lo = mid + 1
return -1
| true |
d6b9c248126e6027e39f3f61d17d8a1a73f687b0 | Dragonriser/DSA_Practice | /LinkedLists/MergeSortedLists.py | 877 | 4.1875 | 4 | #QUESTION:
#Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
#APPROACH:
#Naive: Merge the linked Lists and sort them.
#Optimised: Traverse through lists and add elements to new list according to value, since both lists are in increasing order. Time & Space complexity: O(n + m)
#CODE:
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 and not l2:
return None
merged = cur = ListNode()
while l1 and l2:
if l1.val <= l2.val:
cur.next = l1
l1 = l1.next
elif l2.val <= l2.val:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return merged.next
| true |
f0438d1379df6974702dc34ef108073385a3877e | Nightzxfx/Pyton | /function.py | 1,069 | 4.1875 | 4 | def square(n):
"""Returns the square of a number."""
squared = n ** 2
print "%d squared is %d." % (n, squared) <--%d because is comming from def (function)
return squared
# Call the square function on line 10! Make sure to
# include the number 10 between the parentheses.
square(10)
--------------------------
def power(base, exponent): # Add your parameters here!
result = base ** exponent
print "%d to the power of %d is %d." % (base, exponent, result)
power(37, 4) # Add your arguments here!
-------------------------------
def one_good_turn(n):
return n + 1
def deserves_another(m):
return one_good_turn(m) + 2 <0 use the result of the frist funciton to apply in the second
---------------------------
def cube(number):
return number * number * number
def by_three(number):
if number % 3 == 0: <-- if the number is devided by 3
return cube(number)
else:
return False
-----------------
def distance_from_zero(p):
if type(p) == int or type(p) == float:
return abs(p)
else:
return "Nope"
| true |
c7eed0a9bee1a87a3164f81700d282d1370cebdb | philuu12/PYTHON_4_NTWK_ENGRS | /wk1_hw/Solution_wk1/ex7_yaml_json_read.py | 835 | 4.3125 | 4 | #!/usr/bin/env python
'''
Write a Python program that reads both the YAML file and the JSON file created
in exercise6 and pretty prints the data structure that is returned.
'''
import yaml
import json
from pprint import pprint
def output_format(my_list, my_str):
'''
Make the output format easier to read
'''
print '\n\n'
print '#' * 3
print '#' * 3 + my_str
print '#' * 3
pprint(my_list)
def main():
'''
Read YAML and JSON files. Pretty print to standard out
'''
yaml_file = 'my_test.yml'
json_file = 'my_test.json'
with open(yaml_file) as f:
yaml_list = yaml.load(f)
with open(json_file) as f:
json_list = json.load(f)
output_format(yaml_list, ' YAML')
output_format(json_list, ' JSON')
print '\n'
if __name__ == "__main__":
main()
| true |
96d7d761a9593d39c6d389de8c1dc506d61ef9b4 | AASHMAN111/Addition-using-python | /Development/to_run_module.py | 1,800 | 4.125 | 4 | #This module takes two input from the user. The input can be numbers between 0 and 255.
#This module keeps on executing until the user wishes.
#This module can also be called as a main module.
#addition_module.py is imported in this module for the addition
#conversion_module.py is imported in this module for the conversion
#user_input_moduoe.py is imported in this module for taking the inputs from them and to handle exceptions.
#Aashman Uprety, 26th May, 2020
import addition_module
import conversion_module
import user_input_module
def list_to_string(lst):
"""Function to convert the list 'lst' to string."""
string = ""
for i in lst:
i = str(i)
string = string + i
return string
check = "yes"
while check != "no":
if check == "yes":
lst = user_input_module.user_input_module()
fbinary = conversion_module.decimal_to_binary(lst[0])
sbinary = conversion_module.decimal_to_binary(lst[1])
bit_addition = addition_module.bit_addition(fbinary, sbinary)
bitwise_add = addition_module.bitwise_addition(lst[0],lst[1])
print("First inputted number in binary is: ", list_to_string(fbinary))
print("Second inputted number in binary is: ", list_to_string(sbinary))
print("Sum of the two inputted numbers in binary is: ", list_to_string(bit_addition))
print("Sum of the two inputted numbers in decimal is: ",bitwise_add)
else:
print("please only enter yes or no.")
check = input("Are you willing for another addition? If yes just type yes than you can else just type no, the program will terminate : ")
check = check.lower()
if check == "no":
print("The program is terminating. BYYEEEEEEEE.")
| true |
868ad4369cd64f877f4ea35f1a85c941aa9c7409 | SaketJNU/software_engineering | /rcdu_2750_practicals/rcdu_2750_strings.py | 2,923 | 4.40625 | 4 | """
Strings are amongst the most popular types in Python.
We can create them simply by enclosing characters in quotes.
Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable.
"""
import string
name = "shubham"
print("Data in upper case : ",name.upper()) # upper() for UPPER case strings conversion
lower = "PRAJAPATI"
print("Data in lower case : ",lower.lower()) # lower() for lower case strings conversion
takeData = input("Please enter any data : ")
print("Here is the user input data : ",takeData) # input() for taking data from user
# NOTE -> input() takes data in string if you want to do some functionality with numeric please
# convert that data in your dataType like : int float etc.
# Let's take a look of some in-built string functions
print(string.ascii_uppercase) # ascii_uppercase gives A-Z
print(string.digits) # it gives 0-9
# string formatter
"""
% c -> character
% s -> string
% i ,d-> signed integer deciaml integer
% u -> unsigned decimal integer
% x -> hex decimal integer (lowercase)
% X -> hex decimal integer (UPPERCASE)
% o -> octal decimal integers
% e -> exponantial notation (lowercase, e^3)
% E -> exponantial notation (10^3)
% f -> floating point numbers
"""
print("hexa decimal : ",string.hexdigits) # string.hexdigits gives hexadecimal number
print("only printable no : ",string.printable ) # printable characters only
print("Octa decimal no : ",string.octdigits) # Octa decimal no's
print(type(name.isalnum()),name.isalnum()) # checks alphanumeric
print(type(name.isnumeric()),name.isnumeric()) # checks numeric
print(type(name.isdigit()),name.isdigit()) # checks digit
print("Split func : ",name.split()) # Splits stings
print("Starts With ",name.startswith('s')) # Checks starting char of string return boolean
number = " my number is 97748826478"
print(number.split()) # Basically returns list
print(number.strip()) # removes unprintable charaters from both side left and right
print(number.rstrip()) # removes unprintable charaters right side only
splitn= number.split()
for onew in splitn:
if (onew.strip()).isdigit():
if len(onew.strip())== 11:
print("No", onew.strip())
str1 = "abcdxyzabc"
print(str1.replace('a','k')) # occurance of 'a' by 'k'
str2 = str1.replace('a','k')
print(str2.replace('acd','shu'))
print(str1.capitalize()) # Capitalize capital only first char of an string
# Method 1st
newName = "shubham kumar prajapati"
splitName = newName.split()
print(splitName)
print(splitName[0][0].upper() + ". "+ splitName[1][0].upper() + ". "+ splitName[2].capitalize())
wordlen = len(splitName)
print("Length of list : ",wordlen)
# Method 2nd
count = 0
newname = ""
for aw in splitName:
count +=1
if count < wordlen:
newname += aw[0].upper()+ ". "
else :
newname += aw[0].upper()+aw[1:]
print("By method 2nd : ",newname) | true |
7bbe18daf81dabb7aa2ddb7f20bca261734a17d8 | dodooh/python | /Sine_Cosine_Plot.py | 858 | 4.3125 | 4 | # Generating a sine vs cosine curve
# For this project, you will have a generate a sine vs cosine curve.
# You will need to use the numpy library to access the sine and cosine functions.
# You will also need to use the matplotlib library to draw the curve.
# To make this more difficult, make the graph go from -360° to 360°,
# with there being a 180° difference between each point on the x-axis
import numpy as np
import matplotlib.pylab as plt
plt.show()
# values from -4pi to 4pi
x=np.arange(-4*np.pi,4*np.pi,0.05)
y_sin=np.sin(x)
y_cos=np.cos(x)
#Drawing sin and cos functions
plt.plot(x,y_sin,color='red',linewidth=1.5, label="Sin(x)")
plt.plot(x,y_cos,color='blue', label="Cos(x)")
plt.title("Sin vs Cos graph")
plt.xlabel('Angles in radian')
plt.ylabel('sin(x) and cos(x)')
plt.legend(['sin(x)','cos(x)'])
plt.show() | true |
68d606253d377862c11b0eaf52f942f6b6155f56 | DimaSapsay/py_shift | /shift.py | 349 | 4.15625 | 4 | """"
function to perform a circular shift of a list to the left by a given number of elements
"""
from typing import List
def shift(final_list: List[int], num: int) -> List[int]:
"""perform a circular shift"""
if len(final_list) < num:
raise ValueError
final_list = final_list[num:] + final_list[:num]
return final_list
| true |
630d6de3258bef33cfb9b4a79a276d002d56c39c | VictoryWekwa/program-gig | /Victory/PythonTask1.py | 205 | 4.53125 | 5 | # A PROGRAM TO COMPUTE THE AREA OF A CIRCLE
##
#
import math
radius=float(input("Enter the Radius of the Circle= "))
area_of_circle=math.pi*(radius**2)
print("The Area of the circle is", area_of_circle)
| true |
5503ffdae3e28c9bc81f7b536fc986bf46913d34 | jocogum10/learning_data_structures_and_algorithms | /doubly_linkedlist.py | 1,940 | 4.21875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next_node = None
self.previous_node = None
class DoublyLinkedList:
def __init__(self, first_node=None, last_node=None):
self.first_node = first_node
self.last_node = last_node
def insert_at_end(self, value):
new_node = Node(value)
if not self.first_node: # if there are no elements yet in the linked list
self.first_node = new_node
self.last_node = new_node
else:
new_node.previous_node = self.last_node # else, set the new node's previous node as the last node
self.last_node.next_node = new_node # set the last node's next node to the new node
self.last_node = new_node # set the last node as the new node
def remove_from_front(self):
removed_node = self.first_node # set the node to be removed
self.first_node = self.first_node.next_node # set the first node to be the next node
return removed_node # return the removed node
class Queue:
def __init__(self):
self.queue = DoublyLinkedList()
def enque(self, value):
self.queue.insert_at_end(value)
def deque(self):
removed_node = self.queue.remove_from_front
return removed_node
def tail(self):
return self.queue.last_node.data
if __name__ == '__main__':
node_1 = Node("once")
node_2 = Node("upon")
node_1.next_node = node_2
node_3 = Node("a")
node_2.next_node = node_3
node_4 = Node("time")
node_3.next_node = node_4
dlist = DoublyLinkedList(node_1)
print(dlist.remove_from_front().data)
q = Queue()
q.enque(dlist)
b = q.tail()
print(b.first_node.data) | true |
f9b9480cc340d3b79f06e49aa31a53dbea5379f5 | abilash2574/FindingPhoneNumber | /regexes.py | 377 | 4.1875 | 4 | #! python3
# Creating the same program using re package
import re
indian_pattern = re.compile(r'\d\d\d\d\d \d\d\d\d\d')
text = "This is my number 76833 12142."
search = indian_pattern.search(text)
val = lambda x: None if(search==None) else search.group()
if val(search) != None:
print ("The phone number is "+val(search))
else:
print("The phone number is not found")
| true |
be8b2ea14326e64425af9ee13478ec8c97890804 | beajmnz/IEDSbootcamp | /pre-work/pre-work-python.py | 1,135 | 4.3125 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 23 17:39:23 2021
@author: Bea Jimenez <bea.jimenez@alumni.ie.edu>
"""
#Complete the following exercises using Spyder or Google Collab (your choice):
#1. Print your name
print('Bea Jimenez')
#2. Print your name, your nationality and your job in 3 different lines with one single
#print command
print('Bea Jimenez\nSpanish\nCurrently unemployed, but I\'m a COO wannabe :)')
#3. Create an integer variable taking the value 4
intFour = 4
#4. Create other integer variable taking the value 1
intOne = 1
#5. Transform both variables into boolean variables. What happens?
intFour = bool(intFour)
intOne = bool(intOne)
# -> both variables are transformed into booleans and get True value
#6. Transform this variable "23" into numerical variable.
str23 = '23'
int23 = int(str23)
#7. Ask the user their age in the format 1st Jan, 2019 (check the command input for
#this). Using this info, show on the screen their year of birth
birthdate = input(prompt='Please state your birthdate in the format 1st Jan, 2019')
print('From what you just told me, you were born in the year '+birthdate[-4:])
| true |
28e93fcc30fca3c0adec041efd4fbeb6a467724e | beajmnz/IEDSbootcamp | /theory/03-Data Structures/DS6.py | 452 | 4.34375 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 5 18:24:27 2021
@author: Bea Jimenez <bea.jimenez@alumni.ie.edu>
"""
"""
Write a Python program to count the elements in a list until an element
is a tuple.
Input: [10,20,30,(10,20),40]
Output: 3
"""
Input = [10,20,30,(10,20),40]
counter = 0
for i in Input:
if type(i) != tuple:
counter+=1
else:
break
print("There were",counter,"elements before the first tuple")
| true |
e29dcf2e71f5f207a18e22067c0b26b530399225 | beajmnz/IEDSbootcamp | /theory/02b-Flow Control Elements/FLOW3.py | 468 | 4.125 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 5 13:03:37 2021
@author: Bea Jimenez <bea.jimenez@alumni.ie.edu>
"""
"""
Write a Python program that asks for a name to the user. If that name is your
name, give congratulations. If not, let him know that is not your name
Mark: be careful because the given text can have uppercase or lowercase
letters
"""
name = input('Guess my name').strip().lower()
if name == 'bea':
print('congrats!')
else:
print('too bad') | true |
37b2d8a716c5e5a130cf1761e92a65ea3a517ab7 | JovieMs/dp | /behavioral/strategy.py | 1,003 | 4.28125 | 4 | #!/usr/bin/env python
# http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern
# -written-in-python-the-sample-in-wikipedia
"""
In most of other languages Strategy pattern is implemented via creating some
base strategy interface/abstract class and subclassing it with a number of
concrete strategies (as we can see at
http://en.wikipedia.org/wiki/Strategy_pattern), however Python supports
higher-order functions and allows us to have only one class and inject
functions into it's instances, as shown in this example.
"""
import types
class SortedList:
def set_strategy(self, func=None):
if func is not None:
self.sort = types.MethodType(func, self)
def sort(self):
print(self.name)
def bubble_sort(self):
print('bubble sorting')
def merge_sort(self):
print('merge sorting')
if __name__ == '__main__':
strat = SortedList()
strat.set_strategy(bubble_sort)
strat.sort()
strat.set_strategy(merge_sort)
strat.sort() | true |
ac896f90c9213c8bee169ffd3fbc74a6b4dc15e3 | ICS3U-Programming-JonathanK/Unit4-01-Python | /sum_of_numbers.py | 1,257 | 4.40625 | 4 | #!/usr/bin/env python3
# Created by: Mr. Coxall
# Created on: Sept 2019
# Modified by: Jonathan
# Modified on: May 20, 2021
# This program asks the user to enter a positive number
# and then uses a loop to calculate and display the sum
# of all numbers from 0 until that number.
def main():
# initialize the loop counter and sum
loop_counter = 0
sum = 0
# get the user number as a string
user_number_string = input("Enter a positive number: ")
print("")
try:
user_number_int = int(user_number_string)
print("")
except ValueError:
print("Please enter a valid number")
else:
# calculate the sum of all numbers from 0 to user number
while (loop_counter <= user_number_int):
sum = sum + loop_counter
print("Tracking {0} times through loop.".format(loop_counter))
loop_counter = loop_counter + 1
print("The sum of the numbers from"
"0 to {} is: {}.".format(user_number_int, sum))
print("")
if (user_number_int < 0):
print("{0} is not a valid number".format(user_number_int))
finally:
print("")
print("Thank you for your input")
if __name__ == "__main__":
main()
| true |
e811211d279510195df3bbdf28645579c8b9f6de | megler/Day8-Caesar-Cipher | /main.py | 1,497 | 4.1875 | 4 | # caesarCipher.py
#
# Python Bootcamp Day 8 - Caesar Cipher
# Usage:
# Encrypt and decrypt code with caesar cipher. Day 8 Python Bootcamp
#
# Marceia Egler Sept 30, 2021
from art import logo
from replit import clear
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
game = True
def caesar(cipher:str, shift_amt:int, direction:str) -> str:
code = ''
if direction == 'decode':
shift_amt *= -1
for i,value in enumerate(cipher):
if value in alphabet:
#find the index of the input in the alphabet
answer = alphabet.index(value)
answer += shift_amt
#if shift_amt pushes past end of alphabet, restart
#eg z(26) + shift(5) == 30 = (26 * 1) + 4
alpha_loop = alphabet[answer%len(alphabet)]
code += alpha_loop
else:
code += value
print(f"The {direction}d text is {code}")
print(logo)
#Allow game to continue until user says no
while game:
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
caesar(cipher=text, shift_amt=shift, direction=direction)
play = input("Do you want to play again?\n").lower()
if play == 'no':
print(f"Thanks for playing")
game = False
| true |
03839c78723e70f763d8009fea4217f18c3eff42 | agustinaguero97/curso_python_udemy_omar | /ex4.py | 1,624 | 4.15625 | 4 | """"Your teacher asked from you to write a program that allows her to enter student 4 exam result and then the program
calculates the average and displays whether student passed the semester or no.in order to pass the semester, the average
score must be 50 or more"""
def amount_of_results():
while True:
try:
count = int(input("type the amount of result to calculate the average: "))
if count <= 0:
raise Exception
return count
except:
print("input error, must be a number greater that 0 and a integer")
def result_input(count):
result_list = []
while True:
try:
note = int(input(f"type the {count}° note (o to 100): "))
if 0<= note and note <= 100:
result_list.append(note)
count -= 1
if count == 0:
break
else:
raise Exception
except:
print("invalid number, must go from 0 to 100")
return result_list
def prom(result):
sum = 0
for notes in result:
sum = sum + notes
promedio = int(sum/(len(result)))
print(f"the average of the results is: {promedio}")
return promedio
def pass_failed(average,score):
if average < score:
print("the student does not pass ")
if average >= score:
print("the student does pass")
if __name__ == '__main__':
count = amount_of_results()
result = result_input(count)
average = prom(result)
pass_failed(average,score=50) #here can modify the minimun average score of approval
| true |
7be5665d75207fd063846d31adfc0012aaeee891 | vlad-bezden/data_structures_and_algorithms | /data_structures_and_algorithms/quick_sort.py | 512 | 4.21875 | 4 | """Example of quick sort using recursion"""
import random
from typing import List
def quick_sort(data: List[int]) -> List[int]:
if len(data) < 2:
return data
pivot, left, right = data.pop(), [], []
for item in data:
if item < pivot:
left.append(item)
else:
right.append(item)
return quick_sort(left) + [pivot] + quick_sort(right)
if __name__ == "__main__":
data = random.sample(range(1000), 15)
print(data)
print(quick_sort(data))
| true |
4059405985761b3ae72fff1d6d06169cc35b1823 | lakshay-saini-au8/PY_playground | /random/day03.py | 678 | 4.46875 | 4 | #question
'''
1.Create a variable “string” which contains any string value of length > 15
2. Print the length of the string variable.
3. Print the type of variable “string”
4. Convert the variable “string” to lowercase and print it.
5. Convert the variable “string” to uppercase and print it.
6. Use colon(:) operator to print the index of string from -10 to the end(slicing).
7. Print the whole string using a colon(:) operator(slicing).
'''
string = "Hye, My Name is lakshay saini. we can connect https://www.linkedin.com/in/lakshay-saini-dev/"
print(len(string))
print(type(string))
print(string.lower())
print(string.upper())
print(string[-10:])
print(string[:]) | true |
6a29cb24698e9390ac9077d431d6f9001386ed84 | lakshay-saini-au8/PY_playground | /random/day26.py | 1,164 | 4.28125 | 4 |
# Write a program to find a triplet that sums to a given value with improved time complexity.
'''
Input: array = {12, 3, 4, 1, 6, 9}, sum = 24;
Output: 12, 3, 9
Explanation: There is a triplet (12, 3 and 9) present
in the array whose sum is 24.
'''
# brute force apporach
def triplet(arr, sums):
n = len(arr)
if n < 3:
return "Array length is sort"
for i in range(n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
if arr[i]+arr[j]+arr[k] == sums:
print(arr[i], arr[j], arr[k])
# triplet([12,3,4,1,6,9],24)
# triplet([1,2,3,4,5],9)
# Write a program to find a triplet such that the sum of two equals to the third element with improved time complexity
def triplet_sum(arr):
n = len(arr)
if n < 3:
return "Array length is sort"
for i in range(n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
if arr[i]+arr[j] == arr[k] or arr[j]+arr[k] == arr[i] or arr[k]+arr[i] == arr[j]:
print(arr[i], arr[j], arr[k])
triplet_sum([5, 32, 1, 7, 10, 50, 19, 21, 2])
# triplet_sum([5,32,1,7,10,50,19,21,0])
| true |
fce872e76b3da0255f503a85d718dc36fd739dd6 | Niraj-Suryavanshi/Python-Basic-Program | /7.chapter/12_pr_03.py | 224 | 4.125 | 4 | num=int(input("Enter a number: "))
prime=True
for i in range(2,num):
if(num%i==0):
prime=False
break
if prime:
print("Number is prime")
else:
print("Number is not prime")
| true |
69f491abbf9b757d6dc5b7fe6d5e7cd925785389 | flerdacodeu/CodeU-2018-Group8 | /cliodhnaharrison/assignment1/question1.py | 896 | 4.25 | 4 | #Using Python 3
import string
#Input through command line
string_one = input()
string_two = input()
def anagram_finder(string_one, string_two, case_sensitive=False):
anagram = True
if len(string_one) != len(string_two):
return False
#Gets a list of ascii characters
alphabet = list(string.printable)
if not case_sensitive:
#Case Insensitive so making sure only lowercase letters in strings
string_one = string_one.lower()
string_two = string_two.lower()
for char in alphabet:
if anagram:
#Counts occurences of a character in both strings
#If there is a difference it returns False
if string_one.count(char) != string_two.count(char):
anagram = False
else:
return anagram
return anagram
#My Testing
#print (anagram_finder(string_one, string_two))
| true |
c425fd70a75756fa84add2f21f7593b8e91b1203 | flerdacodeu/CodeU-2018-Group8 | /aliiae/assignment3/trie.py | 2,519 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Optional follow-up:
Implement a dictionary class that can be constructed from a list of words.
A dictionary class with these two methods:
* isWord(string): Returns whether the given string is a valid word.
* isPrefix(string): Returns whether the given string is a prefix of at least one
word in the dictionary.
Assumptions:
The dictionary is a trie implemented as node objects with children stored in
a hashmap.
"""
from collections import defaultdict
class Trie:
def __init__(self, words=None):
"""
Implement a trie node that has trie children and bool if it ends a word.
Args:
words: A list of words that can be inserted into the trie.
"""
self.children = defaultdict(Trie)
self._is_word_end = False
if words:
self.insert_words(words)
def __str__(self):
return ' '.join(self.children)
def insert_words(self, words):
"""
Insert a list of words into the trie.
Args:
words: A list of words to be inserted into the trie.
Returns: None
"""
for word in words:
self.insert_word(word)
def insert_word(self, word):
"""
Insert a word into the trie.
Args:
word: A word to be inserted into the trie.
Returns: None
"""
current = self
for letter in word:
current = current.children[letter]
current._is_word_end = True
def is_word(self, word):
"""
Return whether the given string is a valid word.
Args:
word: The word to look for.
Returns: True if the word is found, else False.
"""
current = self
for letter in word:
if letter in current.children:
current = current.children[letter]
else:
return False
else:
return current._is_word_end
def is_prefix(self, prefix):
"""
Return whether the given string is a prefix of at least one word.
Args:
prefix: Prefix to search for in the trie.
Returns: True if the string is a prefix of a word, else False.
"""
current = self
for letter in prefix:
if letter in current.children:
current = current.children[letter]
else:
return False
else:
return True
| true |
6ddf930b444a33d37a4cc79308577c45cf45af96 | Saraabd7/Python-Eng-54 | /For_loops_107.py | 1,117 | 4.21875 | 4 | # For loops
# Syntax
# for item in iterable: mean something you can go over for e.g: list
# block of code:
import time
cool_cars = ['Skoda felicia fun', 'Fiat abarth the old one', 'toyota corola, Fiat panda 4x4', 'Fiat Multipla']
for car in cool_cars:
print(car)
for lunch_time in cool_cars:
print(car)
time.sleep(1)
print('1 -', cool_cars[0])
Count = 0 # first number being used ( to do the count for points.
for car in cool_cars:
print(Count + 1, '-', car)
Count += 1
# For Loop for dictionaries:
boris_dict = {
'name': 'boris',
'l_name': 'Johnson',
'phone': '0784171157',
'address': '10 downing street'}
for item in boris_dict:
print(item)
# this item is the key so we change it to key:
for key in boris_dict:
print(key)
# I want each individual values
# for this i need, dictionary + key
print(boris_dict[key])
print(boris_dict['phone'])
# for key in boris_dict:
# print(boris_dict['phone'])
# print(boris_dict['name'])
for value in boris_dict.values():
print(value)
print('Name:', 'Boris Johnson')
print('phone:', '0784171157') | true |
933c9d74c3dee9ac64fefe649af9aba3dcffce02 | dmonzonis/advent-of-code-2017 | /day24/day24.py | 2,809 | 4.34375 | 4 | class Bridge:
"""Represents a bridge of magnetic pieces.
Holds information about available pieces to construct the bridge, current pieces used
in the bridge and the available port of the last piece in the bridge."""
def __init__(self, available, bridge=[], port=0):
"""Initialize bridge variables."""
self.available = available
self.bridge = bridge
self.port = port
def strength(self):
"""Return the strength of the current bridge."""
return sum([sum([port for port in piece]) for piece in self.bridge])
def fitting_pieces(self):
"""Return a list of pieces that can be used to extend the current bridge."""
return [piece for piece in self.available if self.port in piece]
def add_piece(self, piece):
"""Return a new bridge with the piece added to it and removed from the available list."""
new_bridge = self.bridge + [piece]
# The new port is the unmatched port in the added piece
new_port = piece[0] if piece[1] == self.port else piece[1]
new_available = self.available[:]
new_available.remove(piece)
return Bridge(new_available, new_bridge, new_port)
def find_strongest(pieces):
"""Find strongest bridge constructable with a given list of pieces."""
max_strength = 0
queue = [Bridge(pieces)]
while queue:
bridge = queue.pop(0)
fitting = bridge.fitting_pieces()
if not fitting:
strength = bridge.strength()
if strength > max_strength:
max_strength = strength
continue
for piece in fitting:
queue.append(bridge.add_piece(piece))
return max_strength
def find_strongest_longest(pieces):
"""Find strongest bridge from the longest bridges constructable with a list of pieces."""
max_strength = max_length = 0
queue = [Bridge(pieces)]
while queue:
bridge = queue.pop(0)
fitting = bridge.fitting_pieces()
if not fitting:
length = len(bridge.bridge)
if length > max_length:
max_length = length
max_strength = bridge.strength()
elif length == max_length:
strength = bridge.strength()
if strength > max_strength:
max_strength = strength
max_length = length
continue
for piece in fitting:
queue.append(bridge.add_piece(piece))
return max_strength
def main():
with open("input") as f:
pieces = [[int(x), int(y)] for x, y in [p.split('/') for p in f.read().splitlines()]]
# print("Part 1:", find_strongest(pieces))
print("Part 2:", find_strongest_longest(pieces))
if __name__ == "__main__":
main()
| true |
a68e2b0be94ba93bb4e9d123c55af80297ddc5d6 | dmonzonis/advent-of-code-2017 | /day19/day19.py | 1,866 | 4.34375 | 4 | def step(pos, direction):
"""Take a step in a given direction and return the new position."""
return [sum(x) for x in zip(pos, direction)]
def turn_left(direction):
"""Return a new direction resulting from turning 90 degrees left."""
return (direction[1], -direction[0])
def turn_right(direction):
"""Return a new direction resulting from turning 90 degrees right."""
return (-direction[1], direction[0])
def get_tile(roadmap, pos):
"""With a position in the form (x, y), return the tile in the roadmap corresponding to it."""
x, y = pos
return roadmap[y][x]
def follow_roadmap(roadmap):
"""Follow the roadmap and return the list of characters encountered and steps taken."""
direction = (0, 1) # Start going down
valid_tiles = ['-', '|', '+'] # Valid road tiles
collected = []
steps = 1
pos = (roadmap[0].index('|'), 0) # Initial position in the form (x, y)
while True:
new_pos = step(pos, direction)
tile = get_tile(roadmap, new_pos)
if tile == ' ':
# Look for a new direction left or right
if get_tile(roadmap, step(pos, turn_left(direction))) != ' ':
direction = turn_left(direction)
continue
elif get_tile(roadmap, step(pos, turn_right(direction))) != ' ':
direction = turn_right(direction)
continue
else:
# We got to the end of the road
return collected, steps
elif tile not in valid_tiles:
collected.append(tile)
pos = new_pos
steps += 1
def main():
with open("input") as f:
roadmap = f.read().split('\n')
collected, steps = follow_roadmap(roadmap)
print("Part 1:", ''.join(collected))
print("Part 2:", steps)
if __name__ == "__main__":
main()
| true |
e140bd8915d97b4402d63d2572c056e61a0d9e5a | presstwice/Python- | /data_camp/simple_pendulum.py | 487 | 4.1875 | 4 | # Initialize offset
offset = -6
# Code the while loop
while offset != 0 :b # The goal is to get offset to always equal 0
print("correcting...") # Prints correcting to clearly state the loop point
if offset > 0: # You start the if statement by checking if the offset is positive
offset = offset - 1 # If so bring the offset closer to 0 by -1
else:
offset = offset + 1 # if its not positive then it must be negative bring it closer to 0 + 1
print(offset) | true |
d22f5a9a6851525504cc7e4f1952a2bbb8ab27ae | BalaRajendran/guvi | /large.py | 336 | 4.21875 | 4 | print ("Find the largest number amoung three numbers");
num=list()
arry=int(3);
a=1;
for i in range(int(arry)):
print ('Num :',a);
a+=1;
n=input();
num.append(int(n))
if (num[0]>num[1] and num[0]>num[2]):
print (num[0]);
elif (num[1]>num[0] and num[1]>num[2]):
print (num[1]);
else:
print(num[2]);
| true |
5e0c461e5b4d1f9e6c328dcc78d88b5c8a08d410 | UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019 | /students/AndrewMiotke/lesson04/class_work/generators.py | 466 | 4.21875 | 4 | """
Generators are iterators that returns a value
"""
def y_range(start, stop, step=1):
""" Create a generator using yield """
i = start
while i < stop:
"""
yield, like next(), allows you to increment your flow control
e.g. inside a loop
"""
yield i
i += step
it = y_range(12, 25)
next(it) # this returns 12
next(it) # this returns 13
# Generators in a list comprehension
[y for y in y_range(12, 25)]
| true |
603e12a667b8908776efbfef8d015c5e12b390c8 | Super1ZC/PyTricks | /PyTricks/use_dicts_to_emulate_switch_statements.py | 761 | 4.375 | 4 | def dispatch_if(operator,x,y):
"""This is similar to calculator"""
if operator == 'add':
return x+y
elif operator == 'sub':
return x-y
elif operator == 'mul':
return x*y
elif operator == 'div':
return x/y
else:
return None
def dispatch_dict(operator,x,y):
"""Using anonymous function lambda to display."""
return{
'add':lambda: x+y,
'sub':lambda: x-y,
'mul':lambda: x*y,
#dict.get function,return None when the operator
#is not key in dict
'div':lambda: x/y,}.get(operator,lambda:None)()
print(dispatch_if('mul',2,8))
print(dispatch_dict('mul',2,8))
print(dispatch_if('unknown',2,8))
print(dispatch_dict('unknown',2,8))
| true |
1af51d9ed56217484ab6060fc2f36ee38e9523df | rgvsiva/Tasks_MajorCompanies | /long_palindrome.py | 560 | 4.21875 | 4 | #This was asked by AMAZON.
#Given a string, find the longest palindromic contiguous substring.
#if there are more than one, prompt the first one.
#EX: for 'aabcdcb'-->'bcdcb'
main_St=input("Enter the main string: ")
st=main_St
palindrome=[st[0]]
while len(st)>1:
sub=''
for ch in st:
sub+=ch
if (sub==sub[::-1]) and (sub not in palindrome) and (len(sub)>len(palindrome[-1])):
palindrome=[sub]
st=st[1:]
print ('Longest palindromic substring: "',palindrome[0],'" at index-',main_St.index(palindrome[0]))
| true |
b6aca7b55b08724d2a922f3788cc2b15c4465f8e | webclinic017/davidgoliath | /Project/modelling/17_skewness.py | 1,280 | 4.125 | 4 | # skewness python
# https://www.google.com/search?q=skewness+python&oq=Skewness+python&aqs=chrome.0.0l4j0i22i30l6.3988j0j4&sourceid=chrome&ie=UTF-8
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skew.html
# https://www.geeksforgeeks.org/scipy-stats-skew-python/
''' Statistical functions
In simple words, skewness is the measure of how much the
probability distribution of a random variable deviates
from the normal distribution.
# https://www.investopedia.com/terms/s/skewness.asp
skewness = 0 : normally distributed.
skewness > 0 : more weight in the left tail of the distribution.
skewness < 0 : more weight in the right tail of the distribution.
'''
# part 1 ----------------------------------
import numpy as np
from scipy.stats import skew
import pandas as pd
arr = np.random.randint(1, 10, 10)
arr = list(arr)
# print(arr)
# # more weight in the right when skew>0,
# # determine skew close enough to zero
# print(skew(arr))
# print(skew([1, 2, 3, 4, 5]))
# part 2 ----------------------------------
# df = pd.read_csv('Data/nba.csv')
df = pd.read_csv('Data/XAUNZD_Daily.csv')
# print(df.tail())
# skewness along the index axis
print(df.skew(axis=0, skipna=True))
# skewness of the data over the column axis
# print(df.skew(axis=1, skipna=True))
| true |
920fbc4957ec799af76035cbb258f2f41392f030 | Reskal/Struktur_data_E1E119011 | /R.2.4.py | 1,096 | 4.5625 | 5 | ''' R-2.4 Write a Python class, Flower, that has three instance variables of type str,
int, and float, that respectively represent the name of the flower, its number of petals, and its price. Your class must include a constructor method
that initializes each variable to an appropriate value, and your class should
include methods for setting the value of each type, and retrieving the value
of each type. '''
class Flower:
def __init__(self, name, petals, price):
self._name = name
self._petals = petals
self._price = price
def get_name(self):
return self._name
def get_petals(self):
return self._petals
def get_price(self):
return self._price
def set_name(self, name):
self._name = name
def set_petals(self, petals):
self._petals = petals
def set_price(self, price):
self._price = price
# f = Flower('sunflower', 24, 1.25)
# print(f.get_name())
# print(f.get_petals())
# print(f.get_price())
# f.set_name('rose')
# f.set_petals(32)
# f.set_price(1.45)
# print(f.get_name())
# print(f.get_petals())
# print(f.get_price())
| true |
de037860649e57eab88dc9fd8ae4cdab26fcb47a | sahilqur/python_projects | /Classes/inventory.py | 1,720 | 4.28125 | 4 | """
Simple python application for maintaining the product list in the inventory
"""
class product:
price, id, quantity = None, None, None
"""
constructor for product class
"""
def __init__(self, price, id, quantity):
self.price = price
self.id = id
self.quantity = quantity
"""
update price function
"""
def update_price(self, price):
self.price = price
"""
update quantity function
"""
def update_quantity(self,quantity):
self.quantity = quantity
"""
print product function
"""
def print_product(self):
print "id is %d\nprice is %.2f\nquantity is %d\n" % (self.id, self.price, self.quantity)
class Inventory:
"""
constructor for inventory class
"""
def __init__(self):
self.product_list = []
"""
add product function
"""
def add_product(self,product):
self.product_list.append(product)
"""
remove product function
"""
def remove_product(self,product):
self.product_list.remove(product)
"""
print inventory function
"""
def print_inventory(self):
total= 0.0
for p in self.product_list:
total+= p.quantity * p.price
print p.print_product()
print "total is %.2f" % total
"""
main function
"""
if __name__ == '__main__':
p1 = product(1.4, 123, 5)
p2 = product(1, 3432, 100)
p3 = product(100.4, 2342, 99)
I = Inventory()
I.add_product(p1)
I.add_product(p2)
I.add_product(p3)
I.print_inventory()
| true |
7279f2f62f5fab795ab14c5eaa8959fc8b1a1226 | gdgupta11/100dayCodingChallenge | /hr_nestedlist.py | 2,031 | 4.28125 | 4 | """
# 100daysCodingChallenge
Level: Easy
Goal:
Given the names and grades for each student in a Physics class of
students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
[["Gaurav",36], ["GG", 37.1], ["Rob", 42], ["Jack", 42]]
Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line.
Input Format
The first line contains an integer,
, the number of students.
The subsequent lines describe each student over
lines; the first line contains a student's name, and the second line contains their grade.
Constraints: 2 <= N <= 5
There will always be one or more students having the second lowest grade.
Output Format
Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line.
"""
if __name__ == "__main__":
main_list = []
for _ in range(int(input())):
name = input()
score = float(input())
main_list.append([name, score])
# using lambda function here to sort the list of lists by second value
main_list.sort(key = lambda main_list: main_list[1])
tmpList = [lst[1] for lst in main_list]
# Taking the all the scores and making set of it to get unique values
tmpList = set(tmpList)
name_list = []
testList = []
for l in tmpList:
testList.append(l)
# sorting that unique list to get second lowest score
testList.sort()
# checking in main list for all the students who matches the second lowest score (Note: There might be more than 1 students with second lowest score)
for lst in main_list:
if lst[1] == testList[1]:
name_list.append(lst[0])
# sorting those names by alphabetically and printing them
name_list.sort()
for name in name_list:
print(name)
"""
Learnings:
using lambda Function to sort the list of list using value at second [1] position.
"""
| true |
c93d362cfdbb5d7ff952181b68dda9d2b378d0c5 | Berucha/adventureland | /places.py | 2,813 | 4.375 | 4 | import time
class Places:
def __init__(self, life):
'''
returns print statements based on the user's input (car color)
and adds or takes away life points accordingly
'''
#testing purposes:
# print('''In this minigame, the user has been walking along to Adventurland.
# However, the user has stumbled across three cars. This car will take you to a mysterious location!
# The user must select a car. Which color car do you choose.. Red, Blue, or Green?
time.sleep(3)
print('')
self.life = life
print("* Some time later *...") #introduction to the game of places
time.sleep(2)
print()
print('You have been walking through Adventurland trying to reach the castle. It seems forever away.')
time.sleep(2.75)
print()
print("Luckily you have stumbled across three cars. Each car will take you to a mysterious location!")
self.car_colors()
time.sleep(2.5)
def car_colors(self):
'''
evaluates which color the user picks and returns the according print statements and life points
:param self: object of the places class
:return:none
'''
print()
time.sleep(2)
self.user_color = input("You must select a car. Which color car do you choose.. Red, Blue, or Green? ").lower() #user must select a car
while self.user_color != ("red") and self.user_color != ("green") and self.user_color != ("blue"):
self.user_color = (input("You must select a car. Which color car do you choose.. Red, Blue, or Green? ")).lower()
if self.user_color == "red":
print() #if user chooses red then it is a bad choice and they lose life points
time.sleep(1.75)
print('''Uh-Oh! Your car takes you to the home of a troll who is one of the wicked ruler's minions!
You are forced to become his prisoner.''')
self.life -= 3
print('* 2 years later you escape and continue on with your journey *')
elif self.user_color == "blue":
print() #if user chooses blue then it is a good choice and they gain life points
time.sleep(1.75)
print(
"Yayyy! Your car takes you to the home of the Leaders of the Adventurer Revolution, where they feed and shelter you for the night.")
self.life += 2
elif self.user_color == "green": #if user chooses green then it is a okay choice and they dont gain life points nor lose them
print()
time.sleep(1.75)
print(
"Your car takes you to Adventureland's forest and then breaks down, you must continue your journey from here.")
#
# Places()
| true |
d0d009499f6dd7f4194f560545d12f82f2b73db8 | starlinw5995/cti110 | /P4HW1_Expenses_WilliamStarling.py | 1,358 | 4.1875 | 4 | # CTI-110
# P4HW1 - Expenses
# William Starling
# 10/17/2019
#
# This program calculates the users expenses.
# Initialize a counter for the number of expenses entered.
number_of_expenses = 1
# Make a variable to control loop.
expenses = 'y'
# Enter the starting amount in your account.
account = float(input('Enter starting amount in account? '))
print()
#Make a variable for the total of the expenses.
total_expenses = 0
# Begin the loop.
while expenses == 'y':
# Get the expenses.
expenses = float(input('Enter expense ' + str(number_of_expenses) + ' : '))
#Calculate the total of expenses.
total_expenses = total_expenses + expenses
# Add 1 to the expense line everytime.
number_of_expenses = number_of_expenses + 1
# Ask if you want another expense.
expenses = input('Do you want to enter another expense? (y/n) ')
print()
# Display amount in account to begin with.
if expenses == 'n':
print('Amount in account before expense subtraction $',
format(account,'.0f'))
# Display number of expenses used.
print('Number of expenses entered:', number_of_expenses - 1 ,'')
print()
#Calculate and display amount left in account.
print('Amount in account AFTER expenses subtracted is $',
format(account - total_expenses,'.0f'))
| true |
3a0f1e27326226da336ceb45290f89e83bb1f781 | dosatos/LeetCode | /Easy/arr_single_number.py | 2,254 | 4.125 | 4 | """
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
Clarification questions:
How big is N?
Solution:
The easiest solution would be to use a dictionary:
- add to the dict each value seen with a value of 1
- and set the value to zero if the integer was seen twice
- after looping once, find a value with a value of 1
"""
import collections
class Solution:
def singleNumber(self, nums):
"""
using XOR operator
:type nums: List[int]
:rtype: int
"""
res = 0
for num in nums:
res ^= num
return res
# def singleNumber(self, nums):
# """
# using Counter instead
# :type nums: List[int]
# :rtype: int
# """
# # use a container to look up value at a constant cost
# # worst complexity O(N)
# container = collections.Counter(nums)
# # find the value that was seen only once
# # worst complexity O((N-1)/2 + 1) => O(N) if N is very large
# for k, v in container.items():
# if v == 1:
# return k # Total complexity is O(N) in the worst case
# return 0 # in case the list is empty
# def singleNumber(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# # use a container to look up value at a constant cost
# # worst complexity O(N)
# container = {}
# for num in nums:
# try: # increase by one if seen already
# container[num] += 1
# except: # add the number to the container otherwise
# container[num] = 0
# # find the value that was seen only once
# # worst complexity O((N-1)/2 + 1) => O(N) if N is very large
# for k, v in container.items():
# if v == 0:
# return k
# return 0
# # total complexity is O(N)
| true |
2fc808a248480a8840944c8e927ebdb2f23e854a | dosatos/LeetCode | /Easy/ll_merge_two_sorted_lists.py | 2,574 | 4.125 | 4 | """
Percentile: 97.38%
Problem:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
Solution:
Change "pointers" as in merge sort algorithm.
Time Complexity = O(N+M)
Space complexity = O(1)
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# node1, node2 = l1, l2
# head = ListNode(0)
# node = head
# while node1 and node2:
# if node1.val <= node2.val:
# tmp = node1.next # save tmp
# node.next = node1 # append
# node = node.next # increment
# node.next = None # clean up node
# node1 = tmp # use tmp
# else:
# tmp = node2.next
# node.next = node2
# node = node.next
# node.next = None
# node2 = tmp
# if node1:
# node.next = node1
# else:
# node.next = node2
# return head.next
# def mergeTwoLists(self, l1, l2):
# """
# :type l1: ListNode
# :type l2: ListNode
# :rtype: ListNode
# """
# if not l1:
# return l2
# if not l2:
# return l1
# if l1.val < l2.val:
# l1.next = self.mergeTwoLists(l1.next, l2)
# return l1
# else:
# l2.next = self.mergeTwoLists(l2.next, l1)
# return l2
# def mergeTwoLists(self, a, b):
# if not a or b and a.val > b.val:
# a, b = b, a
# if a:
# a.next = self.mergeTwoLists(a.next, b)
# return a
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1: return l2
if not l2: return l1
if l1.val < l2.val:
l3, l1 = l1, l1.next
else:
l3, l2 = l2, l2.next
cur = l3
while l1 and l2:
if l1.val < l2.val:
cur.next, l1 = l1, l1.next
else:
cur.next, l2 = l2, l2.next
cur = cur.next
cur.next = l1 if l1 else l2
return l3 | true |
066769bf25ea46c40333a8ddf2b87c35bfed4fae | arvindsankar/RockPaperScissors | /rockpaperscissors.py | 1,646 | 4.46875 | 4 | import random
def correct_input(choice):
while choice != "Rock" and choice != "Scissors" and choice != "Paper":
# corrects rock
if choice == "rock" or choice == "R" or choice == "r":
choice = "Rock"
# corrects scissors
elif choice == "scissors" or choice == "S" or choice == "s":
choice = "Scissors"
# corrects paper
elif choice == "paper" or choice == "P" or choice == "p":
choice = "Paper"
else:
print ("Sorry, didn't get that.\n")
choice = input("Do you chose Rock, Paper, or Scissors? ")
return choice
print ("\nTo play, select one of the following choices: Rock, Paper, or Scissors.\n")
print ("Rock beats Scissors and loses to Paper.")
print ("Paper beats Rock and loses to Scissors")
print ("Scissors beats Paper and loses to Rock\n")
# prompt player for choice
choice = input("Do you chose Rock, Paper, or Scissors? ")
choice = correct_input(choice)
# CPU randomly selects from this list of choices
CPUChoices = ["Rock", "Paper", "Scissors"]
# CPU
CPU = CPUChoices[random.randrange(0,3)]
while choice == CPU:
print ("You and the Computer both picked " + CPU + " so we'll try again.\n")
choice = input("Do you chose Rock, Paper, or Scissors? ")
choice = correct_input(choice)
CPU = CPUChoices[random.randrange(0,3)]
print ("\nYou chose: " + choice)
print ("Computer choses: " + CPU + "\n")
# Player choses Rock
if ( choice == "Rock" and CPU == "Paper"
or choice == "Paper" and CPU == "Scissors"
or choice == "Scissors" and CPU == "Rock"
):
print (CPU + " beats " + choice + ". You lose!")
else:
print (choice + " beats " + CPU + ". You win!")
print ("\nThanks for playing!")
| true |
fd2236eaf9f68b84c79bc5ea679231c8d1678210 | charuvashist/python-assignments | /assigment10.py | 2,992 | 4.34375 | 4 | '''Ques 1. Create a class Animal as a base class and define method animal_attribute. Create another class Tiger which is
inheriting Animal and access the base class method.'''
class Animal:
def animal_attribute(self):
print("This is an Animal Class")
class Tiger(Animal):
def display(self):
print("This is the Lion Class")
a= Tiger()
a.animal_attribute()
a.display()
#Mr.Hacker
'''Ques 2. What will be the output of following code.'''
class A:
def f(self):
return self.g()
def g(self):
return 'A'
class B(A):
def g(self):
return 'B'
a = A()
b = B()
print a.f(), b.f()
print a.g(), b.g()'''
# Solution
class A:
def f(self):
return self.g()
def g(self):
return 'A'
class B(A):
def g(self):
return 'B'
a = A()
b = B()
print(a.f(), b.f())
print(a.g(), b.g())
#Mr.SINGH
'''Ques 3. Create a class Cop. Initialize its name, age , work experience and designation. Define methods to add,
display and update the following details. Create another class Mission which extends the class Cop. Define method
add_mission _details. Select an object of Cop and access methods of base class to get information for a particular
cop and make it available for mission.'''
class Cop:
def add(self,name,age,work_experience,designation):
self.name = name
self.age = age
self.work_experience = work_experience
self.designation = designation
def display(self):
print("\n\nDetails Will be:")
print("\nName is: ",self.name)
print("\nAge is: ",self.age)
print("\nWork_Experience: ",self.work_experience)
print("\nDestination: ",self.designation)
def update(self,name,age,work_experience,designation):
self.name = name
self.age = age
self.work_experience = work_experience
self.designation = designation
class Mission(Cop):
def add_mission_details(self,mission):
self.mission=mission
print(self.mission)
m=Mission()
m.add_mission_details("Mission detail Assigned to HP :")
m.add("Bikram",18,8,"Hacker\n")
m.display()
m.update("Faizal",21,2,"Hacker")
m.display()
#Hacker
#MR.SINGH@
'''Ques 4. Create a class Shape.Initialize it with length and breadth Create the method Area.
Create class rectangle and square which inherits shape and access the method Area.'''
class Shape:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
self.area = self.length * self.breadth
class Rectangle(Shape):
def area_rectangle(self):
print("Area of Rectangle is :", self.area)
class Square(Shape):
def area_square(self):
print("Area of Square is :", self.area)
length = int(input("Enter the Length:"))
breadth = int(input("Enter the Breadth:"))
a = Rectangle(length,breadth)
b = Square(length,breadth)
if length == breadth:
b.area()
b.area_square()
else:
a.area()
a.area_rectangle() | true |
a336d3cc2a6067b7716b502025456667631106d5 | joemmooney/search-text-for-words | /setup.py | 1,437 | 4.5625 | 5 | # This file is the main file for running this program.
import argparse
from fileReader import read_file
# The main function that is run when starting the program.
# It sets up argument parsing for the file name to read, the number of most common words to print,
# whether to return a json file, and the name for the json file that is being returned.
# Then it sends these arguments to the function that reads and processes the file.
def main():
parser = argparse.ArgumentParser(description="Arguments being passed to the word count program")
parser.add_argument("file_name", help="Name of the .txt file to count words in")
parser.add_argument("--number_of_words_to_print", type=int, default=10, help="The number of words to print " +
"when showing the top n most common words (defaults to 10)")
parser.add_argument("--return_json", action="store_true", help="If this flag is present, " +
"a json file with word counts will be returned")
parser.add_argument("--json_name", type=str, default="word_counts", help="Part of the name of the json file " +
"that the word counts will be saved to (naming convention is \"{file_name}_{json_name}.json\") " +
"(defaults to word_counts)")
args = parser.parse_args()
read_file(args.file_name, args.number_of_words_to_print, args.return_json, args.json_name)
if __name__ == "__main__":
main() | true |
cb8844bcac1c3fa02a35fbab9c6e8fd5c993cb74 | MysticSoul/Exceptional_Handling | /answer3.py | 444 | 4.21875 | 4 | # Program to depict Raising Exception
'''
try:
raise NameError("Hi there") # Raise Error
except NameError:
print "An exception"
raise # To determine whether the exception was raised or not
'''
'''Answer2.=> According to python 3.x
SyntaxError: Missing parentheses in call to print
According to python 2.x
The output would be:
NameError: Hi there
''' | true |
9aff241bff636fa31f64cc83cb35b3ecf379738a | devhelenacodes/python-coding | /pp_06.py | 621 | 4.125 | 4 | # String Lists
# Own Answer
string = input("Give me a word:\n")
start_count = 0
end_count = len(string) - 1
for letter in string:
if string[start_count] == string[end_count]:
start_count += 1
end_count -= 1
result = "This is a palindrome"
else:
result = "This is not a palindrome"
print(result)
# Learned def reverse, more effective way
def reverse(word):
x = ''
for position in range(len(word)):
x += word[len(word)-1-position]
return x
word = input('Give me a word:\n')
wordReversed = reverse(word)
if wordReversed == word:
print('This is a palindrome')
else:
print('This is not a palindrome')
| true |
26fb03d7961e7a2d1c34fd0ef19b5ef2f6293061 | emeryberger/COMPSCI590S | /projects/project1/wordcount.py | 839 | 4.28125 | 4 | # Wordcount
# Prints words and frequencies in decreasing order of frequency.
# To invoke:
# python wordcount.py file1 file2 file3...
# Author: Emery Berger, www.emeryberger.com
import sys
import operator
# The map of words -> counts.
wordcount={}
# Read filenames off the argument list.
for filename in sys.argv[1:]:
file=open(filename,"r+")
# Process all words.
for word in file.read().split():
# Get the previous count (possibly 0 if new).
count = wordcount.get(word, 0)
# Increment it.
wordcount[word] = count + 1
file.close();
# Sort in reverse order by frequency.
sort1 = sorted(wordcount.iteritems(), key=operator.itemgetter(0))
sort2 = sorted(sort1, key=operator.itemgetter(1), reverse = True)
for pair in sort2:
print ("%s : %s" %(pair[0] , pair[1]))
| true |
84533ee76a2dc430ab5775fa00a4cc354dfc2238 | tkruteleff/Python | /16 - Password Generator/password_generator.py | 1,239 | 4.3125 | 4 | import random
#Write a password generator in Python.
#Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols.
#The passwords should be random, generating a new password every time the user asks for a new password.
#Include your run-time code in a main method.
#Extra:
#Ask the user how strong they want their password to be. For weak passwords, pick a word or two from a list.
chars = list(range(ord('a'),ord('z')+1))
chars += list(range(ord('A'),ord('Z')+1))
chars += list(range(ord('0'),(ord('9')+1)))
chars += list(range(ord('!'),ord('&')+1))
dictionary = ["word", "input", "list", "end", "order", "rock", "paper", "scissors"]
password = ""
password_strength = str(input("Do you want a weak or strong password? "))
def generate_weak(list):
generated = random.choices(dictionary, k=2)
return (password.join(generated))
def generate_strong(keys):
key = []
for i in range(16):
key.append(chr(keys[random.randint(0,len(keys)-1)]))
return (password.join(key))
if password_strength == "weak":
print(generate_weak(dictionary))
elif password_strength == "strong":
print(generate_strong(chars))
else:
print("sigh")
| true |
9777a2a85ad74c0cad75352fcded12ef838f3eb0 | echang19/Homework-9-25 | /GradeReport.py | 987 | 4.15625 | 4 | '''
Created on Mar 12, 2019
@author: Evan A. Chang
Grade Report
'''
def main():
studentList={'Cooper':['81','86', '90', '97'],'Jennie':['98', '79','99', '87', '82'], 'Julia':['87', '80','75', '10', '78']}
student=''
read=input("Would you like to access a student's grades?")
read.lower()
if read== "no":
student= input("Please enter the name of a student")
student.str
grades=''
while grades.lower !='done':
grades=input('please enter the students grades when done type "done" ')
grades.str
studentList[student]=grades
elif read=="yes":
name=input("Please enter the name of the student you want to see")
print(studentList[name])
again=input("would you like to see another's students grades?")
while again.lower()=='yes':
name=input("Please enter the name of the student you want to see")
print(studentList[name])
| true |
ed4293c4fcc473795705f555a305a4ee7c7a2701 | mittal-umang/Analytics | /Assignment-2/VowelCount.py | 977 | 4.25 | 4 | # Chapter 14 Question 11
# Write a program that prompts the user to enter a
# text filename and displays the number of vowels and consonants in the file. Use
# a set to store the vowels A, E, I, O, and U.
def main():
vowels = ('a', 'e', 'i', 'o', 'u')
fileName = input("Enter a FileName: ")
vowelCount = 0
consonantsCount = 0
try:
with open(fileName, "rt") as fin:
fileContents = fin.read().split(" ")
except FileNotFoundError:
print("File Not Found")
except OSError:
print("Cannot Open File")
finally:
fin.close()
while fileContents:
word = fileContents.pop().lower()
for i in word:
if i.isalpha():
if i in vowels:
vowelCount += 1
else:
consonantsCount += 1
print("There are ", vowelCount, "vowels and", consonantsCount, "consonants in", fileName)
if __name__ == "__main__":
main()
| true |
67593b7fcb04e87730e87066e587576fc3a88386 | mittal-umang/Analytics | /Assignment-1/PalindromicPrime.py | 1,189 | 4.25 | 4 | # Chapter 6 Question 24
# Write a program that displays the first 100 palindromic prime numbers. Display
# 10 numbers per line and align the numbers properly
import time
def isPrime(number):
i = 2
while i <= number / 2:
if number % i == 0:
return False
i += 1
return True
def reverse(number):
reverseNumber = ""
while number > 0:
reverseNumber += str(number % 10)
number = number // 10
return int(reverseNumber)
def isPalindrome(number):
if reverse(number) == number:
return True
else:
return False
def main():
maxNumber = eval(input("Enter the a number of palindromic prime numbers are required: "))
count = 0
primeNumber = 2
while count < maxNumber:
# Evaluating isPalindrome first to reduce the computational time of prime number.
# since number of iterations in isPrime Functions are more.
if isPalindrome(primeNumber) and isPrime(primeNumber):
print(format(primeNumber, '6d'), end=" ")
count += 1
if count % 10 == 0:
print()
primeNumber += 1
if __name__ == "__main__":
main()
| true |
cea462ca0b7bf4c088e1a2b035f26003052fcef2 | mittal-umang/Analytics | /Assignment-2/KeyWordOccurence.py | 1,328 | 4.40625 | 4 | # Chapter 14 Question 3
# Write a program that reads in a Python
# source code file and counts the occurrence of each keyword in the file. Your program
# should prompt the user to enter the Python source code filename.
def main():
keyWords = {"and": 0, "as": 0, "assert": 0, "break": 0, "class": 0,
"continue": 0, "def": 0, "del": 0, "elif": 0, "else": 0,
"except": 0, "False": 0, "finally": 0, "for": 0, "from": 0,
"global": 0, "if": 0, "import": 0, "in": 0, "is": 0, "lambda": 0,
"None": 0, "nonlocal": 0, "not": 0, "or": 0, "pass": 0, "raise": 0,
"return": 0, "True": 0, "try": 0, "while": 0, "with": 0, "yield": 0}
filename = input("Enter a Python source code filename: ").strip()
try:
with open(filename) as fin:
text = fin.read().split()
except FileNotFoundError:
print("File Not Found")
finally:
fin.close()
keys = list(keyWords.keys())
for word in text:
if word in keys:
keyWords[word] += 1
for i in range(len(keys)):
if keyWords.get(keys[i]) < 1:
print(keys[i], "occurs", keyWords.get(keys[i]), "time")
else:
print(keys[i], "occurs", keyWords.get(keys[i]), "times")
if __name__ == "__main__":
main()
| true |
49837fed1d537650d55dd8d6c469e7c77bc3a4c6 | mittal-umang/Analytics | /Assignment-1/ReverseNumber.py | 502 | 4.28125 | 4 | # Chapter 3 Question 11
# Write a program that prompts the user to enter a four-digit integer
# and displays the number in reverse order.
def __reverse__(number):
reverseNumber = ""
while number > 0:
reverseNumber += str(number % 10)
number = number // 10
return reverseNumber
def main():
number = eval(input("Enter an integer: "))
reversedNumber = __reverse__(number)
print("The reversed number is", reversedNumber)
if __name__ == "__main__":
main()
| true |
c86efaf3ce656c67a47a6df3c036345d6e604001 | mittal-umang/Analytics | /Assignment-2/AccountClass.py | 1,428 | 4.1875 | 4 | # Chapter 12 Question 3
class Account:
def __init__(self, id=0, balance=100, annualinterestrate=0):
self.__id = id
self.__balance = balance
self.__annualInterestRate = annualinterestrate
def getMonthlyInterestRate(self):
return str(self.__annualInterestRate * 100) + "%"
def getMonthlyInterest(self):
return "$" + str(self.__annualInterestRate * self.__balance / 12)
def getId(self):
return self.__id
def getBalance(self):
return "$" + str(self.__balance)
def withdraw(self, amount):
if self.__balance < amount:
raise Exception("Balance Less than withdrawal Amount")
else:
self.__balance -= amount
def deposit(self, amount):
self.__balance += amount
def main():
account = Account(1122, 20000, 0.045)
print("Current account balance is ", account.getBalance())
account.withdraw(2500)
print("Account balance after withdrawal is ", account.getBalance())
account.deposit(3000)
print("Account balance after deposit is ", account.getBalance())
print("Account Details are as below: ")
print("\tAccount ID : ", account.getId())
print("\tCurrent Balance is ", account.getBalance())
print("\tAnnual Interest rate is ", account.getMonthlyInterestRate())
print("\tAnnual Interest is ", account.getMonthlyInterest())
if __name__ == "__main__":
main()
| true |
692505ec86ff96fe6e96802c2b2cf6306e11e2e0 | mfnu/Python-Assignment | /Functions-repeatsinlist.py | 554 | 4.1875 | 4 | ''' Author: Madhulika
Program: Finding repeats in a list.
Output: The program returns the number of times the element is repeated in the list.
Date Created: 4/60/2015
Version : 1
'''
mylist=["one", "two","eleven", "one", "three", "two", "eleven", "three", "seven", "eleven"]
def count_frequency(mylist):
result = dict((i,mylist.count(i)) for i in mylist)
return result
print(count_frequency(mylist))
'''
O/P:
C:\Python34\Assignments>python Functions-repeatsinlist.py
{'eleven': 3, 'seven': 1, 'one': 2, 'two': 2, 'three': 2}
''' | true |
013cb916d56e94c09e5d0451ceff7c532c3a85cd | rustyhu/design_pattern | /python_patterns/builder.py | 1,028 | 4.125 | 4 | "Personal understanding: builder pattern emphasizes on the readability and user convenience, the code structure is not quite neat."
class BurgerBuilder:
cheese = False
pepperoni = False
lettuce = False
tomato = False
def __init__(self, size):
self.size = size
def addPepperoni(self):
self.pepperoni = True
return self
def addLecttuce(self):
self.lettuce = True
return self
def addCheese(self):
self.cheese = True
return self
def addTomato(self):
self.tomato = True
return self
# builder
def build(self):
return Burger(self)
class Burger:
def __init__(self, builder):
self.size = builder.size
self.cheese = builder.cheese
self.pepperoni = builder.pepperoni
self.lettuce = builder.lettuce
self.tomato = builder.tomato
if __name__ == '__main__':
# call builder
b = BurgerBuilder(14).addPepperoni().addLecttuce().addTomato().build()
print(b)
| true |
4cc5e4aa3463e07ce239339aac99d5821ec786a1 | ashok148/TWoC-Day1 | /program3.py | 423 | 4.34375 | 4 | #Program to swap two variable without using 3rd variable....
num1 = int(input("Enter 1st number : "))
num2 = int(input("Enter 2nd number : "))
print("Before swaping")
print("num1 = ",num1)
print("num2 = ",num2)
print("After swapping")
#LOGIC 1:- of swapping
# num1 = num1 + num2
# num2 = num1 - num2
# num1 = num1 - num2
#LOGIC 2:- of swapping
num1,num2 = num2,num1
print("num1 = ",num1)
print("num2 = ",num2) | true |
9878feed23238d5a152e08b2547b8db64d616a35 | send2manoo/All-Repo | /myDocs/pgm/python/ml/04-PythonMachineLearning/04-MatplotlibCrashCourse/01-LinePlot.py | 547 | 4.25 | 4 | '''
Matplotlib can be used for creating plots and charts.
The library is generally used as follows:
Call a plotting function with some data (e.g. plot()).
Call many functions to setup the properties of the plot (e.g. labels and colors).
Make the plot visible (e.g. show()).
'''
# The example below creates a simple line plot from one-dimensional data.
# basic line plot
import matplotlib.pyplot as plt
import numpy
myarray = numpy.array([1, 2, 3])
plt.plot(myarray)
plt.xlabel('some x axis')
plt.ylabel('some y axis')
plt.show()
| true |
849647385e43448924aa7108a5f4986015c0c88a | send2manoo/All-Repo | /myDocs/pgm/python/ml/03-MachineLearningAlgorithms/1-Baseline machine learning algorithms/2-Zero Rule Algorithm Classification.py | 1,166 | 4.125 | 4 | from random import seed
from random import randrange
# zero rule algorithm for classification
def zero_rule_algorithm_classification(train, test):
output_values = [row[-1] for row in train]
print 'output=',output_values
print "set=",set(output_values)
prediction = max(set(output_values), key=output_values.count)
'''
The function makes use of the max() function with the key attribute, which is a little clever.
Given a list of class values observed in the training data, the max() function takes a set of unique class values and calls the count on the list of class values for each class value in the set.
The result is that it returns the class value that has the highest count of observed values in the list of class values observed in the training dataset.
If all class values have the same count, then we will choose the first class value observed in the dataset.
'''
print "prediction-",prediction
predicted = [prediction for i in range(len(train))]
return predicted
seed(1)
train = [['0'], ['0'], ['0'], ['0'], ['1'], ['1']]
test = [[None], [None], [None], [None]]
predictions = zero_rule_algorithm_classification(train, test)
print(predictions)
| true |
57a99993916020b5c5780236c8efb052974c51b0 | wuxu1019/1point3acres | /Google/test_246_Strobogrammatic_Number.py | 908 | 4.15625 | 4 | """
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
Example 1:
Input: "69"
Output: true
Example 2:
Input: "88"
Output: true
Example 3:
Input: "962"
Output: false
"""
class Solution(object):
def isStrobogrammatic(self, num):
"""
:type num: str
:rtype: bool
"""
same = '018'
diff = '69'
l, r = 0, len(num) - 1
while l < r:
s = num[l] + num[r]
if s[0] in same and s.count(s[0]) == len(s):
l += 1
r -= 1
elif s == diff or s[::-1] == diff:
l += 1
r -= 1
else:
return False
if l == r:
return num[r] in same
return True
| true |
bcb7788af7663d0e9c52057795c5f62acc349ba1 | mennanov/problem-sets | /other/strings/string_all_unique_chars.py | 1,371 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Implement an algorithm to determine if a string has all unique characters.
"""
def all_unique_set(string):
"""
Running time and space is O(N).
"""
return len(string) == len(set(string))
def all_unique_list(string):
"""
Running time is O(N), space is O(R) where R is a length of an alphabet.
"""
# assume we have an ASCII string
r = 65535 if isinstance(string, unicode) else 255
if len(string) > r:
return False
chars = [0] * r
for i, char in enumerate(string):
chars[ord(char)] += 1
if chars[ord(char)] > 1:
return False
return True
def all_unique_bit(string):
"""
Running time is O(N), required space is 1 byte only for ASCII string and 2 bytes for a Unicode string.
Space usage is optimized using a bit vector.
"""
# bit vector
chars = 0
for i, char in enumerate(string):
# check if we have already seen this char
if chars & (1 << ord(char)) > 0:
return False
else:
chars |= (1 << ord(char))
return True
if __name__ == '__main__':
s = 'abcdefghatyk'
assert not all_unique_set(s)
assert not all_unique_list(s)
assert not all_unique_bit(s)
s = 'abcdefghtlk'
assert all_unique_set(s)
assert all_unique_list(s)
assert all_unique_bit(s) | true |
367e5bcdd755649dbedac19066b4f77e3a1293d7 | suminb/coding-exercise | /daily-interview/binary_tree_level_with_minimum_sum.py | 1,516 | 4.125 | 4 | # [Daily Problem] Binary Tree Level with Minimum Sum
#
# You are given the root of a binary tree. Find the level for the binary tree
# with the minimum sum, and return that value.
#
# For instance, in the example below, the sums of the trees are 10, 2 + 8 = 10,
# and 4 + 1 + 2 = 7. So, the answer here should be 7.
#
# class Node:
# def __init__(self, value, left=None, right=None):
# self.val = value
# self.left = left
# self.right = right
#
# def minimum_level_sum(root):
# # Fill this in.
#
# # 10
# # / \
# # 2 8
# # / \ \
# # 4 1 2
# node = Node(10)
# node.left = Node(2)
# node.right = Node(8)
# node.left.left = Node(4)
# node.left.right = Node(1)
# node.right.right = Node(2)
#
# print minimum_level_sum(node)
from collections import deque
import pytest
from common import build_binary_tree
def minimum_level_sum(root):
queue = deque()
queue.append((root, 0))
sums = {}
while queue:
node, level = queue.popleft()
if node:
sums.setdefault(level, 0)
sums[level] += node.val
queue.append((node.left, level + 1))
queue.append((node.right, level + 1))
return min(sums.values())
@pytest.mark.parametrize("values, expected", [
([1], 1),
([1, 2], 1),
([1, None, 3], 1),
([10, 2, 8, 4, 1, 2], 7),
([10, 9, 8, 7, 6, 5, 4], 10),
])
def test_minimum_level_sum(values, expected):
actual = minimum_level_sum(build_binary_tree(values))
assert expected == actual | true |
7cd442736a1d68ef5e38bdb4927f7b02f2180c3f | zgaleday/UCSF-bootcamp | /Vector.py | 2,932 | 4.53125 | 5 | class Vector(object):
"""Naive implementation of vector operations using the python list interface"""
def __init__(self, v0):
"""
Takes as input the two vectors for which we will operate on.
:param v0: A 3D vector as either a python list of [x_0, y_0, z_0] or tuple of same format
"""
self.v0 = v0
def get(self, index):
"""
Gets the desired x, y, z coordinate
:param index: 0 == x, 1 == y, 2 == z (int)
:return: the value of the specified dimension
"""
if (index > 2 or index < 0):
raise ValueError("Please input a valid index [0-2]")
return self.v0[index]
def add(self, other):
"""
Adds two Vector objects.
:param other: Another Vector object
:return: A Vector equal to the vector sum of the current vector and other
"""
return Vector([self.v0[i] + other.get(i) for i in range(3)])
def subtract(self, other):
"""
Subtract two Vector objects
:param other: Another vector object to be subtracted
:return: A Vector equal to the vector subtraction of the current vector and other
"""
return Vector([self.v0[i] - other.get(i) for i in range(3)])
def normalize(self):
"""
Returns the unit vector of the current vector
:return: A new vector object == the unit vector of the current vector
"""
magnitude = self.dot_product(self) ** .5
return Vector([self.v0[i] / magnitude for i in range(3)])
def dot_product(self, other):
"""
Returns the dot product of the current vector and the other Vector
:param other: Another instance of the vector class
:return:
"""
return sum([self.v0[i] * other.get(i) for i in range(3)])
def cross_product(self, other):
"""
Returns the cross product of the current vector and other
:param other: A Vector object
:return: The cross product of the two Vectors as a new Vector object
"""
x0, y0, z0 = self.v0
x1, y1, z1 = other.get(0), other.get(1), other.get(2)
# Calculate the new vector componants for readability
x2 = y0 * z1 - z0 * y1
y2 = z0 * x1 - x0 * z1
z2 = x0 * y1 - y0 * x1
return Vector([x2, y2, z2])
def __str__(self):
return self.v0.__str__()
if __name__ == "__main__":
v0 = Vector([1, 2, 3])
v1 = Vector([3, 4, 5])
print("Adding " + str(v0) + "and " + str(v1) + "yields: " + str(v0.add(v1)))
print("Subtracting " + str(v0) + "and " + str(v1) + "yields: " + str(v0.subtract(v1)))
print("Normalizing " + str(v0) + "yields: " + str(v0.normalize()))
print("Dotting " + str(v0) + "and " + str(v1) + "yields: " + str(v0.dot_product(v1)))
print("Crossing " + str(v0) + "and " + str(v1) + "yields: " + str(v0.cross_product(v1))) | true |
bf320a4a3eb4a61dbc1f485885196c0067208c94 | cs-fullstack-2019-fall/python-classobject-review-cw-LilPrice-Code-1 | /index.py | 1,852 | 4.28125 | 4 | def main():
pro1()
pro2()
# Problem 1:
#
# Create a Movie class with the following properties/attributes: movieName, rating, and yearReleased.
#
# Override the default str (to-String) method and implement the code that will print the value of all the properties/attributes of the Movie class
#
#
# Assign a value of your choosing for each property/attribute
#
# Print all properties to the console.
#
def pro1():
class Movie:
def __init__(self, movieName, rating,yearReleased):
self.movie = movieName
self.rating = rating
self.year = yearReleased
def __str__(self):
mystr = (f"self.movie = {self.movie}\n"
f"self.rating = {self.rating}\n"
f"self.year = {self.year}")
return mystr
my1 = Movie("A Silent Voice", "9,7/10", "2018")
# !! : create *two* instances
print(my1)
#
# Problem 2:
#
# Create a class Product that represents a product sold online.
#
# A Product has price, quantity and name properties/attributes.
#
# Override the default str (to-String) method and implement the code that will print the value of all the properties/attributes of the Product class
#
# In your main function create two instances of the Product class
#
# Assign a value of your choosing for each property/attribute
#
# Print all properties to the console.
def pro2():
class Product:
def __init__(self,price,quantity,name):
self.price = price
self.quan = quantity
self.name = name
def __str__(self):
mystr = (f"self.price = {self.price}\n"
f"self.quan = {self.quan}\n"
f"self.name = {self.name}")
return mystr
p1 = Product(15, 3, 'apple')
# !! : create *two* instances
print(p1)
main() | true |
1591a5a8e525549a24ed11f49346c6b207b2ef7c | Anthncara/MEMO | /python/coding-challenges/cc-001-convert-to-roman-numerals/Int To Roman V2.py | 896 | 4.28125 | 4 | print("### This program converts decimal numbers to Roman Numerals ###",'\nTo exit the program, please type "exit")')
def InttoRoman(number):
int_roman_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'),\
(50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
if not number.isdigit():
return "Not Valid Input !!!"
number = int(number)
if (number > 3999) or (number < 1):
return "Not Valid Input !!!"
result = ""
while number > 0:
for i, roman in int_roman_map:
while number >= i:
result += roman
number -= i
return result
while True:
number = input("Please enter a number between 1 and 3999, inclusively : ")
if number == "exit":
print("Exiting the program... Good Bye")
break
print(InttoRoman(number))
| true |
eebd301ffac344f8fe7bdf16a8cf9677bb542d3a | G00398275/PandS | /Week 05 - Datastructures/prime.py | 566 | 4.28125 | 4 | # This program lists out the prime numbers between 2 and 100
# Week 05, Tutorial
# Author: Ross Downey
primes = []
upto = 100000
for candidate in range (2, upto):
isPrime = True # Required only to check if divisible by prime number
for divisor in primes: # If it is divisible by an integer it isn't a prime number
if (candidate % divisor == 0):
isPrime = False
break # No reason to keep checking if not prime number
if isPrime:
primes.append(candidate) # If it is a prime number, append it to the list
print (primes) | true |
75a5d8161498d62cbdce415742715a9baac22543 | G00398275/PandS | /Week 02/hello3.py | 235 | 4.21875 | 4 | # Week 02 ; hello3.py, Lab 2.2 First Programs
# This program reads in a person's name and prints out that persons name using format
# Author: Ross Downey
name = input ("Enter your name")
print ('Hello {} \nNice to meet you'.format (name)) | true |
a0986698fa2430008eb4d33ebf02b50e933fc09c | G00398275/PandS | /Week 03/Lab 3.3.1-len.py | 270 | 4.15625 | 4 | # Week 03: Lab 3.3.1 Strings
# This program reads in a strings and outputs how long it is
# Author: Ross Downey
inputString = input ('Please enter a string: ')
lengthOfString = len(inputString)
print('The length of {} is {} characters' .format(inputString, lengthOfString)) | true |
8ff8959b62adcc0f3455ca00c1e9108a16fbf97e | G00398275/PandS | /Week 03/Lab 3.3.3 normalize.py | 575 | 4.46875 | 4 | # Week 03: Lab 3.3.2 Strings
# This program reads in a string and removes any leading or trailing spaces
# It also converts all letters to lower case
# This program also outputs the length of the original string
# Author: Ross Downey
rawString = input("Please enter a string: ")
normalisedString = rawString.strip().lower()
lengthOfRawString = len(rawString)
lengthOfNormalised = len(normalisedString)
print("That string normalised is: {}" .format(normalisedString))
print("We reduced the input string from {} to {} characters" .format (
lengthOfRawString, lengthOfNormalised)) | true |
59fc57e8d10d9f71c59999d297edfaf310676efd | G00398275/PandS | /Week 04-flow/w3Schools-ifElse.py | 1,257 | 4.40625 | 4 | # Practicing ifElse loops, examples in https://www.w3schools.com/python/python_conditions.asp
# Author: Ross Downey
a = 33
b = 200
if b > a: # condition is IF b is greater than a
print("b is greater than a") # Ensure indentation is present for print, i.e. indent for condition code
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b: # condition is ELSE/IF a and b are equal
print("a and b are equal")
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else: # Condition is ELSE, when the preceding if/elif conditions aren't met
print("a is greater than b")
a = 200
b = 33
if b > a:
print("b is greater than a")
else: # same above without the elif condition, can use just IF and ELSE if needed
print("b is not greater than a")
if a > b: print("a is greater than b")
# shorthand if, can do on one line if only one simple condition needed
a = 2
b = 330
print("A") if a > b else print("B")
# shorthand if / else, done on one line
a = int(input("Please enter integer a:"))
b = int(input("Please enter integer b:")) # changing code to inputs, ensure integer is used
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b") | true |
2e60abd703a5013e8ee5f7d2ce30b066833a7872 | arnavgupta50/BinarySearchTree | /BinaryTreeTraversal.py | 1,155 | 4.3125 | 4 | #Thsi Program traverses the Binary Tree in 3 Ways: In/Post/Pre-Order
class Node:
def __init__ (self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return Node(key)
else:
if root.val==key:
return root
elif root.val<key:
root.right=insert(root.right, key)
else:
root.left=insert(root.left, key)
return root
def preorder(root):
if root:
print(root.val)
preorder(root.left)
preorder(root.right)
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(root.val)
r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)
print("Pre-Order Traversal: ")
preorder(r)
print("In-Order Traversal: ")
inorder(r)
print("Post-Oder Traversal: ")
postorder(r)
| true |
e6657c32a76d198d60ad812ef1fc5587e8a74465 | subham-paul/Python-Programming | /Swap_Value.py | 291 | 4.1875 | 4 | x = int(input("Enter value x="))
y = int(input("Enter value y="))
print("The value are",x,"and",y)
x = x^y
y = x^y
x = x^y
print("After the swapping value are",x,"and",y)
"""Enter value x=10
Enter value y=20
The value are 10 and 20
After the swapping value are 20 and 10
"""
| true |
eafda40ba1154d3f8d02c01d9b827f93f3d7edc6 | audflexbutok/Python-Lab-Source-Codes | /audrey_cooper_501_2.py | 1,788 | 4.3125 | 4 | # Programmer: Audrey Cooper
# Lab Section: 502
# Lab 3, assignment 2
# Purpose: To create a menu driven calculator
# set calc equal to true so it runs continuously
calc = True
while calc == True:
# adds two numbers
def add(x, y):
return x + y
# subtracts two numbers
def subtract(x, y):
return x - y
# multiplies two numbers
def multiply(x, y):
return x * y
# divides two numbers
def divide(x, y):
return x / y
# menu driven portion that allows user to select operation
print("Select operation.")
print("1. Add ")
print("2. Subtract ")
print("3. Multiply ")
print("4. Divide ")
print("5. Exit ")
# user input for operation choice
choice = input("Enter choice(1/2/3/4/5):")
# user input for number choice to perform operation
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
# statements to perform the correct operations and print their results
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
elif choice == '5':
break
else:
# input validation
print("Invalid input")
'''
IDLE Output
Select operation.
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter choice(1/2/3/4/5):4
Enter first number: 2
Enter second number: 2
2 / 2 = 1.0
Select operation.
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter choice(1/2/3/4/5):
'''
| true |
71c813eeaea12d9f0b3791bbbf7c2c92fcaf391f | dedx/PHYS200 | /Ch7-Ex7.4.py | 797 | 4.46875 | 4 | #################################
#
# ThinkPython Exercise 7.4
#
# J.L. Klay
# 30-Apr-2012
#
# Exercise 7.4 The built-in function eval takes a string and evaluates
# it using the Python interpreter. For example:
# >>> eval('1 + 2 * 3')
# 7
# >>> import math
# >>> eval('math.sqrt(5)')
# 2.2360679774997898
# >>> eval('type(math.pi)')
# <type 'float'>
# Write a function called eval_loop that iteratively prompts the user,
# takes the resulting input and evaluates it using eval, and prints the
# result.
# It should continue until the user enters 'done', and then return the
# value of the last expression it evaluated.
#
#
import math
def eval_loop():
while True:
line = raw_input('> ')
if line == 'done':
break
last = eval(line)
print last
print last
eval_loop()
| true |
8617d6b008e47ed734b1ecaf568ae94dfc7db835 | sathishmepco/Python-Basics | /basic-concepts/collections/dequeue_demo.py | 1,329 | 4.34375 | 4 | from collections import deque
def main():
d = deque('abcd')
print('Queue of : abcd')
for e in d:
print(e)
print('Add a new entry to the right side')
d.append('e')
print(d)
print('Add a new entry to the left side')
d.appendleft('z')
print(d)
print('Return and remove the right side elt')
print(d.pop())
print('Return and remove the left side elt')
print(d.popleft())
print('Peek of leftmost item')
print(d[0])
print('Peek of rightmost item')
print(d[-1])
print('Reverse of deque')
l = list(reversed(d))
print(l)
print('Search in the deque')
bool = 'c' in d
print(bool)
print('Add multiple elements at once')
d.extend('xyz')
print(d)
print('Right rotation')
d.rotate(1)
print(d)
print('Left rotation')
d.rotate(-1)
print(d)
main()
'''
Queue of : abcd
a
b
c
d
Add a new entry to the right side
deque(['a', 'b', 'c', 'd', 'e'])
Add a new entry to the left side
deque(['z', 'a', 'b', 'c', 'd', 'e'])
Return and remove the right side elt
e
Return and remove the left side elt
z
Peek of leftmost item
a
Peek of rightmost item
d
Reverse of deque
['d', 'c', 'b', 'a']
Search in the deque
True
Add multiple elements at once
deque(['a', 'b', 'c', 'd', 'x', 'y', 'z'])
Right rotation
deque(['z', 'a', 'b', 'c', 'd', 'x', 'y'])
Left rotation
deque(['a', 'b', 'c', 'd', 'x', 'y', 'z'])
''' | true |
c5e31c20a1a55cec683250a8d64ebc8836c3f5b6 | JKodner/median | /median.py | 528 | 4.1875 | 4 | def median(lst):
"""Finds the median of a sequence of numbers."""
status = True
for i in lst:
if type(i) != int:
status = False
if status:
lst.sort()
if len(lst) % 2 == 0:
num = len(lst) / 2
num2 = (len(lst) / 2) + 1
avg = float(lst[num - 1] + lst[num2 - 1]) / 2
median = {"median": avg, "positions": [lst[num - 1], lst[num2 - 1]]}
elif len(lst) % 2 != 0:
num = (len(lst) + 1) / 2
median = {"median": lst[num - 1], "position": num}
return median
else:
raise ValueError("Inappropriate List") | true |
33487b5cd6e069e72cbe686724143ba1eb16979e | Tayuba/AI_Engineering | /AI Study Note/List.py | 1,895 | 4.21875 | 4 | # original list
a = [1, 2, 3, 4, "m", 6]
b = ["a", "b", "c", "d", 2, 9, 10]
# append(), add an item to the end of already existing list
c = 8
a.append(c) # interger append
print(a) # [1, 2, 3, 4, 'm', 6, 8]
d = "Ayuba"
b.append(d)
print(b) # ['a', 'b', 'c', 'd', 2, 9, 10, 'Ayuba']
# extend(), add all items to the to end of already existing list
a.extend(b)
print(a) # [1, 2, 3, 4, 'm', 6, 8, 'a', 'b', 'c', 'd', 2, 9, 10, 'Ayuba']
# insert(), insert an item at the a given position, first argument is the index and second argument is what is what to be inserted
first_names = ["ayuba", "zsuzsanna"]
first_names.insert(1, "tahiru")
first_names.insert(2, "imri")
print(first_names) # ['ayuba', 'tahiru', 'imri', 'zsuzsanna']
# remove(x), removes the first item from the list whose values is equal to the "x". raise ValueError if no such item
first_names.remove("ayuba")
print(first_names) # ['tahiru', 'imri', 'zsuzsanna']
# pop([i]), removes the item at the given position in the list, if no position is given, it removes and return the last item
index_zero_pop = first_names.pop(0)
print(index_zero_pop) # tahiru
no_index_pop = first_names.pop()
print(no_index_pop) # zsuzsanna
# clear(), remove all item from the list. equivalent to del a[:]
a.clear()
print(a) # []
del b[:]
print(b) # []
# index(x[,start[,end]]), return zero_base index in the list of the first item whose value is equal to x, Raise a ValueError if there is no such item
b = ["w", "a", "b", "c", "d","d", 2, 9, 10, 10]
indexed_value = b.index(2)
print(indexed_value) # 6
# count(x), returns the number of times x appears in a list
count_value = b.count("d")
print(count_value) # 2
c = ["w", "a", "b", "c", "d","d", "z", "q", "l"]
c.sort()
print(c) # ['a', 'b', 'c', 'd', 'd', 'l', 'q', 'w', 'z']
# reverse(), reverse the element of the list
c.reverse()
print(c) # ['z', 'w', 'q', 'l', 'd', 'd', 'c', 'b', 'a'] | true |
4f340717ec34d4d1ee5dc79b1bcac29c8be02600 | OliverMathias/University_Class_Assignments | /Python-Projects-master/Assignments/Celsius.py | 367 | 4.3125 | 4 | '''
A script that converts a user's celsius input into farenheight by using
the formula and prints out an temp in farenheight
'''
#gets user's temp Input
temp_c = float(input("Please enter the current temperature in celsius: "))
# turns it into farenheight
temp_f = temp_c*(9/5) + 32
#prints out farenheight
print("The current temp in farenheight is "+str(temp_f))
| true |
10ea306fedbee3cff2ce63c97add2561c9f2b54a | mbkhan721/PycharmProjects | /RecursionFolder/Practice6.py | 2,445 | 4.40625 | 4 | """ Muhammad Khan
1. Write a program that recursively counts down from n.
a) Create a recursive function named countdown that accepts an
integer n, and progressively decrements and outputs the value of n.
b) Test your function with a few values for n."""
def countdown(n): # def recursive_function(parameters)
if n <= 0: # countdown stops at 1 since the parameter is 0
return n # return base_case_value
else:
print(n)
countdown(n - 1) # countdown decrements by 1
countdown(5)
print()
""" 2. Write a function called numEven that returns the number of even
digits in a positive integer parameter.
For example, a program that uses the function numEven follows.
print(numEven(23)) # prints 1
print(numEven(1212)) # prints 2
print(numEven(777)) # prints 0 """
def numEven(n): # defining numEven Function
even_count = 0 # making initial count=0
while (n > 0): # checking input number greater than 0 or not
rem = n % 10 #slashing up inputted number into digits
if (rem % 2 == 0): #verifing digit is even or odd by dividing with 2.if remainder=0 then digit is even
even_count += 1 #counting the even digits
n = int(n / 10)
print(even_count) #printing the even number count
if (even_count % 2 == 0): #exits the function
return 1
else:
return 0
numEven(23)
numEven(1212)
numEven(777)
print()
""" 3. Write a function called lastEven that returns the last even digit
in a positive integer parameter. It should return 0 if there are no
even digits.
For example, a program that uses the function lastEven follows.
print(lastEven(23)) # prints 2
print(lastEven(1214)) # prints 4
print(lastEven(777)) # prints 0 """
def lastEven(x):
if x == 0:
return 0
remainder = x % 10
if remainder % 2 == 1:
return lastEven(x // 10)
if remainder % 2 == 0:
return remainder + lastEven(x // 10)
print(lastEven(23))
print(lastEven(1212))
print(lastEven(777))
print()
class Vehicle:
def __init__(self, t ="unknown"):
self.type = t
def print(self):
print("type =", self.type)
x1 = Vehicle()
x1.print()
x2 = Vehicle("abcde")
x2.print()
print()
class Car(Vehicle):
def __init__(self, name="Unknown"):
#super().__init__()
self.name = name
self.type = "Car"
def print(self):
print(self.type, self.name)
x1 = Car()
x1.print()
x2 = Car("Audi")
x2.print()
print()
| true |
3a21120c6e8e9814b6dad06431ec73beaeee9ff2 | Roha123611/activity-sheet2 | /prog15.py | 366 | 4.1875 | 4 | #prog15
#t.taken
from fractions import Fraction
def addfraction(st_value,it_value):
sum=0
for i in range(st_value,it_value):
sum=sum+Fraction(1,i)
print('the sum of fractions is:',sum)
return
st_value=int(input('input starting value of series:'))
it_value=int(input('enter ending value of series'))
addfraction(st_value,it_value)
| true |
4a917541eaf35c7e398ec8a4bb6acd1774541c9e | helgurd/Easy-solve-and-Learn-python- | /differBetw_ARR_LIST.py | 978 | 4.4375 | 4 | # first of all before we get into Python lists are not arrays, arrays are two separate things and it is a common mistakes that people think that lists are the same arrays.
#in array if we append different data type will return typeerror which that is not case in the list.
# ARRAY!=LIST
###example 1 python list
import array
#LIST....................................
aList= [1,2,'monkey' ]
print(aList)
#Appending to the LIST.
bList= [1,2,3,5,6,7,8,'limon' ]
bList.append('Name')
print(bList,end='')
print('')
#extra list, in this exersice the program only print the numbers that can be devided by 2:
bList= [1,2,3,5,6,7,8 ]
for x in bList:
if x % 2==0:
print([x],end='')
print(' ')
#ARRAY...................................
num= array.array('i',[1,2,3,4])
num.append(5)
print(num)
#### this code will not work as we add a different data type to the arry which it is string monkey.
# num= array.array('i',[1,2,3,4])
# num.append('monkey')
# print(num) | true |
bfa347e6247121c5cd10b86b7769eb368d5ae487 | helgurd/Easy-solve-and-Learn-python- | /open_and_read _string.py | 1,310 | 4.6875 | 5 | #write a program in python to read from file and used more than method.
# read from file --------------------------------------------------------------------
#write a program in python to read from file and used more than method.
# method1
# f=open('str_print.txt','r')
# f.close()
#---------
# method2 called context manager where we use (With and as) and in this method we don't need to write close() method.
with open('str_print.txt', 'r') as f:
f_contents = f.read()
print (f_contents)
#print in format -------------------------------------------------------
# Write a Python program to print the following string in a specific format (see the output). Go to the editor
# Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are"
# Output :
# Twinkle, twinkle, little star,
# How I wonder what you are!
# Up above the world so high,
# Like a diamond in the sky.
# Twinkle, twinkle, little star,
# How I wonder what you are.add()
f='Twinkle, twinkle,\n little star,\n How I wonder what you are!\n Up above the world so high,\n Like a diamond in the sky.\n Twinkle, twinkle, little star,\n How I wonder what you are'
print (f)
| true |
75964cfe90c20dbed87347908b79b899f45b593a | sachi-jain15/python-project-1 | /main.py | 1,206 | 4.1875 | 4 | # MAIN FILE
def output(): #Function to take user's choice
print "\nWhich script you want to run??\n Press 1 for students_to_teacher\n Press 2 for battleship\n Press 3 for exam_stats"
choice=int(raw_input('Your choice: ')) # To take users input of their choice
if (choice==1):
print "\n STUDENTS_TO_TEACHER\n"
import students_to_teacher # It will import the code written in students_to_teacher.py
elif (choice==2):
print "\n BATTLESHIP\n"
import battleship # It will import the code written in battleship.py
elif (choice==3):
print "\n EXAM STATISTICS\n"
import exam_stats # It will import the code written in exam_stats.py
else:
print # To print blank line
print "Invalid choice" # To inform user that he/she has entered a wrong number
output() #Function call to start the program
print "\n If you want to continue to run any script once again type yes" # To ask user one more time whether he want to run the code again or not
user_input=raw_input().lower() # This statement will take the input in lower case
if(user_input=='yes' or user_input=='y'):
output() #Function Call
print "\n END"
| true |
91e7da83b03fe16d65782809e07e397a41aabb72 | TheNathanHernandez/PythonStatements | /Unit 2 - Introductory Python/A1/Comments_Outputs_Errors.py | 1,379 | 4.65625 | 5 | print('Welcome to Python!')
# Output: Welcome to Python
# Why: String says "Welcome to Python
print(1+1)
# Output: 2
# Why: Math sum / 1 + 1 = 2
# print(This will produce an error)
# Output: This will produce an Error
# Why: The text doesn't have a string, it's invalid
print(5+5-2)
# Output: 8
# Why: 5 + 5 - 2
print(3*3+1)
# Output: 10
# Why: 3 x 3 + 1
print(10+3*2)
# Output: 16
# Why: 10 + 3 x 2
print((10 + 3) *2)
# Output: 26
# Why: 10 + 3 x 2
print(10/5)
# Output: 2
# Why: 10 divided by 5
print(5<6)
# Output: True
# Why: 6 is greater than 5. So, the Boolean statement is true.
print(5>6)
# Output: False
# Why: 5 is not over 6. So, the Boolean statement is false.
print(3==3)
# Output: True
# Why: 3 is the same as 3. So, the Boolean statement is true.
print(3==4)
# Output: False
# Why: 3 is not the same as 4. So, the Boolean statement is false.
print(4!=4)
# Output: False
# Why: != < means not equal. But 4 is equal to 4. So, the Boolean statement is false.
print("The secret number is", 23)
# Output: The secret number is 23
# Why: The print statement said it in a string with a number.
print("The secret number is",23)
# Output: The secret number is 23
# Why: The print statement said it in a string with a number.
print("The sum is ",(5+2))
# Output: The sum is 7
# Why: "The sum is" after that, a mathematical statement was added. Which equalled 7.
| true |
bbed8da2e0837f77df6ae36a03ef73ac25e172fd | TheNathanHernandez/PythonStatements | /Unit 2 - Introductory Python/A4 - Conditional Expressions/programOne.py | 403 | 4.15625 | 4 | # Program One - Write a number that asks the user to enter a number between 1 and 5. The program should output the number in words.
# Code: Nathan Hernandez
from ess import ask
number = ask("Choose a number between 1 and 5.")
if number == 1:
print("One.")
if number == 2:
print("Two.")
if number == 3:
print("Three.")
if number == 4:
print("Four.")
if number == 5:
print("Five.")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.