blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
030d32c1d9e1f809046976a7e1bb2aea87736aed | NixonRosario/crytography-using-Fernet | /main.py | 2,419 | 4.21875 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from cryptography.fernet import Fernet # install cryptography and import Fernet
key = Fernet.generate_key() # generates random keys
file = open('keys.txt', 'a+')
file.write("keys:- " + str(key) + "\n") # converting bytes to string and store it in a file
file.close()
def cipher():
obj = Fernet(key) # the generated key is stored in variable obj
user = input('Enter the encrypted: ') .encode() # .encode() is used to convert string to bytes
encrypted = obj.encrypt(user) # .encrypt() is used to encrypt the text
file = open('keys.txt', 'a+')
file.write("Value:- " + str(encrypted) + "\n") # encrypted text is stored
file.close()
print('Encrypted data:- ', encrypted)
n = input('If you want to decrypt select (y/n):- ') # if y is enterd decryption will take place
if n == 'y':
decrypted = obj.decrypt(encrypted)
utf = decrypted.decode('utf-8') # .decode() is used to convert bytes to text
print("Decrypted msg:- ", utf)
else:
print("Thank You!!")
def all_files():
obj = Fernet(key) # the generated key is stored in variable obj
file = open('key.txt', 'a+')
file.write("KEYS:- " + str(key) + "\n") # key generated gets stored
file.close()
path = input('Enter the path for encryption- ') # path of the file is given
print("Path of the file", path)
img = open(path, "rb")
img1 = img.read() # reads the file which is in the path
img.close()
encrypted = obj.encrypt(img1) # encrypts the image
en = open(path, 'wb')
en.write(encrypted) # returns the encryped file while opening the file
en.close()
print("Encrypted!!")
n = input('Do you want to decrypt (y/n):- ')
if n == 'y':
en_file = open(path, "rb")
encrypted = en_file.read() # reads the encrypted file
en_file.close()
decrypted = obj.decrypt(encrypted) # decrypts the encrypted file
de = open(path, 'wb')
de.write(decrypted) # returns the actual file
de.close()
print("Decrypted!!")
else:
print("Thank you!!")
cipher() # fuction call is made
all_files()
| true |
ec823e35ba2387cca400cea55d8916034f0123d1 | RayWLMo/Eng_89_Python_Collections | /dict_sets.py | 2,064 | 4.8125 | 5 | # Dictionaries and Sets are both data collections in Python
# Dictionaries
# Dict are another way to manage data but can be a little more Dynamic\
# Dict work as a KEY AND VALUE
# KEY = THE REFERENCE OF THE OBJECT
# VALUE + WHAT THE DATA STORAGE MECHANISM YOU WISH TO USE
# Dynamic as it we have Lists, and another dict inside a dict
# Syntax of dicts - dict_name = {}
# we use {} brackets to declare a Dict
# key
student_1 = {
"name": "James",
"stream": "DevOps",
"completed_lessons": 4,
"completed_lessons_names": ["data types", "git and github", "operators", "Lists and Tuples"]
} # Indexing 0 1 2 3
# Let's check if we have got the syntax right and print the dict
print(student_1)
print(type(student_1))
# Finding which value applies to which key
print(student_1["stream"])
# Printing the second last item from completed_lesson_names list
print(student_1["completed_lessons_names"][-2])
# Or alternatively
print(student_1["completed_lessons_names"][2])
# Could we apply CRUD on a dict?
student_1["completed_lessons"] = 3
print(student_1["completed_lessons"])
# Removing an item from completed_lesson_names
student_1["completed_lessons_names"].remove("operators")
print(student_1["completed_lessons_names"])
# Built-In Methods to use with dict
# To print all the keys - keys()
print(student_1.keys())
# To print all the values only - values()
print(student_1.values())
# Set are also Data collection
# Syntax - set_name = ["", "", ""]
# What is the difference between sets and dict
# Sets are unordered - no indexing
shopping_list = {"eggs", "milk", "tea"}
# 0 1 2
print(shopping_list)
car_parts = {"Engine", "Wheels", "Windows"}
print(car_parts)
# Adding items to a set
car_parts.add("Seats")
print(car_parts)
# Removing items to a set
car_parts.discard("Wheels")
print(car_parts)
# Python also has frozen sets
# Syntax - name = value([1, 2, ""])
planets = (["Mercury", "Saturn", "Neptune"])
print(planets)
| true |
374a8d5bbe59f30f7d8b1a6b9f02c9be92120e91 | group1BSE1/BSE-2021 | /src/chapter5/exercise2.py | 292 | 4.15625 | 4 | largest = None
smallest = None
while True:
num = input('Enter a number: ')
if num =='done':
break
elif largest is None or num > largest:
largest = num
elif smallest is None or num < num:
smallest = num
print('maximum',largest)
print('minimum',smallest) | true |
9250e0bab7e1c634b3aa416c66bce8cddd5ec048 | timurkurbanov/firstPythonCode | /firstEx.py | 463 | 4.46875 | 4 |
# Remember, we get a string from raw_input, but we need an int to compare it
weather = int(25);
# if the weather is greater than or equal to 25 degrees
if weather >= 25:
print("Go to the beach!")
# the weather is less than 25 degrees AND greater than 15 degrees
elif weather < 25 and weather > 15:
print("Go home!")
# Still warm enough for ice cream!
else:
print('wear a sweater and dream of beaches')
# Wear a sweater and dream of beaches.
| true |
7bc262beb842765e249819a987fd68c68f3bd0b1 | MTaylorfullStack/flex_lesson_transition | /jan_python/week_one/playground.py | 1,191 | 4.15625 | 4 | print("Hello World")
## Data Types
## String
collection_of_characters="hrwajfaiugh5uq34ht834tgu89398ht4gh0q4tn"
collection_of_characters+="!!!!!!!!!!!!!"
name="Adam"
stack="Python"
# print(f"The student {name} is in the {stack} stack")
## Numbers
## Operators: +, -, /, *, %
ten=10
one_hundred=100
# print(one_hundred-ten)
## Lists
students = ['Vineet', 'Adam', 'Cameron', 'Roxanne']
# print(students[2])
# print(students.length)
# help(list)
# students.pop()
# print(students)
# students.append("Roxanne")
# print(students)
## Dictionaries
player = {'first_name': 'Michael', 'last_name' : 'Jordan'}
# print(students[0]['first_name'])
## Conditionals and Loops
# if(bird['feathers']=='blue'){
# console.log("it is a blue bird")
# }
# if bird['feathers']=='blue':
# print("it is a blue bird")
# elif bird['feathers']=='red':
# print("It is a red bird")
# else:
# print("it is not a red or a blue bird")
## Loops
my_list=[1,2,3,4,5,6,7,8]
for i in range(len(my_list)):
print(my_list[i])
bird={
'feathers':"blue",
'wings':'2',
'name':"floppy",
'friends':["Tom", "Tweety", "Woodie"]
}
for thing in bird:
print(thing, bird[thing]) | true |
6a0b6f550fbd00cf80b035789b7364626d2b55d1 | wesleyhooker/assign1 | /ccpin.py | 1,355 | 4.40625 | 4 | #!/usr/bin/env python3
"""
Validates that the user enteres the correct PIN number
"""
def valid_input(input):
"""
Checks for valid PIN Number
Argument:
input = the users inputted PIN
Returns:
Any Errors with the input
TRUE if it passes, False if it doenst
"""
if(len(input) != 4):
print("Invalid PIN length. Correct format is: <9876>")
return False
elif(not input.isdigit()):
print("Invalid PIN character. Correct format is: <9876>")
return False
elif(input != "1234"):
print("Your PIN is incorrect")
return False
elif(input == "1234"):
print("Your PIN is correct")
return True
def main():
"""
Tests the valid_Input() function to make sure that the user entered pin
is corrrect
If user enters wrong pin 3x they are blocked from the account
If they enter correct it is accepted
Exit 0 if correct PIN
Exit 1 if Incorrect PIN 3x
"""
i = 0
while (i !=3): #allow input for 3 tries
userInput = input("Enter your PIN: ")
if(valid_input(userInput)):
exit(0)
else:
i = i + 1 #incriment i
if (i == 3): #after 3 tries, block account.
print("Your bank card is blocked")
exit(1)
if __name__ == "__main__":
main()
exit(0)
| true |
384cb75137c4702da88da4a227e2af8c72f3a0a8 | jeffvswanson/DataStructuresAndAlgorithms | /Stanford/10_BinarySearchTrees/red_black_node.py | 2,069 | 4.25 | 4 | # red_black_node.py
class Node:
"""
A class used to represent a Node in a red-black search tree.
Attributes:
key: The key is the value the node shall be sorted on. The key can be an integer,
float, string, anything capable of being sorted.
instances (int): The number of times the key for a node was inserted into the tree.
parent (node): The pointer to the parent of the node.
left (node): The pointer to the left child node.
right (node): The pointer to the right child node.
is_red (bool): The color attribute keeps track of whether a node is red or black.
"""
def __init__(self, key):
"""
Parameters:
key: The key is the value the node shall be sorted on. The key can be an integer,
float, string, anything capable of being sorted.
"""
self.key = key
self.instances = 1
self.parent = None
self.left = None
self.right = None
self.is_red = True
def recolor(self):
"""
Switches the color of a Node from red to black or black to red.
"""
if self.is_red:
self.is_red = False
else:
self.is_red = True
def add_instance(self):
"""
Allows for duplicates in a node by making it "fat" instead of
creating more nodes which would defeat the purpose of a self-
balancing tree.
"""
self.instances += 1
def remove_instance(self):
"""
Allows for removal of a single instance of a key from the
search tree rather than pruning an entire node from the tree.
"""
self.instances -= 1
def delete(self):
"""
Zeroes out a node for deletion.
"""
self.key = None
self.instances = 0
self.parent = None
self.left = None
self.right = None
self.is_red = False # Null nodes are, by default, black. | true |
2c6883f73522c971670cae797200f454968a635f | Neeragrover/HW04 | /HW04_ex00.py | 1,265 | 4.21875 | 4 | #!/usr/bin/env python
# HW04_ex00
# Create a program that does the following:
# - creates a random integer from 1 - 25
# - asks the user to guess what the number is
# - validates input is a number
# - tells the user if they guess correctly
# - if not: tells them too high/low
# - only lets the user guess five times
# - then ends the program
################################################################################
# Imports
import random
# Body
################################################################################
def main():
print("Hello World!") # Remove this and replace with your function calls
turn=0
x=random.randint(1,25)
try:
while(turn<5):
input_num=raw_input('enter a number:')
input_num_int=int(input_num)
if(input_num_int==x):
print "Congratulations, you got it!"
break
elif (input_num_int<x):
print "Too Low, please guess again!"
turn=turn+1
elif (input_num_int>x):
print "Too High,please guess again!"
turn=turn+1
else:
print 'random'
if turn==5:
print "Sorry, you ran out of turns. Please start over to guess again!!"
except:
print "Only numbers please, start over buddy!"
if __name__ == '__main__':
main() | true |
3ec08d9e5985e5ab19eae234835ae990bd31d8ac | lamngockhuong/python-guides | /basic/dictionaries/dictionaries-1.py | 1,106 | 4.46875 | 4 | # https://www.w3schools.com/python/python_dictionaries.asp
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
x = thisdict["model"]
print(x)
y = thisdict.get("model")
print(y)
# Change values
thisdict["year"] = 2019
print(thisdict)
# Return values of a dictionary
for x in thisdict:
print(thisdict[x])
# Return values of a dictionary
for x in thisdict.values():
print(x)
# Loop through both keys and values
for x, y in thisdict.items():
print(x, y)
# Check if key exists
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
# return dict length
print(len(thisdict))
# add items
thisdict["color"] = "red"
print(thisdict)
# remove items
thisdict.pop("model")
print(thisdict)
# remove last inserted item (in versions before 3.7, a random item is removed instead):
thisdict.popitem()
print(thisdict)
# del
# del thisdict["model"]
# print(thisdict)
#
# del thisdict
# print(thisdict)
# clear
thisdict.clear()
print(thisdict)
thisdict = dict(brand="Ford", model="Mustang", year=1964)
print(thisdict)
| true |
524b7612faa6b189b228d9f8e6aca0f69fbf6364 | lamngockhuong/python-guides | /basic/strings/strings-2.py | 497 | 4.375 | 4 | # https://www.w3schools.com/python/python_strings.asp
x = "Hello, world!"
print(x[2:5])
y = " Hello world "
print(y.strip()) # remove any whitespace from the beginning or the end
print(len(y)) # return the length of a string
print(y.lower()) # return the string in lower case
print(y.upper()) # return the strung in upper case
print(y.replace("H", "J")) # replace a string with another string
print(x.split(",")) # return list that splits the string into substrings
print(x is not y)
| true |
de9b2cef5eea479083e2932d8291e8ba6a4188bf | kisa411/CSE20211 | /isPalindrom.py | 476 | 4.15625 | 4 |
word = raw_input("Enter a word:")
list = []
start = 0
end = len(word) - 1
def isPalindrome(word):
global start
global end
for letter in word:
list.append(letter)
while (start < end):
if list[start] != list[end]:
return False
else:
return True
start+=1
end-=1
if isPalindrome(word) == True:
print "Is palindrome.\n"
else:
print "Is not a palindrome.\n"
isPalindrome(word) | true |
b0f26fc98716307747c63e4bbc3921dd660ac6b1 | waddahAldrobi/RatebTut- | /Python Algs copy/print bst by level.py | 504 | 4.125 | 4 | def print_bst(tree):
current_level = [tree.root]
while current_level:
next_level = []
for node in current_level:
print(node.value,end='')
# Logic to start building the next level
##Added
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
####
print() # Print a newline between levels
current_level = next_level
| true |
8fc3791795ba4f7be4da91cf325c64d2a3810572 | alexnicolescu/Python-Practice | /lambda/ex1.py | 289 | 4.1875 | 4 | # Write a Python program to create a lambda function that adds 15 to a given number passed in as an argument, also create a lambda function that multiplies argument x with argument y and print the result.
def l1(x): return x + 15
def l2(x, y): return print(x*y)
print(l1(15))
l2(12, 10)
| true |
c82870abca988247ab2a07c841550bf1e57d36b8 | Adamrathjen/MOD1 | /Module1.py | 1,073 | 4.125 | 4 | import os
print("Character Creator!")
selected = 1
while "4" != selected:
print("Make new Character: 1")
print("Delete character: 2")
print("See current characters: 3")
print("Quit: 4")
selected = input("Make your selection: ")
if selected == "1":
print("you selected 1")
characterName = input("Enter a character name: ")
f = open(characterName, "x")
print("make character and create character file function call")
elif selected == "2":
print("you selected 2")
filename = input("Enter the name of the character to delete or enter n to stop: ")
if filename != "n":
if os.path.exists(filename):
os.remove(filename)
else:
print("The file does not exist")
else: continue
elif selected == "3":
print("you selected 3")
print("function call to display list of created characters")
elif selected == "4":
print("you quit")
else:
print("that isn't an option")
print("you got out") | true |
7b67bdcd6f6dfef936e27507d5b5390562475359 | sohinipattanayak/Fundamentals_Of_Python | /p2_palindrome_num.py | 638 | 4.21875 | 4 | #Check if num is plaindrome
num=int(input("Enter the number: "))
num_str=str(num) #Type-casting the number to String
flag=0
#No need to iterate throught the whole of string
#Just iterate till the half of the string
#If the last two match it is automatically a reverse
for i in range(len(num_str)//2): #halfing the list
if num_str[i]!=num_str[len(num_str)-i-1]:
flag=1 #Check till that point till it is not equal
break #As soon as u reach that point break & get out
if flag==1:
print("Not a Plaindrome")
else:
print("Palindrome") #It could be a plaindrome because the above iteration could occur successfully
| true |
a94426f5e57d3027080f43255a23b785fc829bae | alaamarashdeh92/CA06---More-about-Functions-Scope | /P3.py | 2,132 | 4.375 | 4 | # Shopping List
# Your shopping list should keep asking for new items until nothing is entered (no input followed by enter/return key).
# The program should then print a menu for the user to choose one of the following options:
# (A)dd - To add a new item to the list.
# (F)ind - To search for an item in the list.
# (P)rint - To pretty print the list.
# (S)ort - To sort the list.
# (C)lear - To clear all items in the list.
# (Q)uit - To exit your program.
# TODO: Define a data structure to keep track of your shopping list.
# TODO: Implement a function to show the menu to the user, then wait for a valid user choice.
def add_item(item):
shopping_list.append(item)
#Implement a function to find an item in your shopping list.
def find_item(item):
if item in shopping_list:
print("the item was found ")
else:
print("the items is not in the list ")
#implement a function to pretty print your tabbed lits.
def print_list():
print("the items in the list are ")
print(shopping_list, end ="/t")
# function to sort print your tabbed lits.
def sort_list():
shopping_list.sort()
print (f"the sorted shopping list is {shopping_list}")
#Implement a function to pretty print your tabbed lits.
def clear_list():
shopping_list.clear()
#Implement a function which calls the exit() function.
def quit():
print("Goodbye! Hope to see you again soon :).")
shopping_list=[]
def show_menu():
print(f"this is the menu{shopping_list}")
print ("""chose one of the following options
Add - To add a new item to the list.
Find - To search for an item in the list.
Print - To pretty print the list.
Sort - To sort the list.
Clear - To clear all items in the list.
Quit - To exit your program.
""")
str=input("your choice is :")
if str=="Add" :
item=input("enter the item you want to add ")
add_item(item)
elif str=="find":
item=input("what are you looking for ")
find_item(item)
elif str=="print":
print_list()
elif str=="sort":
sort_list()
elif str=="clear":
clear_list() | true |
d6482340a7a0125c28ac00e22c30974bb3edf79d | riteshsharma29/Python_data_extraction | /ex_2.py | 501 | 4.28125 | 4 | #!/usr/bin/python
# coding: utf-8 -*-
#This example shows reading a dataset using csv reader
import csv
#creating an empty list
MonthlySales = []
with open('data/MonthlySales.csv', 'r') as f:
reader = csv.DictReader(f)
for row in reader:
MonthlySales.append(row)
for a in MonthlySales:
print a
#print keys
for a in MonthlySales:
print a.keys()
#print keys and values
for a in MonthlySales:
for key, value in a.items():
print key + ": ", value
print '\n'
| true |
6a296745a5d413d0f2c23635425fba1e751d1af1 | DanielOjo/Iteration | /Classroom exercises/Development/Iteration Class Exercise (Development Part 2).py | 347 | 4.21875 | 4 | #DanielOgunlana
#31-10-2014
#Iteration Class Exercise (Development Part 2)
number_stars = int(input("How many stars do you want on each row:"))
number_display = int(input("How many times would you like this to display?:"))
stars_printed = "*"
for stars in range(1,number_display+1):
print(stars_printed*number_stars)
| true |
d223031deac627cd02f4c4cb223534b185b07579 | asterane/python-exercises | /other/friend/Multiplication Tables.py | 204 | 4.21875 | 4 | print("What multiplication table would you like? ")
i = input()
print("Here's your table: ")
for j in range(11):
print(i, " x ", j, "=", i * j)
# The code above creates the table... I hope. #
| true |
a0208582f00a6f392e80905246e296dd45e843ca | b-ark/lesson_4 | /Task3.py | 820 | 4.375 | 4 | # Create a program that reads an input string and then creates and prints 5 random strings
# from characters of the input string.
# For example, the program obtained the word ‘hello’, so it should print 5 random strings(words)
# that combine characters ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ -> ‘hlelo’, ‘olelh’, ‘loleh’ …
# Tips: Use random module to get random char from string)
from random import shuffle, sample
# 1 способ
answer = input('Type in your string: ')
string_list = list(answer)
counter = 0
while counter != 5:
shuffle(string_list)
print(''.join(string_list))
counter += 1
# 2 способ
answer = input('Type in your string: ')
string_list = list(answer)
counter = 0
while counter != 5:
print(''.join(sample(string_list, len(answer))))
counter += 1
| true |
14a4b02855d5b08a9a4c3b2eb8ee8e69474fed12 | Atularyan/Letsupgrade-Assignment | /Day_3_Assignment/Day_3(Question2).py | 338 | 4.25 | 4 | """
Question 2
Define a function swap that should swap two values and print the swapped variables outside the
swap function.
"""
def swap(n):
rev=0
while(n>0):
rem=n%10
rev=(rev*10)+rem
n=n//10
return (rev+n)
n=int(input("Enter the number = "))
res=swap(n)
print("swapped value = ",res) | true |
e47a5b27a63194e1a59814f5ce3d9d5fe1f0c5cc | vijay-Jonathan/Python_Training | /bin/44_classes_static_methods.py | 2,156 | 4.15625 | 4 | """
Client Requiremnt is :for 43rd example, add method to compute percentage,
if student pass marks, method should return percentage.
Now,
for this compute_percentage method, not required to pass instance object OR
class object, only passing 2 marks is enough method will return perecnetage.
Other methods inside the class is receiving either instance object/class object,
because, in those methods we are either storing some values inside the object/
reading varaible values from the object
But,
In this case, we dont need class/instance object. Uncessarily if we pass
any object to method, it will also occupy memory.
In this case we can write method wchi will not take any instance/class method as
first argument
i.e : STATIC METHODS
"""
class Student:
college = "Xyz College"
def __init__(self,n,s1,s2):
self.name = n
self.sub1_marks = s1
self.sub2_marks = s2
@classmethod
def add_college_rank(cls,r):
cls.college_rank = r
@staticmethod
def compute_percentage(marks1,marks2):
return ((marks1+marks2)/200)*100
Student1 = Student("Student-1",70,80)
Student2 = Student("Student-2",80,90)
avg_sub1_marks = (Student1.sub1_marks + Student2.sub1_marks)/2
avg_sub2_marks = (Student1.sub2_marks + Student2.sub2_marks)/2
total_sub1_marks = Student1.sub1_marks + Student2.sub1_marks
total_sub2_marks = Student1.sub2_marks + Student2.sub2_marks
total_marks = Student1.sub1_marks + Student2.sub1_marks + Student1.sub2_marks + Student2.sub2_marks
print(" Student_1_name : ",Student1.name)
print(" Student_2_name : ",Student2.name)
print(" Student_1_College : ",Student.college)
print(" Student_2_College : ",Student.college)
print("avg_sub1_marks : ",avg_sub1_marks)
print("avg_sub2_marks : ",avg_sub2_marks)
print("total_sub1_marks : ",total_sub1_marks)
print("total_sub2_marks : ",total_sub2_marks)
print("total_marks : ",total_marks)
Student.add_college_rank(1)
print("College Rank : ",Student.college_rank)
s1_per = Student.compute_percentage(Student1.sub1_marks,Student1.sub2_marks)
print("Student 1 Percentage : ",s1_per)
print("-"*40)
#------------------------------------
| true |
f14ac23d41d53f6cb09d94da5facd833aa3bb7f6 | vijay-Jonathan/Python_Training | /bin/2_core_datatypes.py | 1,842 | 4.25 | 4 | """
CORE DATA TYPES :
Similar to other languages, in python also we ALREADY have SOME options to store SOME kind of data.
In that,
1. int,float,hex,bin classes : ALREADY have option to store numbers like int, float, hex, bin, oct etc
2. str class : ALREADY have option to store Strings like "My Name", "My Addess" etc
3. list class : ALREADY have option to store collection of elements like list of students : After creating list,we CAN alter throught the program
4. tuple class : ALREADY have option to store collection of elements like list of students : After creating tuple,we CAN'T alter throught the program
5. dict class : ALREADY have option to store collection of elements like list of students : After creating dictionary,we CAN alter throught the program
Why we need dictionary when we already have list?
Answer :
a) dict class help us to provide OWN index called key
b) dict class help us to store json data
c) dict class help us to store no-sql database data
6. set class : ALREADY have option to store collection of elements like list of students : After creating set, we CAN alter throught the program
Why we need set when we already have list/dict?
Answer:
a) set class help us to store/keep unique elements
b) set class help us to perform sets and unions operations like union, intersection, difference etc
7. frozenset class : ALREADY have option to store collection of elements like list of students : After creating frozenset, we CAN'T alter throught the program
And Many More Classes are available, we will discuss throughout the course
Summary:
IMMUTABLE (We CAN'T modify)
-------------------------
1. number classes like int,float,hex,bin,oct etc
2. str class
3. tuple class
4. frozenset class
MUTABLE (We CAN modify)
1. list
2. dict
3. set
"""
| true |
ba07cec6d0f3f8f0131b8ac1680314dedb04dd89 | dmonzonis/advent-of-code-2019 | /day3/day3.py | 2,192 | 4.28125 | 4 | def compute_path(path):
"""Return a set with all the visited positions in (x, y) form"""
current = [0, 0]
visited = {}
total_steps = 0
for move in path:
if move[0] == 'U':
pos = 1
multiplier = 1
elif move[0] == 'D':
pos = 1
multiplier = -1
elif move[0] == 'R':
pos = 0
multiplier = 1
else: # 'L'
pos = 0
multiplier = -1
steps = int(move[1:])
for _ in range(1, steps + 1):
current[pos] += multiplier
total_steps += 1
current_tuple = tuple(current)
if current_tuple not in visited:
visited[current_tuple] = total_steps
return visited
def manhattan_distance(point1, point2):
return abs(point1[0] - point2[0]) + abs(point1[1] - point2[1])
def find_intersections(path1, path2):
"""Return a dictionary with the intersecting points as keys and the total steps
to reach that intersection by both paths, as given by the compute_path method"""
visited1 = compute_path(path1)
visited2 = compute_path(path2)
intersections = set(visited1.keys()).intersection(set(visited2.keys()))
result = {}
# Construct the dictionary of intersection: total steps
for point in intersections:
result[point] = visited1[point] + visited2[point]
return result
def find_closest_point(points, origin=(0, 0)):
closest = None
closest_distance = float('inf')
for point in points:
distance = manhattan_distance(point, origin)
if distance < closest_distance:
closest = point
closest_distance = distance
return closest
def main():
with open("input.txt") as f:
paths = [path.split(',') for path in f.read().splitlines()]
# Part 1
intersection_dict = find_intersections(paths[0], paths[1])
closest = find_closest_point(intersection_dict.keys())
print(manhattan_distance(closest, (0, 0)))
# Part 2
print(min(intersection_dict.values()))
if __name__ == "__main__":
main()
| true |
17baad513d548bf71b1ec6eea648fa0ca2917d7d | Ads99/python_learning | /python_crash_course/names.py | 924 | 4.15625 | 4 | name = "ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
message = "Hello, " + full_name.title() + "!"
print(message)
# whitespace demo
print("\tPython")
print("Languages:\nPython\nC\nJavaScript")
print("Languages:\n\tPython\n\tC\n\tJavaScript")
# stripping whitepace - this is best seen in a terminal session without print statements
favourite_language = 'python '
print(len(favourite_language))
print(len(favourite_language.rstrip()))
# however, note aboe that the variable is unchanged by rstrip()
# to change the variable we need to re-assign
favourite_language = favourite_language.rstrip()
print(len(favourite_language))
message = "One of Python's strengths is its diverse community"
print(message)
# incorrect use of apostrophes
#message = 'One of Python's strengths is its diverse community' | true |
1eb80efb19d1ef10b0b5ef2cfe6db47a3d3dc2ff | Ads99/python_learning | /python_crash_course/_11_3_example_employee_class.py | 1,023 | 4.46875 | 4 | # Example 11.3 - Employee
# Write a class called Employee. The __init__() method should take in a first
# name, last name and an annual salary and store each of these as attributes.
# Write a method called give_raise() that adds $5000 to the annual salary by
# default but also accepts a different raise amount
class Employee():
"""Collect detauls about an employee"""
def __init__(self, f_name, l_name, salary):
"""Store a question, and prepare to store responses."""
self.f_name = f_name
self.l_name = l_name
self.salary = salary
def give_raise(self, salary_raise=0):
"""Add $5000 to the annual salary by default but also accept
another val"""
if salary_raise:
self.salary += salary_raise
else:
self.salary += 5000
def show_results(self):
"""Show all details of an employee"""
print("Employee name: " + self.f_name.title() + ' ' + self.l_name.title())
print("Salary: " + str(self.salary)) | true |
8b918360be7f45468c503e81f9c32b52e174ca17 | AdarshSubhash/C-97- | /hwpro.py | 351 | 4.15625 | 4 | number=6
guess=int(input("Guess a number between 1 to 10"))
if(guess==number):
print("You Guessed The Right Number")
elif(guess>number):
print("Try a bit lower number")
guess=int(input("Guess a number between 1 to 10"))
else :
print("Try a bit higher number")
guess=int(input("Guess a number between 1 to 10"))
| true |
bb9d7c309c187c7106e758685a02ffb1a9279c24 | sourav9064/coding-practice | /coding_10.py | 746 | 4.1875 | 4 | ##Write a code to check whether no is prime or not.
##Condition use function check() to find whether entered no is
##positive or negative ,if negative then enter the no,
##And if yes pas no as a parameter to prime()
##and check whether no is prime or not?
num = int(input())
def check(n):
if n >= 0:
a = n
return a
else:
b = n
return b
def prime(n):
if n>1:
for i in range(2,n):
if n%i == 0:
print("not prime number")
break
else:
print("prime number")
print(n)
else:
print("not prime number")
if (check(num)>=0):
prime(num)
else:
print("not prime number")
| true |
9be112de553bec1a1af362c51ecd2877e622c214 | sourav9064/coding-practice | /coding_22.py | 1,385 | 4.21875 | 4 | ##A doctor has a clinic where he serves his patients. The doctor’s consultation fees are different for different groups of patients depending on their age. If the patient’s age is below 17, fees is 200 INR. If the patient’s age is between 17 and 40, fees is 400 INR. If patient’s age is above 40, fees is 300 INR. Write a code to calculate earnings in a day for which one array/List of values representing age of patients visited on that day is passed as input.
##
##Note:
##
##Age should not be zero or less than zero or above 120
##Doctor consults a maximum of 20 patients a day
##Enter age value (press Enter without a value to stop):
##Example 1:
##
##Input
##20
##30
##40
##50
##2
##3
##14
##
##
##Output
##Total Income 2000 INR
##
##
##Note: Input and Output Format should be same as given in the above example.
##For any wrong input display INVALID INPUT
##
##Output Format
##
##Total Income <Integer> INR
age = []
for i in range(20):
p = input()
if p == "":
break
elif int(p) in range(0,120):
age.append(int(p))
else:
print("Invalid Input")
exit()
fees = 0
for i in age:
if i<17:
fees += 200
elif i<40:
fees += 400
else:
fees += 300
print("Total Income {} INR".format(fees))
| true |
f2e698e05e449961409b844e9bc4b667a2042cab | sourav9064/coding-practice | /coding_8.py | 1,058 | 4.15625 | 4 | ##The program will recieve 3 English words inputs from STDIN
##
##These three words will be read one at a time, in three separate line
##The first word should be changed like all vowels should be replaced by *
##The second word should be changed like all consonants should be replaced by @
##The third word should be changed like all char should be converted to upper case
##Then concatenate the three words and print them
##Other than these concatenated word, no other characters/string should or message should be written to STDOUT
##
##For example if you print how are you then output should be h*wa@eYOU.
##
##You can assume that input of each word will not exceed more than 5 chars
a = str(input())
b = str(input())
c = str(input())
v = ['a','e','i','o','u']
con = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
for i in a:
if i in v:
x = a.replace(i,'*')
for i in b:
if i in con:
y = b.replace(i,'@')
else:
y = b
z = c.upper()
print(x+y+z)
| true |
f39aa64260dbce9cbe7d34c12129b2427f91a2f8 | Krista-Pipho/BCH-571 | /Lab_5/Lab_5.2.py | 811 | 4.4375 | 4 | # Declares an initial list with 5 values
List1 = [1,2,3,4,5]
# Unpacks this list into 5 separate variables
a,b,c,d,e = List1
# Prints both the list and one of the unpacking variables
print(List1)
print(a)
# Changes the value of a to 6
a = 6
# Prints both the list and a, and we can see that changing a does not change the corresponding value in the list
print(a)
print(List1)
# Changes the value of one list entry to nine
List1[1] = 9
# Prints the list and the corresponding unpacking variable to show that changing the unpacking
# variable does not change the list value
print(List1)
print(b)
# We conclude that this method does not just create a variable that points to the same location in space, but rather
# fills new separately stored variables with values from the list
| true |
d9fbf08a599b0a04491081eece5292114ba12039 | hamburgcodingschool/L2CX-November | /lesson 6/dashes.py | 413 | 4.21875 | 4 | # ask the user for a word
# seperate the letters with dashes:
# ex: banana becomes b-a-n-a-n-a
def dashifyWord(word):
dashedWord = ""
firstTime = True
for letter in word:
if firstTime:
firstTime = False
else:
dashedWord += "-"
dashedWord += letter
return dashedWord
print("What's the word YO?")
userWord = input()
print(dashifyWord(userWord)) | true |
6a79b8a8424d83855aa72aefdf873be19b1a9ecd | manishg2015/python_workpsace | /python-postrgress/main.py | 1,625 | 4.25 | 4 | from sqlitedatabase import add_entry,get_entries,create_connection,create_table
menu = """ Welcome to the programming diary!
Please select one of the following options:
1) Add new entry for today.
2) View entries.
3) Exit.
Your selection:
"""
welcome = "**Welcome to the programing diary!**"
# entries = [
# {"content": "Today I started learning programing.", "date": "01-01-2020"},
# {"content": "I created my first SQLite database!", "date": "02-01-2020"},
# {"content": "I finished writing my programming diary application.", "date": "03-01-2020"},
# {"content": "Today I'm going to continue learning programming!", "date": "04-01-2020"},
# ]
def prompt_new_entry():
entry_content = input("What have you learned today? ")
entry_date = input("Enter the date: ")
add_entry(entry_content, entry_date)
def view_entries(entries):
for entry in entries:
print(f"{entry['date']}\n{entry['content']}\n\n")
# print(welcome)
# while (user_input := input(menu)) != "3":
# if user_input == "1":
# prompt_new_entry()
# elif user_input == "2":
# view_entries(get_entries())
# else:
# print("Invalid option, please try again!")
def main():
database = r"/Users/manishgarg/software/sqlite/database.db"
# create a database connection
connection = create_connection(database)
with connection:
create_table(connection)
add_entry(connection,"Learning SQLite with Python" ,"2020-06-01")
entries = get_entries(connection)
for entry in entries:
print(entry)
if __name__ == '__main__':
main()
| true |
66703e13e0e831b7472ac1d5bb3df64e0af61a59 | RobRoseKnows/umbc-cs-projects | /umbc/CMSC/2XX/201/Homeworks/hw8/hw8_part1.py | 685 | 4.4375 | 4 | # File: hw8_part1.py
# Author: Robert Rose
# Date: 11/24/15
# Section: 11
# E-mail: robrose2@umbc.edu
# Description:
# This program takes a list from user input and outputs it in reverse using
# recursion.
def main():
integers = []
number = int(input("Enter a number to append to the list, or -1 to stop: "))
while(number != -1):
integers.append(number)
number = int(input("Enter a number to append to the list, or -1 to stop: "))
print("The list as you entered it is:", integers)
rev(integers)
# Recursively prints the integers in reverse
def rev(integers):
print(integers[-1])
if(len(integers) != 1):
rev(integers[0:-1])
main()
| true |
e97487959ffb477fed5bb5dde9019144a7f6536b | RobRoseKnows/umbc-cs-projects | /umbc/CMSC/2XX/201/Homeworks/hw2/hw2.py | 2,425 | 4.34375 | 4 | # File: hw2.py
# Author: Robert Rose
# Date: 9/12/15
# Section: 11
# Email: robrose2@umbc.edu
# Description:
# This file contains mathmatical expressions as
# part of Homework 1.
print("Robert Rose")
print("Various math problem solutions as part of Homework 1.")
# Question 1:
# Expected output: 24
num1 = (7 + 1) * 3
print("Question 1 evaluates to:", num1)
# Actual output: 24
# Explanation: Parentheses first (8), then multiplication (24)
# Question 2:
# Expected output: 2
num2 = (12 % 5)
print("Question 2 evaluates to:", num2)
# Actual output: 2
# Explanation: Remainder of 12 / 5 is 2.
# Question 3:
# Expected output: 21
num3 = (21 % 49)
print("Question 3 evaluates to:", num3)
# Actual output: 21
# Explanation: 21 / 49 = 0, remainder 21.
# Question 4:
# Expected output: 2
num4 = (5 - 3) + (10 - 5) * (8 % 2)
print("Question 4 evaluates to:", num4)
# Actual output: 2
# Explanation: Parentheses first (2, 5, 0), then multiplaction (0), then
# addition (2)
# Question 5:
# Expected output: 34.0
num5 = 6.5 + 5 / 2 * (4 + 7)
print("Question 5 evaluates to:", num5)
# Actual output: 34.0
# Explanation: Parantheses first (11), then division (2.5), then
# multiplacation (27.5), then addition (34)
# Question 6:
# Expected output: 5.0
num6 = 9 / 3 + 18 - 4 * 4
print("Question 6 evaluates to:", num6)
# Actual output: 5.0
# Explanation: First division (3), then multiplication (16), then
# addition (21), then subtraction (5)
# Question 7:
# Expected output: 22
num7 = 8 % 3 + 5 * 4
print("Question 7 evaluates to:", num7)
# Actual output: 22
# Explanation: Frist multiplication (20), then mod (2), then
# addition (22)
# Question 8:
# Expected output: 79.914...
num8 = 81.3 / 2.1 + ((51.5 % 65.2) * 2 / 2.5)
print("Question 8 evaluates to:", num8)
# Actual output: 79.91428571428571
# Explanation: First parantheses (51.5), then parantheses multiplication (103),
# then parantheses division (41.2), then division (38.714...), then
# addition (79.914...)
# Question 9:
# Given equation: 100 - 8 * 8 + 1 / 0.5
# Solved equation: 100 - ((8 * 8 + 1) / 0.5)
# Target number: -30
num9 = 100 - ((8 * 8 + 1) / 0.5)
target9 = -30
print("Question 9 evaluates to:", num9, "and should be", target9)
# Question 10:
# Given equation: 84 / 10 + 11 - 4 * 4
# Solved equation: (84 / (10 + 11) - 4) * 4
# Target number: 0
num10 = (84 / (10 + 11) - 4) * 4
target10 = 0
print("Question 10 evaluates to:", num10, "and should be", target10)
| true |
120b363afdecbbc5f67640a53cad242b5c97ad01 | huangdaweiUCHICAGO/CAAP-CS | /Assignment 1/cash.py | 890 | 4.1875 | 4 | # Dawei Huang
# 07/17/2018
# CAAP Computer Science Assignment 1
# Programs for Part 1 of the assignment is contained in the file hello.py
# Programs for Part 2 of the assignment is contained in the file cash.py
# Part 2
print("Part 2: Change Program\n")
print("This program will prompt user for the amount of change and print the least possible number of coins returned")
change1 = int(float(input("Change owed: "))*100)
def leastChange(change):
coinCounter = 0
while change > 0:
if change >= 25:
coinCounter += 1
change -= 25
elif change >= 10:
coinCounter += 1
change -= 10
elif change >= 5:
coinCounter += 1
change -= 5
elif change >= 1:
coinCounter += 1
change -= 1
return coinCounter
print ("least number of coin owed: "+ str(leastChange(change1))) | true |
daabf510c6a6fd05ec5338da302af3c071c34015 | bogdanlungu/learning-python | /rename_files.py | 727 | 4.21875 | 4 | """
Renames all the files from a given directory by removing the numbers from
their names - example boston221.jpg will become boston.jpg
"""
import os
from string import digits
# define the function
def rename_files():
# get the file names from a folder
file_list = os.listdir(r"C:\Python\tmp\prank")
saved_path = os.getcwd() # get the current working directory
print("Current working directory is " + saved_path)
os.chdir(r"C:\Python\tmp\prank") # the folder that contains the files
# rename files
remove_digits = str.maketrans('', '', digits)
for file_name in file_list:
os.rename(file_name, file_name.translate(remove_digits))
os.chdir(saved_path)
rename_files()
| true |
1e38094a5fa47b540c7a5350010c74bc389ab13c | bogdanlungu/learning-python | /combinations.py | 752 | 4.46875 | 4 | """This programs computes how many combinations are possible
to be made from a collection of 'n' unique integers grouped under 'g' elements.
You need to specify the length of the collection and how many elements at a time you
want to group from the collection.
The number of possible combinations will be printed."""
# pylint: disable=C0103
from math import factorial as fac
message = "Hello! Please complete the length of the collection and the value of the group"
set_message = "The collection length is:"
group_message = "Specify the group length:"
print(message)
print(set_message)
n = int(input())
print(group_message)
g = int(input())
result = fac(n) / (fac(g) * fac(n - g))
print("The number of possible combinations is " + str(int(result)))
| true |
f59a50d4c5a1d9fdf489097819905c086ee06df5 | CoranC/Algorithms-Data-Structures | /Cracking The Coding Interview/Chapter Nine - Recursion and Dynamic Programming/9_2__xy_grid.py | 734 | 4.25 | 4 | """
Imagine a robot sitting on the upper left corner of an X by Y grid. The robot can
only move in two directions: right and down. How many possible paths are there for the robot to go
from (0,0) to (X,Y)?
"""
#Workings
"""
Grid
[
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
Answer
[
[6, 3, 1],
[3, 2, 1],
[1, 1, 0]
]
"""
def count_robot_paths_rec(grid, row, col):
if row == 0:
return 1
if col == 0:
return 1
return count_robot_paths_rec(grid, row-1, col) + count_robot_paths_rec(grid, row, col-1)
def count_robot_paths_rec(grid, row, col):
grid[row][col] = 1
if __name__ == "__main__":
the_grid = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
print count_robot_paths_rec(the_grid, 2, 2) | true |
4ef0fe0dfebb3c739f8d52ea017b78b75a4076a0 | shadman19922/Algorithm_Practice | /H_Index/h_index_sorted_array.py | 783 | 4.21875 | 4 | def compute_h_index(Input):
#Input.sort()
left = 0
right = len(Input) - 1
h_idx = -2
while left < right:
middle = (int)(left + (right - left)/2)
middle_element = Input[middle]
remaining_elements = right - middle + 1
if middle_element <= remaining_elements:
h_idx = middle_element
left = middle + 1
else:
right = middle - 1
return Input[left]
some_numbers = [2, 2, 2, 4, 4, 4, 5, 5, 5, 5, 5, 6]
#some_numbers.sort()
#print("The value of len(some_numbers) is: ", len(some_numbers))
print("Here's a sorted array \n")
for i in range(0, len(some_numbers)):
print(some_numbers[i], end = " ")
result = compute_h_index(some_numbers)
print('The h-index is: ', result)
| true |
9ec4277cb9d0f88290a5f1c7abd4815d12677a90 | mdisieno/Learning | /Python/FCC_PythonBeginner/14_ifStatements.py | 278 | 4.15625 | 4 | isMale = True
isTall = False
if isMale and isTall: #checks if either true
print("You are a tall male")
elif isMale and not(isTall):
print("You are a male")
elif not(isMale) and isTall:
print(("You are not a male, but are tall"))
else:
print("You are a female")
| true |
916e34cc0cce126412c21d0c4cb71fc640f2e73d | SaM-0777/OOP | /Strings.py | 462 | 4.3125 | 4 | ##Strings in Python
str1 = "Python is Easy"
print(str1[:])
print(str1[::])
print(str1[:3]) ##Print first 3 characters
print(str1[-2:3])
##Slicing of String in Python
s = "Computer Science"
slice_1 = slice(-1, -6, -1)
slice_2 = slice(1, 6, -1)
slice_3 = slice(0, 5, 2)
print(s[slice_1])
print(s[slice_2])
print(s[slice_3])
##Reverse string using slicing
reverse_s = s[::-1]
print(reverse_s)
s1 = "Computer"
s2 = "Science"
print(s1 * 2)
print(s1, " " + s2)
| true |
2624adf68591e885926d1a3fea74a5c4183b126d | SaM-0777/OOP | /Dictionary.py | 1,781 | 4.59375 | 5 | ##Dict is an unordered set or collection of items or objects where unique keys are mapped yhe values
##These keys are used to access the corresponding paired value. While the keys are unique, values can be common and repeated
##The data type of a value is also mutable and can change whereas, the data type of keys must be mutable such as strings, numbers or tuples
##Example 1
d = {'cat' : 'cute', 'dog' : 'furry'}
print(d['cat'])
print('cat' in d) ##Print True
d['fish'] = 'wet' ##Set an Entry in a Dict
print(d['fish'])
print(d)
print(d.get('monkey', 'N/A')) ##Get an Element with default; prints "N/A"
print(d.get('fish', 'N/A')) ##Get an Element with default; prints "N/A"
del d['fish'] ##Remove an Element from Dict
print(d.get('fish', 'N/A')) ##If fish is not in dict it will print "N/A"
print(d)
###Changing existing value
dict_list = {'name' : 'Rama', 'hobbies' : ['painting', 'singing', 'cooking']}
dict_list['name'] = 'krishna'
print("Name : ", dict_list['name'])
##Adding new Key:value
dict_list = {'name' : 'Ariel', 'hobbies' : ['painting', 'singing', 'cooking']}
dict_list['age'] = 11
print("Dict : ", dict_list)
##Deleting a key:value
del dict_list['name']
print(dict_list)
print("Hobbies : ", end = '')
for i in dict_list['hobbies']:
print(i, end = ', ')
##Predefined Dict Func
#clear(), copy(), get(), items(), fromkeys(), keys(), update(), pop(), values(), popitems()
##How Dict is diff from list ?
# A dict is a composite datatype in python which resembles a list
# List has an ordered set of objects which can iterate and can be referenced and accessed by an index number unlike a dict which is unordered and
# has a key:value pair where values are accessed by keys | true |
f0d0f136058ba7b063ff00fe6e4e9165f106d0c2 | Sjaiswal1911/PS1 | /python/Lists/methods_1.py | 1,030 | 4.25 | 4 | # LIST METHODS
# Append
# list.append(obj)
# Appends object obj to list
list1 = ['C++', 'Java', 'Python']
print("List before appending is..", list1)
list1.append('Swift')
print ("updated list : ", list1)
del list1
# Count
# list.count(obj)
# Returns count of how many times obj occurs in list
aList = [123, 'xyz', 'zara', 'abc', 123];
print ("Count for 123 : ", aList.count(123))
print ("Count for zara : ", aList.count('zara'))
# Extend
# list.extend(seq)
# Appends the contents of seq to list
list1 = ['physics', 'chemistry', 'maths']
list2 = list(range(5)) #creates list of numbers between 0-4
list1.extend(list2)
print ('Extended List :', list1)
# Index
# list.index(obj)
# Returns the lowest index of obj in the list
print ('Index of chemistry', list1.index('chemistry'))
#print ('Index of C#', list1.index('C#'))
# this produces an error
# Insert
# list.insert(index, obj)
# inserts the obj at 'index' location in list
print("Before insertion:" ,list1)
list1.insert(1, 'Biology')
print ('Final list : ', list1)
| true |
15449e1043649cf221e878405e1db4437bb74bfb | manish711/ml-python | /regression/multiple_linear_regression/multiple_linear_regression.py | 1,688 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
@author: manishnarang
Multiple Linear Regression
"""
#Importing Libraries
import numpy as np #contains mathematical tools.
import matplotlib.pyplot as plt #to help plot nice charts.
import pandas as pd #to import data sets and manage data sets.
#Importing Data Set - difference between the independent variables and the dependent variables.
dataSet = pd.read_csv('50_Startups.csv')
X = dataSet.iloc[:, :-1].values
Y = dataSet.iloc[:, -1].values
#Encode Categorical Data
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
ct = ColumnTransformer([('encoder', OneHotEncoder(), [3])], remainder='passthrough')
X = np.array(ct.fit_transform(X))
#Split the training set and test set - a test set on which we test the performance of this machine learning model and the performance on the test set shouldn't be that different from the performance on the training sets because this would mean that the machine learning models understood well the correlations and didn't learn them by heart.
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state = 0)
# Fitting Multiple Linear Regression to the training set - y = b + m0x0 + m1x1...
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, Y_train)
# Predicting the test set result
Y_pred = regressor.predict(X_test)
np.set_printoptions(precision=2) #This will display any numerical value with 2 decimals after comma
print(np.concatenate((Y_pred.reshape(len(Y_pred), 1), Y_test.reshape(len(Y_test), 1)),1)) | true |
9aae48aeae5c81ef96ed1e28e6764e67a89fc4fa | FordMcLeod/witAdmin | /python/rockpaperscissors.py | 2,234 | 4.53125 | 5 | # Rock Paper scissors demo for python introduction. SciCamps 2017
# Extentions: Add options for lives, an option to ask the player to play again.
# 2 player mode. Add another option besides rock/paper/scissors. etc.
import random
import time
computer = random.randint(0,2) # Let 0 = rock, 1 = paper, 2 = scissors
print("Let's play rock paper scissors!")
time.sleep(1.5) # Pause in between statements
while True: # Validate input to make sure user can only type 'y' or 'n'
instruct = input("Wish to listen to instructions?(y/n) ").lower() # keep input in lowercase letters
if instruct == 'y' or instruct == 'n': # if we get what we want, break out of while loop
break
if instruct == 'y':
# These triple quotes let use write more stuff for the print statement in several lines
print('''In this game you choose rock paper or scissors and hope to beat your opponent's move.
Scissors beats paper, paper beats rock, and rock beats scissors. The computer chooses its move
based on a random number. You win if your move is successful.''')
time.sleep(3)
while True:
player = input("Choose rock,paper, or scissors. (r/p/s)").lower()
if player == 'r' or player == 'p' or player == 's':
break
if computer == 0: # if computer choose rock
if player == 'r':
print('It is a tie! Computer chose rock')
elif player == 'p':
print('You win! Computer chose rock')
else:
print('You lose! Computer chose rock')
elif computer == 1: # if computer chooses paper
if player == 'r':
print('You lose! Computer chose paper')
elif player == 'p':
print('It is a tie! Computer chose paper')
else:
print('You Win! Computer chose paper')
else: # if computer chooses scissors
if player == 'r':
print('You Win! Computer chose scissors')
elif player == 'p':
print('You lose! Computer chose scissors')
else:
print('It is a tie! Computer chose scissors') | true |
d81c8918a31ad2299039cdcc2517d1eeacb72599 | RyuAsuka/python-utils | /color-code-change.py | 2,192 | 4.125 | 4 | import sys
usage = """
Usage:
python color-code-change.py <rgb|hex> <number>
Arguments:
rgb: Convert RGB color to hex number style.
hex: Convert hex number color code to RGB color number.
Examples:
python color-code-change.py rgb 100 90 213 -> #645AD5
python color-code-change.py hex FF9900 -> 255 153 0
"""
_hex_digits = [
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'A',
'B',
'C',
'D',
'E',
'F']
def rgb_to_hex(r, g, b):
result = ''
try:
if r < 0 or g < 0 or b < 0 or r > 255 or g > 255 or b > 255:
raise ValueError('RGB value should between 0 and 255.')
for num in [r, g, b]:
t1 = _hex_digits[num // 16]
t2 = _hex_digits[num % 16]
result += t1 + t2
return '#' + result
except ValueError as e:
print(e)
def hex_to_rgb(hex_number):
result = []
try:
if len(hex_number) != 6:
raise ValueError('The length of HEX number must be 6!')
t1 = hex_number[0:2]
t2 = hex_number[2:4]
t3 = hex_number[4:]
for t in [t1, t2, t3]:
assert isinstance(t, str)
if t[0].upper() not in _hex_digits or t[1].upper() not in _hex_digits:
raise ValueError('Invalid characters! Please check your input.')
result.append(_hex_digits.index(t[0].upper()) * 16 + _hex_digits.index(t[1].upper()))
return result
except ValueError as e:
print(e)
if __name__ == '__main__':
if len(sys.argv) < 2:
print(usage)
elif sys.argv[1] == 'rgb':
if len(sys.argv) == 5:
result = rgb_to_hex(int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
if result is not None:
print(result)
else:
print(usage)
elif sys.argv[1] == 'hex':
if len(sys.argv) == 3:
result = hex_to_rgb(sys.argv[2])
if result is not None:
print(result)
else:
print(usage)
else:
print(usage)
| true |
6fb000907798ff6426fd8fc933ecf2cc5656ab40 | ravularajesh21/Python-Tasks | /Count number of alphabets,digits and special characters in STRING.py | 532 | 4.28125 | 4 | # Count number of alphabets,digits and special characters
string=input('enter string:')
alphabetcount=0
digitcount=0
specialcharactercount = 0
for x in string:
if x>='A' and x<='Z' or x>='a' and x<='z':
alphabetcount = alphabetcount + 1
elif x>='0' and x<='9':
digitcount=digitcount + 1
else:
specialcharactercount = specialcharactercount+1
print('Alphabet count',alphabetcount)
print('digit count',digitcount)
print('special character count',specialcharactercount)
| true |
c7cf39004c6961400afcb2983112060aba156f44 | ravularajesh21/Python-Tasks | /Palindrome 1.py | 553 | 4.5 | 4 | # Approach 1
date = input('enter the date in dd/mm/yyyy format:')
given_date = date.replace('/', '')
reversed_date = given_date[::-1]
if given_date == reversed_date:
print(date,'is palindrome')
else:
print('It is not palindrome')
# Approach 2
day = input('enter day:')
month = input('enter month:')
year = input('enter year:')
given_date = day+month+year
reversed_date = given_date[::-1]
if given_date == reversed_date:
print('date is not palindrome')
else:
print('date is not palindrome')
| true |
85e1e5c1adbc4daf79aaebaa31a2514e523dcef9 | KotaCanchela/PythonCrashCourse | /6 Dictionaries/pizza.py | 774 | 4.34375 | 4 | # Store information about a pizza being ordered.
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese']
}
# Summarise the order
print(f"You ordered a {pizza['crust']}-crust pizza with the following toppings: ")
for topping in pizza['toppings']:
print("\t" + topping)
# favourite languages.py
print("")
favourite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell']
}
for name, languages in favourite_languages.items():
if len(languages) > 1:
print(f"{name.title()}'s favourite languages are: ")
elif len(languages) == 1:
print(f"{name.title()}'s favourite language is: ")
for language in languages:
print(f"\t{language.title()}") | true |
b3f906c56f714ca8d5e724b607dbe2e8d071b662 | KotaCanchela/PythonCrashCourse | /6 Dictionaries/favourite_languages.py | 1,860 | 4.5 | 4 | # Break a large dictionary into several lines for readability
# Add a comma after last key-value pair to be ready to add any future pairs
favourite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
sarah_language = favourite_languages['sarah'].title()
print(f"Sarah's favourite language is {sarah_language}.")
print("The following languages have been mentioned: ")
for language in favourite_languages.values():
print(language.title())
print(f"The following languages have been mentioned: "
f"{[language for language in favourite_languages.values()]}")
# removing duplicates (python was mentioned twice before)
print("")
print("The following languages have been mentioned: ")
for language in set(favourite_languages.values()): # set is a collection in which each item must be unique
print(language.title())
# languages = {'python', 'ruby', 'c', 'python'} IS ALSO A SET
# print(languages) will return no duplicates
# IMPORTANT: IF YOU SEE BRACES BUT NO KEY-VALUE PAIRS. YOU'RE PROBABLY LOOKING AT A SET (does not retain info in order)
# 6-6 Polling
# Make a list of people who should take the favorite languages poll.
# Include some names that are already in the dictionary and some that are not.
# Loop through the list of people who should take the poll.
# If they have already taken the poll, print a message thanking them for responding.
# If they have not yet taken the poll, print a message inviting them to take the poll.
poll_applicants = ['jen', 'sarah', 'henry', 'james']
for applicant in poll_applicants:
if applicant not in favourite_languages:
print(f"{applicant.title()}, you have not yet taken the poll. "
f"Please take the poll.")
elif applicant in favourite_languages:
print(f"Thank you {applicant.title()} for taking the poll.")
| true |
9656f8e78d643569f078cf363ca57b4af32cb8ad | KotaCanchela/PythonCrashCourse | /9 Classes/9-8_Privileges.py | 1,844 | 4.28125 | 4 | # Write a separate Privileges class. The class should have one attribute, privileges,
# that stores a list of strings as described in Exercise 9-7. Move the show_privileges()
# method to this class. Make a Privileges instance as an attribute in the Admin class.
# Create a new instance of Admin and use your method to show its privileges.
from modules import User
class Admin(User):
"""Stores information about a user"""
def __init__(self, first_name, last_name):
"""Initialise attributes about a person's name"""
super().__init__(first_name, last_name)
"""Initialise an empty set of privileges"""
self.privileges = Privileges()
def show_privileges(self):
"""Shows the user's privileges"""
print(
f"{self.first_name.title()} {self.last_name.title()} has the following privileges:"
)
if self.privileges:
for privilege in self.privileges:
print(f"\t{privilege.capitalize()}")
else:
print("This user has no privileges")
class Privileges():
def __init__(self, privileges=[]):
"""Initialise privileges for the user."""
self.privileges = privileges
def show_privileges(self):
"""Shows the user's privileges"""
print(
f"User has the following privileges:"
)
if self.privileges:
for privilege in self.privileges:
print(f"\t{privilege.capitalize()}")
else:
print("This user has no privileges")
my_user = Admin('Kota', 'canchela')
my_user.describe_user()
my_user.show_privileges
my_user_privileges = [
'mod mod any user',
'can ban who they wish',
'ability to promote any user'
]
my_user.privileges.privileges = my_user_privileges
my_user.privileges.show_privileges()
| true |
4d440d271bd189b22db644b888408fd001330c81 | KotaCanchela/PythonCrashCourse | /4 working with lists/4-6 Odd Numbers.py | 932 | 4.78125 | 5 | # “4-6. Odd Numbers: Use the third argument of the range() function
# to make a list of the odd numbers from 1 to 20.
# Use a for loop to print each number.
odd_number = [value for value in range(1, 21, 2)]
print(odd_number)
# 4-7. Threes: Make a list of the multiples of 3 from 3 to 30.
# Use a for loop to print the numbers in your list.
threes = [value for value in range (3, 31, 3)]
print(threes)
threes_alt = []
for value in range (3, 31, 3):
threes_alt.append(value)
print(threes_alt)
# 4-8 Cubes: “ A number raised to the third power is called a cube.
# For example, the cube of 2 is written as 2**3 in Python.
# Make a list of the first 10 cubes (that is, the cube of each integer from 1 through 10)
# and use a for loop to print out the value of each cube.
cubes = [value ** 3 for value in range (1, 11)]
print(cubes)
cubes_alt = []
for value in range (1, 11):
cubes_alt.append(value ** 3)
print(cubes_alt) | true |
4262c4943e75c83ce8b337b8ec7a7802400760e5 | KotaCanchela/PythonCrashCourse | /10 Files and Exceptions/favourite_number.py | 784 | 4.46875 | 4 | # Write a program that prompts for the user’s favorite number. Use json.dump()
# to store this number in a file. Write a separate program that reads in this
# value and prints the message, “I know your favorite number! It’s _____.”
import json
def ask_number():
"""Asks the user for their favourite number and stores it."""
filename = '10 Files and Exceptions/favourite_number.json'
ask_number = input("What is your favourite number? ")
with open(filename, 'w') as f:
json.dump(ask_number, f)
return filename
def remember_number():
filename = '10 Files and Exceptions/favourite_number.json'
with open(filename, 'r') as f:
number = json.load(f)
print(f"Your favourite number is {number}")
ask_number()
remember_number()
| true |
332454e2039df29fa6c379252da70dcbd5c8a532 | KotaCanchela/PythonCrashCourse | /7 User input and While statements/Counting.py | 609 | 4.375 | 4 | # Using continue in a loop
# continue allows the user to return to the beginning of the loop rather than breaking out entirely
# The continue statement tells Python to ignore the rest of the loop
# Therefore, when current_number is divisible by 2 it loops back
# otherwise when it is odd it goes to the next line (print)
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
# Avoiding infinite loops
# If you forget to add the x += 1 the loop will run forever
print("")
x = 1
while x <= 5:
print(x)
x += 1 | true |
cefb4142ffda596bf0e822678abdabac4209538b | OldLace/Python_the_Hard_Way | /may_19.py | 1,844 | 4.1875 | 4 | #May 19 - Paul Gelot
#Python the Hard Way - Exercise 12
num1 = int(input("Please enter a number: "))
num2 = int(input("Please enter another number: "))
total_sum = num1 + num2
subtract = num1 - num2
product = num1 * num2
division1 = num1 / num2
print("The sum of the two numbers is:", total_sum)
print("The difference between the two numbers is:", subtract)
print ("The product of the two numbers is:", product)
print(25 * "**")
print(int(division1))
print(division1)
# from sys import argv
# script, file_name = argv
# print(file_name)
# text_file = open(file_name)
# print(text_file)
# print(text_file.read())
#####################################
#import argv method from sys
from sys import argv
#define script & filename as argument
script, filename = argv
txt = open(filename)
#displays message and name of file
print(f"Here's your file {filename}:")
#displays contents of text file
print(txt.read())
#Asks for filename
print("Type the filename again:")
file_again = input("> ") #seeks input from user for file name
#Uses input from previous line
txt_again = open(file_again)
#displays contents of second text file
print(txt_again.read())
from sys import argv
script, file_name = argv
text_file = open(file_name, 'w')
print(text_file)
text_file.write('Adding to the file')
text_file.close()
text_file = open(file_name)
print(text_file.read())
#Importing
import math
thenumber = int(input("Please enter a number: "))
print(int(math.sqrt(thenumber)))
# Two Files - I got it... I think
from sys import argv
script, filename1, filename2 = argv
# txt = filename.read()
text_file1 = open(filename1)
info = text_file1.read()
# print(info)
text_file2 = open(filename2, 'w')
text_file2.write(info)
text_file2.close()
text_file2 = open(filename2, 'r')
info2 = text_file2.read()
# text_file2.write(info)
print(info2)
| true |
180c892336d6a048da555972c923c8968874cafc | OldLace/Python_the_Hard_Way | /hw4.py | 1,723 | 4.4375 | 4 |
# 1. Write a Python program to iterate over dictionaries using for loops
character = {"name": "Walter", "surname": "White", "nickname": "Isenberg", "height": "6 foot 7", "hobby": "trafficking"}
for i in character:
print(i,":", character[i])
# 2. Write a function that takes a string as a parameter and returns a dictionary. The
# dictionary keys should be numbers from 0 to the length of strings and values should be
# the characters appeared in the string.
print("***************" * 4)
def into_dictionary(string):
string_dict = {}
for i in range(len(string)):
string_dict.update({i:string[i]})
print(string_dict)
into_dictionary("quick")
print("***************" * 4)
def make_dict(string):
the_dict = {}
key = 0
for val in string:
the_dict[key] = val
key = key + 1
return the_dict
print(make_dict("test"))
print("***************" * 4)
# a. For example: function call with ‘hello’ should print {0: ‘h’, 1:’e’, 2:’l’, 3: ‘l’ , 4:’o’}
# 3. Write a Python script to check if a given key already exists in a dictionary.
def check_for_key(q):
for i in character:
if i == q:
print("Key exists")
else:
continue
check_for_key("surname")
# 4. Create a dictionary to hold information about pets. Each key is an animal's name, and
# each value is the kind of animal.
# i. For example, 'ziggy': 'canary'
# b. Put at least 3 key-value pairs in your dictionary.
pets = {'Lucky': 'hamster', 'Spot': 'dog', 'Sophia': 'cat', 'Dumbo': 'elephant'}
# c. Use a for loop to print out a series of statements such as "Willie is a dog."
print("******" * 4)
for i in pets:
print(i, "is a", pets[i]) | true |
51f72b65f476209ce78a087d0c401548be8dbb34 | nivedipagar12/PracticePython | /E7_ListComprehensions.py | 882 | 4.28125 | 4 | '''
************* DISCLAIMER: THESE TASKS WERE POSTED ON https://www.practicepython.org ***********************************
************************* I AM ONLY PROVIDING SOLUTIONS ***************************************************************
Project/Exercise 7 : List Comprehensions (https://www.practicepython.org/)
Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100].
Write one line of Python that takes this list a and makes a new list that has only the even
elements of this list in it.
Solution
Created on: 14/08/2019
Created by: Nivedita Pagar
'''
# Define the list
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# create a new list with only the even elements of list a
print("The new list with even elements is = " + str([i for i in a if i % 2 == 0]))
| true |
76100afdfbeaabc631e5375da7ce9d06553957d3 | nivedipagar12/PracticePython | /E24_DrawAGameBoard.py | 2,666 | 4.4375 | 4 | '''
************* DISCLAIMER: THESE TASKS WERE POSTED ON https://www.practicepython.org ***********************************
************************* I AM ONLY PROVIDING SOLUTIONS ***************************************************************
Project/Exercise 24 : Draw a Game Board (https://www.practicepython.org/)
This exercise is Part 1 of 4 of the Tic Tac Toe exercise series. The other exercises are: Part 2,
Part 3, and Part 4.
Time for some fake graphics! Let’s say we want to draw game boards that look like this:
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
This one is 3x3 (like in tic tac toe). Obviously, they come in many other sizes (8x8 for chess,
19x19 for Go, and many more).
Ask the user what size game board they want to draw, and draw it for them to the screen using Python’s
print statement.
Remember that in Python 3, printing to the screen is accomplished by
print("Thing to show on screen")
Hint: this requires some use of functions, as were discussed previously on this blog and elsewhere
on the Internet, like this TutorialsPoint link.
Solution
Created on: 19/08/2019
Created by: Nivedita Pagar
'''
def user_input():
'''asks the user the desired size of the board
Parameters
-----------
None
Returns
-----------
size1
integer representing size of the board
'''
global size1
size1 = int(input("Which size board do you want ? \nPlease enter an integer for example 'n' for an 'nxn' board: "))
return size1
def characters(size):
'''defines the characters to be printed and the sequence in which they are to be printed
Parameters
-----------
size: int
user defined size of the board
Returns
-----------
None
'''
dash = "-"
line = "|"
space = " "
rows = (space + 3 * dash) * size
columns = (line + (3 * space)) * (size+1)
for i in range(size):
print(rows)
print(columns)
print(rows)
user_input()
characters(size1)
| true |
17e09b72eba9b69ffed63b90d1ab3ceaec8b225a | nivedipagar12/PracticePython | /E1_CharacterInput.py | 1,894 | 4.28125 | 4 | '''
************* DISCLAIMER: THESE TASKS WERE POSTED ON https://www.practicepython.org************************************
************************* I AM ONLY PROVIDING SOLUTIONS ***************************************************************
Project/Exercise 1 : Character Input (https://www.practicepython.org/)
Create a program that asks the user to enter their name and their age. Print out a message addressed to
them that tells them the year that they will turn 100 years old.
Extras:
1) Add on to the previous program by asking the user for another number and printing out that many
copies of the previous message. (Hint: order of operations exists in Python)
2) Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same
as pressing the ENTER button)
Solution
Created on: 12/08/2019
Created by: Nivedita Pagar
'''
# Import datetime package to determine the current year instead of hard coding it.
import datetime
# User variables
name, age = input("Enter your name and age (separated by a space): ").split()
# Create a datetime object
now = datetime.datetime.now()
# Find out the current year, subtract the current age from 100 and add the difference to the current year
current_year = now.year + (100 - int(age))
num = int(input("Enter the number of times you wish to see the result : "))
# Simply print the result
print("You will turn 100 in the year : " + str(current_year))
# Print the result "num" times using a for loop
for i in range(0, num):
print("(EXTRA LOOP) You will turn 100 in the year : " + str(current_year))
# Print the result "num" times by manipulating strings
print(("(EXTRA STRING MANIPULATION) You will turn 100 in the year : " + str(current_year) + "\n") * num)
| true |
a81f36182dee04cd838b6ce101acd217d309ab66 | poojajunnarkar11/CTCI | /CallBoxDevTest-3.py | 567 | 4.53125 | 5 | def is_power_two (my_num):
if my_num == 0:
return False
while (my_num != 1):
if my_num%2 != 0:
return False
my_num = my_num/2
return True
print is_power_two(18)
# Why this will work for any integer input it receives?
# -Because the while loop works until the number is 1
# -Numbers that are power of two will loop thorugh the while and return True
# -Odd numbers will return False
# -Even numbers that are not powers of 2 will be divided by 2 unless they are equal to an odd number whereafter the loop returns False | true |
00404a17c4abb680cc7424d8e968d4b5bce4de82 | bsakers/Introduction_to_Python | /classes_three.py | 1,976 | 4.3125 | 4 | class Computer(object):
condition = "new"
def __init__(self, model, color, ram, storage):
self.model = model
self.color = color
self.ram = ram
self.storage = storage
def display_computer(self):
return "This is a %s %s with %s gb of RAM and %s gb SSD." %(self.color, self.model, str(self.ram), str(self.storage))
def use_computer(self):
self.condition = "used"
my_computer = Computer("Macbook Pro", "space grey", 16, 512)
print my_computer.display_computer()
print my_computer.condition
my_computer.use_computer()
print my_computer.condition
#note that in the above we modified condition variable from new to used, via the use_computer method
#if we were to create a new computer variable, it would have the "new" condition
class CellPhone(Computer):
def __init__(self, model, color, ram, storage, carrier):
self.model = model
self.color = color
self.ram = ram
self.storage = storage
self.carrier = carrier
def use_computer(self):
self.condition = "almost new"
def __repr__(self):
return "(%s, %s, %i, %i, %s)" %(self.model, self.color, self.ram, self.storage, self.carrier)
my_cell = CellPhone("iPhone", "black", 8, 64, "Verizon")
print my_cell.carrier
print my_cell.condition
my_cell.use_computer()
print my_cell.condition
#in the above, we overrode the "use computer" method, to change the condition from new to "almost new"
#OVERRIDING __repr__():
#there is a built in function, __repr__ which stands for representation
#representation is how python will represent an object
#normally, this is returned in a format similar to <__ object at 0x012202>
#however, we can tell python to show us the object however we want
#note the difference between printing my_computer and my_cell below
print my_computer
print my_cell
#since we overwrote the repr method for the CellPhone class, we see the object differently than for the computer class
| true |
c4f1a54798667c53eb6952afc1d0fe923c052803 | bsakers/Introduction_to_Python | /classes.py | 1,977 | 4.34375 | 4 | #general sytax for a class:
class NewClassName(object):
# code
pass
#in the above, we simply state the keyword 'class' and whatever we want to name it
#then we state what the class will inherit from (here we inherit from python's object)
#the 'pass' keyword doesnt do anything, but can act as a placeholder to not break our placeholder
#similar to ruby, each class requires an initialize function to actually create class objects
class Hero(object):
def __init__(self, name, role):
self.name = name
self.role = role
is_from_dota2 = True
def description(self):
print self.name
print self.role
#in the above, the initialize function follows the syntax '__init__(x, y, z)'
#the first argument is almost always 'self', which just refers to that specific object being created
#technically, you dont have to use 'self', as the first argument will always refer to calling upon that specific object, but this is common practice
#under initialize we define each of the subsequent arguments passed in
#this is very similar to ruby, where we used @name = name
#since we've made a class, we can now instantiate objects:
jugg = Hero("Juggernaut", "carry")
print jugg.name, jugg.role
#scope
# global variables/functions, variables that are available everywhere
# member variables/functions, variables that are only available to members of a certain class
# instance variables/functions, variables that are only available to particular instances of a class
#in our hero class, we created a member variable, is_from_dota2, meaning all objects of that class have access (and will return the same)
print jugg.is_from_dota2
#no matter how many heros I create, they will all have true for is_from_dota2
#we also created a member function, description, which also required a self statement
jugg.description()
#note in the above, I can call .description() on ANY of my class objects since it's a member function
| true |
027342a1e6c8fa72fc03ea820f4770209fa04f77 | bsakers/Introduction_to_Python | /enumerate.py | 463 | 4.6875 | 5 | #enumerate supplies a corresponding index as we loop
options = ["pizza", "sushi", "gyro"]
#normal for loop:
for option in options:
print option
#enumerator (note that "index" could be replaced by anything; it's just a placeholder)
for index, option in enumerate(options):
print index, option
#we can even alter the index count if needed (example, for a list to not start at 1)
for index, option in enumerate(options):
print index +1, option
| true |
325ab3f4d26130fd386bbdb3473ae5c7dbe9ca63 | bsakers/Introduction_to_Python | /pig_latin_translator.py | 376 | 4.125 | 4 | print 'Welcome to the Pig Latin Translator!'
original_word = raw_input("Enter a word you would like translated: ").lower()
ending = "ay"
if len(original_word) > 0 and original_word.isalpha():
translated_word = original_word[1:len(original_word)] + original_word[0] + ending
print translated_word
else:
print "Your imput is either empty or contains a non-letter"
| true |
3aae270f26e6a22bf805081abfee3ed682002282 | ayecoo-103/Python_Code_Drills | /03_Inst_ATM_Application_Logic/Unsolved/atm.py | 656 | 4.15625 | 4 | """This is a basic ATM Application.
This is a command line application that mimics the actions of an ATM.
Example:
$ python app.py
"""
accounts = [
{
"pin": 123456,
"balance" : 1436.19},
{
"pin" : 246802,
"balance": 3571.87},
{
"pin": 135791,
"balance" : 543.79},
{
"pin" : 123987,
"balance": 25.89},
{
"pin" : 269731,
"balance": 3258.42}
]
def login(user_pin):
for account in accounts:
if account ["pin"] == user_pin:
print ("")
return account["balance"]
print("Wrong PIN")
return False
# Create the `login` function for the ATM application.
| true |
ac51a04b6213e9a8b96e8b1b5d8e4310b56a945a | sarahdepalo/python-classes | /pokemon.py | 2,834 | 4.125 | 4 | #Below is the beginnings of a very basic pokemon game. Still needs a main menu built in. Someday I'd like to add the ability to maybe find new pokemon and battle random ones!
class Pokemon:
def __init__(self, name, health, attack, defense):
self.name = name
self.health = health
self.attack = attack
self.defense = defense
self.potions = 3
def attack_opponent(self, other_pokemon):
# While loop that starts the battle
while self.health > 0 or other_pokemon.health == 0:
desire_to_attack = input("Do you want to attack? Yes or No? ")
lower_desire_to_attack = desire_to_attack.lower()
#If the user wants to attack do:
if lower_desire_to_attack == "yes":
other_pokemon.health = other_pokemon.health - (self.attack * 0.1)
self.attack -= 5
self.health = self.health - (other_pokemon.attack * 0.1)
print("%s's health has decreased to %d" % (other_pokemon.name, other_pokemon.health))
print("-----------")
print("%s's attack has decreased to %d" % (self.name, self.attack))
print("%s attacked your pokemon. Your health fell to: %d" % (other_pokemon.name, self.health))
elif lower_desire_to_attack == "no":
print("""
1. Flee
2. Take Potion
""")
flee_or_potion = int(input("What do you want to do? Type 1 or 2." ))
# Option for taking potions
if flee_or_potion == 2:
if self.potions > 0:
self.health += 20
self.potions -= 1
print("Your pokemon's health is now at %d. You have %d potions left" % (self.health, self.potions))
else:
print("You don't have any more potions.")
# Option for fleeing the battle
else:
print("You have fled the battle.")
self.health = 0
else:
print("Please enter a valid option.")
def list_stats(self):
print("""%s's stats:
Health: %d
Attack: %d
Defense: %d
""" % (self.name, self.health, self.attack, self.defense))
running = True
charizard = Pokemon("Charizard", 100, 120, 80)
blastoise = Pokemon("Blastoise",100, 100, 110)
charizard.attack_opponent(blastoise)
# print("Welcome to Pokemon!")
# while running:
# print("""
# 1. View Pokemon's stats
# 2. Fight another pokemon
# 3. Exit
# """)
# user_input = int(input("What would you like to do? Select a number 1-3"))
| true |
b2478988fed601e0c3b2bbcba70605d0940622b4 | seshu141/20-Projects | /19th Program.py | 715 | 4.125 | 4 | # 19th program Find second biggest number of a list
print(" enter the range of no. and stop")
def Range(list1):
largest = list1[0]
largest2 = None
for item in list1[1:]:
if item > largest:
largest2 = largest
largest = item
elif largest2 == None or largest2 < item:
largest2 = item
print("Largest element is:", largest)
print("Second Largest element is:", largest2)
# Driver Code
# try block to handle the exception
try:
my_list = []
while True:
my_list.append(int(input()))
# if the input is not-integer, just print the list
except:
print(" The Range of no u enter are : ", my_list)
Range(my_list) | true |
40f42faa9ff184914e9725e845f69113d73634a2 | stevenckwong/learnpython | /ex06.py | 590 | 4.3125 | 4 | #String formatting
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print (joke_evaluation.format(hilarious))
a = "Adam"
b = "Bob"
c = "Cathryn"
friends = "There were once 3 friends named {}, {} and {}"
print (friends.format(a,b,c))
# positioning of the variables corresponds to the location of the {} in the string
bfgf = "{} and {} were in love and {} was jealous"
print (bfgf.format(a,c,b))
bfgf2 = f"Because of this {b} left the group, and {a} and {c} broke up"
print (bfgf2)
w = "This is eh left side of .... "
e = "a string with a right side."
print (w + e)
| true |
9b67263e7c33c532840bd950c7fc055053e70cd7 | stevenckwong/learnpython | /ex32.py | 676 | 4.53125 | 5 | #Loops and Lists
the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'quarters']
#the first kind of for loop that goes through a list
for number in the_count:
print(f"This is count {number}")
for fruit in fruits:
print(f"A fruit of type: {fruit}")
# notice we have to use {} since we don't know what type of data is in the list
for i in change:
print(f"I got {i}")
# we can also build lists, first starting with an empty one.
elements = []
for i in range(0,6):
print(f"Adding {i} to the list")
elements.append(i)
#now we can print them out too
for i in elements:
print (f"Element was: {i}")
| true |
66fa6d629d9ddfe80b4255e1ba72f95bff31ad4a | kwikl3arn/python-tutorial | /Python-Palindrome-Number.py | 290 | 4.25 | 4 | # Python Program for Palindrome Number
num = int(input("Enter a number: "))
temp = num
rev = 0
while num>0:
remain = num % 10
rev = (rev * 10) + remain
num = num // 10
if temp == rev:
print("Number is palindrome")
else:
print("Number is not palindrome")
| true |
4a369bff7a8797951f2ab3c7af2fef2b4ae75ba3 | CraGL/Hyperspectral-Inverse-Skinning | /PerVertex/util.py | 2,478 | 4.21875 | 4 | import re
import numpy as np
def veclen(vectors):
""" return L2 norm (vector length) along the last axis, for example to compute the length of an array of vectors """
return np.sqrt(np.sum(vectors**2, axis=-1))
def normalized(vectors):
""" normalize array of vectors along the last axis """
return vectors / veclen(vectors)[..., np.newaxis]
def homogenize(v, value=1):
""" returns v as homogeneous vectors by inserting one more element into the last axis
the parameter value defines which value to insert (meaningful values would be 0 and 1)
>>> homogenize([1, 2, 3]).tolist()
[1, 2, 3, 1]
>>> homogenize([1, 2, 3], 9).tolist()
[1, 2, 3, 9]
>>> homogenize([[1, 2], [3, 4]]).tolist()
[[1, 2, 1], [3, 4, 1]]
"""
v = np.asanyarray(v)
return np.insert(v, v.shape[-1], value, axis=-1)
def dehomogenize(a):
""" makes homogeneous vectors inhomogenious by dividing by the last element in the last axis
>>> dehomogenize([1, 2, 4, 2]).tolist()
[0.5, 1.0, 2.0]
>>> dehomogenize([[1, 2], [4, 4]]).tolist()
[[0.5], [1.0]]
"""
a = np.asfarray(a)
return a[...,:-1] / a[...,np.newaxis,-1]
def transform(v, M, w=1):
""" transforms vectors in v with the matrix M
if matrix M has one more dimension then the vectors
this will be done by homogenizing the vectors
(with the last dimension filled with w) and
then applying the transformation """
if M.shape[0] == M.shape[1] == v.shape[-1] + 1:
v1 = homogenize(v, value=w)
return dehomogenize(np.dot(v1.reshape((-1,v1.shape[-1])), M.T)).reshape(v.shape)
else:
return np.dot(v.reshape((-1,v.shape[-1])), M.T).reshape(v.shape)
def filter_reindex(condition, target):
"""
>>> indices = np.array([1, 4, 1, 4])
>>> condition = np.array([False, True, False, False, True])
>>> filter_reindex(condition, indices).tolist()
[0, 1, 0, 1]
"""
if condition.dtype != np.bool:
raise ValueError, "condition must be a binary array"
reindex = np.cumsum(condition) - 1
return reindex[target]
def tryint(s):
try:
return int(s)
except:
return s
def alphanum_key(s):
""" Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"]
"""
return [ tryint(c) for c in re.split('([0-9]+)', s) ]
def sort_nicely(l):
""" Sort the given list in the way that humans expect.
"""
l.sort(key=alphanum_key)
| true |
3667fe3935484f27411ba2d9522f282b98cd9d26 | adsr652/Python | /fact2.py | 534 | 4.1875 | 4 | def recu_fact(num):
if num==1:
return num
else:
return num * recu_fact(num-1)
num= int(input("Enter any no. : "))
if num < 0:
print("Factorial cannot be found for negative integer")
print("Reenter the value again ")
num= int(input("Enter any no. : "))
if num==0:
print("Factorial of 0 is 1")
else:
print("Factorial of", num, "is: ", recu_fact(num))
elif num==0:
print("Factorial of 0 is 1")
else:
print("Factorial of", num, "is: ", recu_fact(num))
| true |
7bf3ded502ca212e55ebdb24b40b27cdf9c020df | shillwil/cs-module-project-iterative-sorting | /src/searching/searching.py | 908 | 4.125 | 4 | def linear_search(arr, target):
# Your code here
if len(arr) is not 0:
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
return -1
# Write an iterative implementation of Binary Search
def binary_search(arr, target):
# Your code here
if len(arr) is not 0:
lowest = 0
highest = len(arr) - 1
return binary_search_helper(arr, target, highest, lowest)
else:
return -1
def binary_search_helper(arr, target, highest, lowest):
mid_range = ((lowest + highest) / 2).__round__()
if arr[mid_range] < target:
return binary_search_helper(arr, target, highest, mid_range)
elif arr[mid_range] > target:
return binary_search_helper(arr, target, mid_range, lowest)
else:
if arr[mid_range] == target:
return mid_range
else:
return -1 | true |
ec747b85a18d2962577e2e24547981b3d70be38b | kemar1997/TSTP_Programs | /Chapter13_TheFourPillarsOfObjectOrientedProgramming/Inheritance.py | 2,766 | 4.90625 | 5 | """
Inheritance in programming is similar to genetic inheritance. In genetic inheritance, you inherit attributes like eye
color from your parents. Similarly, when you create a class, it can inherit methods and variables from another class.
The class that is inherited from is the parent class, and the class that inherits is the child class. In this section,
you will model shapes using inheritance. Here is a class that models a shape:
"""
class Shape:
def __init__(self, w, l):
self.width = w
self.len = l
def print_size(self):
print("""{} by {}
""".format(self.width,
self.len))
my_shape = Shape(20, 25)
my_shape.print_size()
"""
With this class, you can create Shape objects with width and len. In addition, Shape objects have the method
print_size, which prints their width and len.
You can define a child class that inherits from a parent class by passing the name of the parent class as a parameter to
the child class when you create it. The following example creates a Square class that inherits from the Shape class:
"""
# class Square(Shape):
# pass
#
#
# a_square = Square(20,20)
# a_square.print_size()
# >> 20 by 20
"""
Because you passed the Shape class to the Square class as a parameter; the Square class inherits the Shape class's
variables and methods. The only suite you defined in the Square class was the keyword pss, which tells Python not to do
anything.
Because of inheritance, you can create a Square object, pass it a width and length, and call the method print_size on it
without writing any code (aside from pass) in the Square class. This reduction in code is important because avoiding
repeating code makes your program smaller and more manageable.
A child class is like any other class; you can define methods and variables in it without affecting the parent class:
"""
# class Square(Shape):
# def area(self):
# return self.width * self.len
#
#
# a_square = Square(20, 20)
# print(a_square.area())
"""
When a child class inherits a method from a parent class, you can override it by defining a new method with the same
name as the inherited method. A child class's ability to change the implementation of a method inherited from its parent
class is called method overriding.
"""
class Square(Shape):
def area(self):
return self.width * self.len
def print_size(self):
print("""I am {} by {}
""".format(self.width,
self.len))
a_square = Square(20, 20)
a_square.print_size()
"""
In this case, because you defined a method named print_size, the newly defined method overrides the parent method
of the same name, and it prints a new message when you call it.
""" | true |
ced65aca9c260388d36e6d84939b29e3d60660c2 | kemar1997/TSTP_Programs | /Loops/range.py | 750 | 4.90625 | 5 | """
You can use the built-in range function to create a sequence of integers, and use a for-loop to iterate through them.
The range function takes two parameters: a number where the sequence starts and a number where the sequence stops. The
sequence of integers returned by the range function includes the first parameter (the number to start at), but not the
second parameter (the number to stop at). Here is an example of using the range function to create a sequence of
numbers, and iterate through them:
"""
for i in range(1, 11):
print(i)
"""
In this example, you used a for-loop to print each number in the iterable returned by the range function. Programmers
often name the variable used to iterate through a list of integers i.
"""
| true |
52c6816d339f1140d7da3fd7c97c9df468084f7f | kemar1997/TSTP_Programs | /String_Manipulation/Concatenation.py | 321 | 4.25 | 4 | """
You can add two (or more) strings together using the addition operator. HTe result is a string made up of the characters
from the first string, followed by the characters from the next string(s). Adding strings together is called
concatenation:
"""
print("cat" + "in" + "hat")
print("cat" + " in" + " the" + " hat") | true |
56329c35e37e044922969f696523bd39b76281fb | kemar1997/TSTP_Programs | /Challenges/Ch12_Challenges/Triangle.py | 565 | 4.1875 | 4 | # Create a Triangle class with a method called area that calculates and returns
# its area. Then create a Triangle object, call area on it, and print the result.
# a,b,c are the sides of the triangle
class Triangle():
def __init__(self, a, b, c):
self.s1 = a
self.s2 = b
self.s3 = c
def area(self):
# calculcate the semi-perimeter
s = (self.s1 + self.s2 + self.s3) / 2
# calculate the area
return (s*(s-self.s1)*(s-self.s2)*(s-self.s3)) ** 0.5
triangle = Triangle(5, 6, 7)
print(triangle.area())
| true |
17601476e7b674a9900d695a47a4cecc327ae2cf | kemar1997/TSTP_Programs | /Challenges/Ch13_Challenges/Challenge4.py | 415 | 4.34375 | 4 | """
Create a class called Horse and a class called Rider. Use composition to model a horse that has a rider
"""
class Horse:
def __init__(self,
name,
owner):
self.name = name
self.owner = owner
class Rider:
def __init__(self, name):
self.name = name
john = Rider("John Whitaker")
jaguar = Horse("Jaguar",
john)
print(jaguar.owner.name) | true |
25da8767ef0a8ec27bfc216ca40c4cdf9967adf9 | kemar1997/TSTP_Programs | /Challenges/Ch4_Challenges/ch4_challenge1.py | 236 | 4.25 | 4 | """
1. Writing a function that takes a number as an input and returns that number squared.
"""
def square_a_number():
num = input("Enter a number: ")
num = int(num)
return num*num
result = square_a_number()
print(result) | true |
9b7c6e30ca621c5796db893acbb3eab3a7b7d1f5 | paskwal/python-hackerrank | /Basic_Data_Types/04_finding_the_percentage.py | 1,169 | 4.21875 | 4 | # -*- coding: utf-8 -*-
#
# (c) @paskwal, 2019
# Problem
# You have a record of N students. Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry.
# The marks can be floating values. The user enters some integer N followed by the names and marks for N students.
# You are required to save the record in a dictionary data type. The user then enters a student's name.
# Output the average percentage marks obtained by that student, correct to two decimal places.
# Input Format
# The first line contains the integer N, the number of students. The next N lines contains the name and marks obtained by that student
# separated by a space. The final line contains the name of a particular student previously listed.
def mean(numbers):
return float(sum(numbers)) / max(len(numbers), 1)
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
if query_name in student_marks.keys():
print("%.2f" % mean(student_marks[query_name]))
| true |
3c530015d9a9088feb6ce024b49fc3cd51717ba9 | shobha-bhagwat/Python | /games/RockPaperScissors.py | 1,554 | 4.15625 | 4 | import random
rock = 1
paper = 2
scissors = 3
names = {rock: "Rock", paper: "Paper", scissors: "Scissors"}
rules = {rock: scissors, paper: rock, scissors: paper}
player_score = 0
computer_score = 0
def start():
print("Lets play Rock, Paper, Scissors!!")
while game():
pass
scores()
def game():
player = move()
computer = random.randint(1, 3)
result(player, computer)
return play_again()
def move():
while True:
player = input("1: Rock\n2: Paper\n3: Scissors\nMake your move: ")
try:
player = int(player)
if player in (1, 2, 3):
return player
except ValueError:
print("Please enter 1, 2 or 3")
def result(player, computer):
global player_score, computer_score
print("Computer's move: {}".format(names[computer]))
if player == computer:
print("Tie!!")
else:
if rules[player] == computer:
print("You win!! :)")
player_score += 1
else:
print("Sorry, you lost! :(")
computer_score += 1
def play_again():
answer = input("Would you like to play again (y/n): ")
if answer in ('y', 'Y', 'yes', 'YES', 'Yes'):
return answer
else:
print("Thanks for playing the game!")
def scores():
global player_score, computer_score
print("---------- FINAL SCORES ----------------")
print("Computer: {}".format(computer_score))
print("You: {}".format(player_score))
if __name__ == '__main__':
start()
| true |
3eed1469ae90561bb9a21487579d822b21d09f8b | shobha-bhagwat/Python | /algorithms/binarySearch.py | 440 | 4.125 | 4 | def binarySearch(arr, start, end, x):
while start <= end:
mid = (start + end)//2
if arr[mid] == x:
return mid
elif arr[mid] < x:
start = mid + 1
else:
end = mid -1
return -1
arr = [-5, 3.0, 10, 20, 50, 80]
x = 3
result = binarySearch(arr, 0, len(arr), x)
print(result)
arr = [0, 1, 0] #### doesn't work correctly if multiple instances of a number present
| true |
1a257fddb2c63d53423544a9737d3dca62e85968 | xperrylinn/whiteboard | /algo/easy/branch_sums.py | 1,328 | 4.1875 | 4 | # Write a function that takes in a Binary tree and retuns a list of
# its branch sums ordered from leftmost branch to rightmost branch
#
# A branch is the sum of all values in a Binary Tree branch. A
# binary tree branch is a path of nodes in a tree that starts at the
# root and ends at any leaf
# This is the class of the input root. Do not edit it.
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def branchSums(root):
return branchSumsHelper(root, 0, [])
def branchSumsHelper(root, s=0, output=[]):
if root == None:
return
else:
if root.left == None and root.right == None:
output.append(s + root.value)
else:
branchSumsHelper(root.left, s + root.value, output)
branchSumsHelper(root.right, s + root.value, output)
return output
# Notes:
# - O(n) Time | O(n) Space
# -- time: we need to touch each of the n node. At every node constant time
# operations.
# -- space: aside from the recusrive calls on the stack, we are returning
# a list sums and there are roughly 1/2 leaf nodes as there are nodes
# - The question is asking you determine the sum of node values from
# root to each left, orderd left to right.
# -- Left to right is achieved by choosing pre-order traversal of tree
| true |
9ae2ccf4e88e93d0c47565cd6b0b9d18825faa2f | supercp3/code_leetcode | /basedatestructure/stack_run_class.py | 822 | 4.15625 | 4 | class Node:
def __init__(self,value):
self.value=value
self.next=None
class Stack:
def __init__(self):
self.top=None
def push(self,value):
node=Node(value)
node.next=self.top
self.top=node
def pop(self):
node=self.top
if node is None:
raise Exception("this is an empty stack")
self.top=node.next
return node.value
def peek(self):
node=self.top
if node is None:
raise Exception("this is an empty stack")
return node.value
def is_empty(self):
return not self.top
def size(self):
node=self.top
count=0
if node is None:
raise Exception("this is an empty stack")
while node is not None:
count+=1
node=node.next
return count
if __name__=="__main__":
stack=Stack()
stack.push(2)
stack.push(3)
print(stack.peek())
print(stack.is_empty())
print(stack.size()) | true |
877ee9220c82d773f6b8e7e83b281e1be3b455dc | vedashri15/new1 | /Basic1.6.py | 717 | 4.84375 | 5 | #Write a Python program to accept a filename from the user and print the extension of that.
filename = input("Input the Filename: ")
f_extns = filename.split(".")
print ("The extension of the file is : " + f_extns[-1])
#The function returns a list of the words of a given string using a separator as the delimiter string.
#If maxsplit is given, the list will have at most maxsplit+1 elements.
#If maxsplit is not specified or -1, then there is no limit on the number of splits.
#If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings.
#The sep argument may consist of multiple characters.
#Splitting an empty string with a specified separator returns ['']. | true |
85c53dbee3db530435a9f69c43fac32606b6b476 | tonylattke/python_helpers | /5_functions_methods.py | 1,154 | 4.34375 | 4 | ######################## Example 1 - Create a function and using ########################
# Even or not
# @number : Number to decide
# @return : True if the number is even, otherwise Flase
def even(number):
return number % 2 == 0
# Testing Function
for aux in xrange(0,10):
if even(aux):
print "%d - Even" % aux
else:
print "%d - Odd" % aux
################################# Example 2 - Recursion #################################
# Factorial of number
# @number : Number
# @return : Factorial value of number
def factorial(value):
if (value <= 1):
return 1
return value * factorial(value -1)
# Fibonacci
# @value : Number
# @return : Fibonacci value
def fibonacci(value):
if value == 0: return 0
elif value == 1: return 1
else: return fibonacci(value-1)+fibonacci(value-2)
# Testing Function
number = 7
print 'Factorial of %d is %d' % (number,factorial(number))
print 'Fibonacci of %d is %d' % (number,fibonacci(number))
#################################### Example of main ####################################
import sys
def main():
params = sys.argv
print params
print 'Here is the main'
if __name__ =='__main__':
main() | true |
8f6f34a49a9920138306f43dca03aaf9d4952df3 | MilanaShhanukova/programming-2021-19fpl | /shapes/circle.py | 803 | 4.125 | 4 | """
Programming for linguists
Implementation of the class Circle
"""
from math import pi
from shapes.shape import Shape
class Circle(Shape):
"""
A class for circles
"""
def __init__(self, uid: int, radius: int):
super().__init__(uid)
self.radius = radius
def get_area(self):
"""
Returns the area of a circle
:return int: the area of a circle
"""
return self.radius **2 * pi
def get_perimeter(self):
"""
Returns the perimeter of a circle
:return int: the perimeter of a circle
"""
return self.radius * pi * 2
def get_diameter(self):
"""
Returns the diameter of a circle
:return int: the diameter of a circle
"""
return 2 * self.radius
| true |
1c14f80470bc5c858587261c932b8fe958f1b1c3 | yvonneonu/Test8 | /test8.py | 774 | 4.34375 | 4 | # A Simple Python 3 program to compute
# sum of digits in numbers from 1 to n
#Returns sum of all digits in numbers from 1 to n
def countNumberWith3(n) :
result = 0 # initialize result
# One by one compute sum of digits
# in every number from 1 to n
for x in range(1, n + 1):
if(has3(x) == True):
result = result + 1
return result
# A utility function to compute sum
# of digits in a given number x
def has4(x):
while (x != 0):
if (x%10 ==4):
return True
x = x //10
return False
# Driver Program
n = 35
print ("Count of numbers from 1 to ", n,
" that has 3 as a digit is",
countNumbersWith3(n))
| true |
0efc63ac7d07f35ae5d978169adb8849f175bad4 | eawww/BI_HW | /HW1/seqid.py | 2,201 | 4.125 | 4 | #Bridget Mohn and Eric Wilson
#CS 466R
#Homework 1
#Reads an input filename from command line, opens the file, reads each character
#in the file to see whether the file contains a DNA, RNA, or Protein sequence
import sys
#Input filename is taken from the command line which is the second argument
InputFile = sys.argv[1]
#Opens the file read from the command line
fin = open(str(InputFile), "r")
#Array and array length needed to turn the lines in the file one string
temp = []
sequence_length = 80
sequence = ""
#To take the header off of the biological sequence
for line in fin.readlines():
#Add each line in the file into the array
temp.append(line)
#Delete the first line since it's not apart of the sequence
del temp[0]
#Put all the lines of the file into one big string
for line in temp:
modified_line = line.strip()
sequence = sequence + modified_line
seq_type = ""
for char in sequence:
#Checks if U is in the sequence since it is unique to RNA
if('U' in line):
#print("RNA")
seq_type = "RNA"
#Checks the file for all of the possible amino acid codes that make a protein
elif('B' in line or 'D' in line or 'E' in line or 'F' in line or
'H' in line or 'I' in line or 'K' in line or 'L' in line or
'M' in line or 'N' in line or 'Q' in line or 'X' in line or
'R' in line or 'S' in line or 'P' in line or 'V' in line or
'W' in line or 'Y' in line or 'Z' in line):
#print("Protein")
seq_type = "Protein"
#Checks if T is in the sequence since it is only found in DNA and Protein
elif('T' in line):
#print("DNA or Protein")
seq_type = "DNA or Protein"
#If just A, G, and C are found in the sequence then it could be any of the options
elif('A' in line and 'G' in line and 'C' in line):
#print("DNA or RNA or Protein")
seq_type = "DNA or RNA or Protein"
#If none of those are found in the sequence then it is none of the above
else:
#print("None")
seq_type = "None"
print(seq_type)
#Close input file
fin.close()
| true |
3267bcaa907a1eda60abe8c60ff69b7cc7cff0a9 | Ryan-Lawton-Prog/IST | /IST Assessment Program/I1.py | 2,768 | 4.28125 | 4 | def a():
while = True:
print """
\tGuide Contents:
\t* raw_input() = Gives the user the option to input data to the user,
anything inbetween the '()' will be displayed before
the users input.
"""
raw_input()
break
test = True
while test:
print "print \"How old are you?\","
a = raw_input("> ")
if a == "print \"How old are you?\",":
test = False
print ""
else:
print "Please Check Over Your Code"
print ""
test = True
while test:
print "age = raw_input()"
b = raw_input("> ")
if b == "age = raw_input()":
test = False
print ""
else:
print "Please Check Over Your Code"
print ""
test = True
while test:
print "print \"How tall are you?\","
c = raw_input("> ")
if c == "print \"How tall are you?\",":
test = False
print ""
else:
print "Please Check Over Your Code"
print ""
test = True
while test:
print "height = raw_input()"
d = raw_input("> ")
if d == "height = raw_input()":
test = False
print ""
else:
print "Please Check Over Your Code"
print ""
test = True
while test:
print "print \"How much do you weigh?\","
e = raw_input("> ")
if e == "print \"How much do you weigh?\",":
test = False
print ""
else:
print "Please Check Over Your Code"
print ""
test = True
while test:
print "weight = raw_input()"
f = raw_input("> ")
if f == "weight = raw_input()":
test = False
print ""
else:
print "Please Check Over Your Code"
print ""
test = True
while test:
print "print \"So, you're %r old, %r tall and %r heavy.\" % (age, height, weight)"
g = raw_input("> ")
if g == "print \"So, you're %r old, %r tall and %r heavy.\" % (age, height, weight)":
test = False
print ""
else:
print "Please Check Over Your Code"
print ""
print "You have wrote"
print ""
print a
print b
print c
print d
print e
print f
print g
Exit = raw_input()
print "This is what would happen if you ran it."
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
| true |
9bc1edb29c6feb34e3384611c3353014579821d0 | Ryan-Lawton-Prog/IST | /IST Assessment Program/Run.py | 1,632 | 4.15625 | 4 | import Beginner
# Program Varriable is now True
Program = True
# 'while' Program is true run and loop this
while Program:
# select your difficulty text
print "Please select your Stream"
print "Beginner:"
print "Intermediate:"
print "Advanced:"
# difficulty input
Difficulty = raw_input("> ")
# 'if' difficulty is 'Beginner':
if Difficulty == "Beginner":
print "Please select your exercise"
print """
\t* Intro:
\t* 1: A Good First Program
\t* 2: Comments And Pound Characters
\t* 3: Numbers And Math
\t* 4: Variables And Names
\t* 5: More Variables And Printing
\t* 6: Strings And Text
\t* 7: More Printing
\t* 8: Printing, Printing
\t* 9: Printing, Printing, Printing
\t* 10: What Was That
"""
ExerciseB = raw_input("> ")
Beginner.run(ExerciseB)
# 'if' difficulty is 'Intermediate':
elif Difficulty == "Intermediate":
print "Please select your exercise"
print """
\t* Intro:
\t* 1:
\t* 2:
\t* 3:
\t* 4:
\t* 5:
\t* 6:
\t* 7:
\t* 8:
\t* 9:
\t* 10:
"""
ExerciseI = raw_input("> ")
Beginner.run(ExerciseI)
# 'if' difficulty is 'Advanced':
elif Difficulty == "Advanced":
print "Please select your exercise"
print """
\t* Intro:
\t* 1:
\t* 2:
\t* 3:
\t* 4:
\t* 5:
\t* 6:
\t* 7:
\t* 8:
\t* 9:
\t* 10:
"""
ExerciseA = raw_input("> ")
Beginner.run(ExerciseA)
# if no 'if' or 'elif' statments are run, run this:
else:
print "Invalid"
# repeat to beggining of program
Program = True
| true |
40917733d3f5c754297756d8e440bdb2c96d5607 | calvinwalterheintzelman/Computer-Security-Algorithms | /Finding Primes/Fields.py | 1,307 | 4.125 | 4 | # Calvin Walter Heintzelman
# ECE 404
# Homework 3
# Python 3.7.2
import os
import sys
print("Please enter a small digit: ")
number = input()
while(number.isdigit() is False or int(number) < 1):
print("Error! Please only input a single small positive integer!")
number = input()
if(int(number) >= 50):
print('Warning! The input is not that small. Are you sure you want to input an integer that is 50 or greater?')
print('Please anser "y" or "n"')
continue_running = input()
while(not(continue_running == 'y' or continue_running == 'n')):
print('Error! Please enter "y" or "n"')
continue_running = input()
if continue_running == 'n':
print('Please enter a number less than 50')
number = input()
while(number.isdigit() is False or int(number) >= 50 or int(number) < 1):
print('Error! Please only input a positive single integer that is less than 50')
number = input()
number = int(number)
test_prime = 2
is_prime = True
if number == 1:
is_prime = False
while(test_prime <= number/2):
possible_factor = number % test_prime
if possible_factor == 0:
is_prime = False
break
test_prime += 1
if is_prime is True:
print('field')
else:
print('ring') | true |
42efd486938984bf55bb1699472c9abca16e3106 | Pratik180198/Every-Python-Code-Ever | /factorial.py | 480 | 4.375 | 4 | num1=input("Enter number: ")
try:
num=int(num1)
fact=1
for i in range(1,num+1): #Using For Loop
fact=fact*i
print("Factorial of {} is {}".format(num,fact)) #For Loop Answer
def factorial(num): #Using Recursive Method
if num == 0 or num ==1:
return 1
else:
return num * factorial(num-1)
print(f"Factorial of {num} is {factorial(num)}") #Recursive Method Answer
except:
print("Please enter only integer")
| true |
1af7bd227c2e2a919baeda39d55c27d631b93908 | maimumatsumoto/prac04 | /list_exercises.py | 2,474 | 4.28125 | 4 | #//1. Basic list operations//#
numbers=[]
for i in range(5):
value= int(input("Number: "))
numbers.append(value)
print("The first number is {}".format(numbers[0]))
print("The last number is {}".format(numbers[-1]))
print("The smallest number is {}".format(min(numbers)))
print("The largest number is {}".format(max(numbers)))
print("The average of the numbers is {}".format(sum(numbers)/5))
#//2. Woefully inadequate security checker//#
usernames = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45',
'BaseInterpreterInterface', 'BaseStdIn', 'Command', 'ExecState',
'InteractiveConsole', 'InterpreterInterface', 'StartServer', 'bob']
username= input("Enter your username")
if username in usernames:
print("Access granted")
if not username in usernames:
print("Access denied")
#//3. List comprehensions//#
"""
CP1404/CP5632 Practical
List comprehensions
"""
names = ["Bob", "Angel", "Jimi", "Alan", "Ada"]
full_names = ["Bob Martin", "Angel Harlem", "Jimi Hendrix", "Alan Turing",
"Ada Lovelace"]
# for loop that creates a new list containing the first letter of each name
first_initials = []
for name in names:
first_initials.append(name[0])
print(first_initials)
# list comprehension that does the same thing as the loop above
first_initials = [name[0] for name in names]
print(first_initials)
# list comprehension that creates a list containing the initials
# splits each name and adds the first letters of each part to a string
full_initials = [name.split()[0][0] + name.split()[1][0] for name in
full_names]
print(full_initials)
# one more example, using filtering to select only the names that start with A
a_names = [name for name in names if name.startswith('A')]
print(a_names)
# TODO: use a list comprehension to create a list of all of the full_names in lowercase format
#for i in range(len(full_names)):
# full_names[i]=full_names[i].lower()
#print(full_names)
lowercase_full_names =[name.lower() for name in full_names]
print(lowercase_full_names)
almost_numbers = ['0', '10', '21', '3', '-7', '88', '9']
# TODO: use a list comprehension to create a list of integers from the above list of strings
numbers = [int(i) for i in almost_numbers]
print(numbers)
# TODO: use a list comprehension to create a list of only the numbers that are greater than 9 from the numbers (not strings) you just created
greater_9 = [number for number in numbers if number>9]
print(greater_9)
| true |
d7a241d07e554b6b0b56913e51aa3a853ee5c6b9 | gagnongr/Gregory-Gagnon | /Exercises/sum up odd ints.py | 718 | 4.40625 | 4 | # Sum up a series of even numbers
# Make sure user input is only even numbers
# Variable names without types are integers
print("Allow the user to enter a series of even integers. Sum them.")
print("Ignore non-even input. End input with a '.'")
# Initialize input number and the sum
number_str = input("Number: ")
the_sum = 0
# Stop if a period (.) is entered
# remember, number_str is a string until we convert it
while number_str != ".":
number = int(number_str)
if number % 2 == 1: # number is not even (it is odd)
print ("Error. Only even numbers, please.")
number = int(0)
else:
the_sum += number
number_str = input("Number: ")
print ("The sum is: ", the_sum)
| true |
f55ae7e36f0430c48633e5b032f0adf57c57c9b0 | cserajeevdas/Python-Coding | /decorator.py | 701 | 4.5625 | 5 | #assigned a method to a variable and called the method
# def f1():
# print("in f1")
# x = f1
# x()
#calling f2 from the rturn value of f1
# def f1():
# def f2():
# print("in f2")
# return f2
# x = f1()
# x()
#calling the nested method through passed method
# def f1(f):
# def f2():
# print("before function call")
# f()
# print("after function call")
# return f2
# def f3():
# print("this is f3")
# x = f1(f3)
# x()
#creating the decorator function
def f1(f):
def f2():
print("before function call")
f()
print("after function call")
return f2
@f1
def f3():
print("this is f3")
f3()
| true |
5c36b47de38425bf90e47c7348b525a35c173305 | annewoosam/shopping-list | /shoppinglist.py | 628 | 4.21875 | 4 | print("create a quick, no duplicate, alphabetical shopping list by entering items then hitting enter when done.")
shopping_list=[]
while True:
add_item=input("add item>")
if add_item.lower()!="":
shopping_list.append(add_item.lower())
shopping_list=set(shopping_list)
print( "\noriginal order - no duplicates\n")
print(shopping_list)
shopping_list=list(shopping_list)
print("\nduplicates removed and sorted\n")
print(sorted(shopping_list))
else:
print("\nYour final list is:\n")
print(sorted(shopping_list))
break
| true |
987650133ed8611b645aef9a6c2ef0fef97dc2be | tasnia18/Python-assignment-certified-course-in-Coursera- | /Python Data Structure/7_2.py | 954 | 4.125 | 4 | """ 7.2 Write a program that prompts for a file name, then opens that file and reads through the file,
looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values
and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.
You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below
enter mbox-short.txt as the file name. """
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
c=0
k=0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") :
continue
else:
c=c+1
a=line.find(':')
s=line.find('/n',a)
line=line[a+2:s]
line=float(line)
k=k+line
p=(k/c)
print('Average spam confidence:',p) | true |
33791e76660c95af96ae04c7b45fd8b1bcfb5646 | snowd25/pyPract | /stringPermutation.py | 611 | 4.25 | 4 | #Python Program to Print All Permutations of a String in Lexicographic Order using Recursion
#without using permutations builtin
def permuteStr(lst,l,r):
if l == r:
print("".join(lst))
else:
for i in range(l,r+1):
lst[l],lst[i] =lst[i],lst[l]
permuteStr(lst,l+1,r)
lst[l],lst[i] =lst[i],lst[l]
# permutations using library function
from itertools import permutations
def permuteStr1(lst):
print("Using permutations:")
p = permutations(lst)
for ch in p:
print("".join(ch))
str1 = input()
print("Without using permutations:")
permuteStr(list(str1),0,len(str1)-1)
permuteStr1(list(str1))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.