blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d8ca1f9146fa6dad6de66701e10e45f054f37c39 | dgervais19/Eng74_Python | /dictionaries.py | 1,694 | 4.65625 | 5 | # What is a dictionary
# Dictionary (arrays) is another way managing data more Dynamically
# Key value pairs to store and manage data
# Syntax : {"name": "James"}
# a = {"key": "value"}
# what type of data can store/manage
# Let's create one
devops_student_data = {
"key": "value",
"name": "james",
"stream": "tech",
"completed_lessons": 4,
"completed_lesson_names":["operators", "data types", "variables"] # In order to put more than one value to the key you have to create a list
}
# print(type(devops_student_data))
# display the data by fetching the key "name"
# print(devops_student_data["completed_lessons"])
# print(devops_student_data["name"])
# print(devops_student_data.keys())
# print(devops_student_data["completed_lesson_names"])
# How can I change the value of specific key
# devops_student_data["completed_lessons"] = 3
# print(devops_student_data)
# print(devops_student_data.items())
# How can we fetch the value called "data types"
# print(devops_student_data["completed_lesson_names"][1])
# Task
# create a New dictionary to store user details
user_details = {
"key": "value",
"name": "Dono",
"DOB": "12/02/1940",
"course:": "Devops",
"hobbies": ["basketball", "Piano", "Gym", "Socialising", "data types"]
}
print(user_details)
# Managing the list within the dictionary
user_details["hobbies"].append("running")
user_details["hobbies"].remove("data types")
# all the details that you utilised in the last task
# methods of dictionary to remove, add, replace, display the type of items
user_details["age"] = "40"
print(user_details)
# create a list of hobbies of at least 3 items
# display data in reverse order of hobby list
| true |
8d8a4983bc39fb8c6870cb7e7f275b43d160baea | bhawnabhatt2012/python_lab_exp | /2.b.py | 497 | 4.21875 | 4 | index = 0
string = input("Enter the string: ")
substring = input("Enter the substring: ")
if substring in string:
print(substring," is present in ",string)
while index < len(string):
index = string.find(substring, index)
if index == -1:
break
print(substring, ' found at', index)
index += len(substring)
print('No. of occurences of',substring,': ',string.count(substring))
else:
print(substring," is not present in ",string) | true |
edc8eefa43d0a05859412b8ca21107af71e8237c | lanaelsanyoura/CommentedPythonIntermediateWorkshop | /Person.py | 1,226 | 4.25 | 4 | from datetime import date, datetime #for date
class Person:
"""
A person class
==== Attributes ====
firstname: str
lastname: str
birthdate: date YEAR, MONTH, DAY
address: str
"""
def __init__(self): #, firstname, lastname, birthdate, address):
#self.firstname = firstname
#self.lastname = lastname
#self.birthdate = birthdate
#self.address = address
def __str__(self):
"""
Return the string in a human-readable manner
@return: string
"""
#return "{} {}".format(self.firstname, self.lastname)
def age(self):
"""
Given the current date, return the age of this person
:return: int age
"""
#today = date.today()
#age = today.year - self.birthdate.year
#if today < date(today.year, self.birthdate.month, self.birthdate.day):
# age -= 1
#return age
pass
def getInfo(self):
"""
Return the information of this user to showcase overriding
:return:
"""
#print("I am a generic person")
pass
# Example Build
#person = Person("Joane", "Do", date(1997, 4, 20), "50 st george str")
| true |
13c0b258a492922a560d61c522efd7d6217fc045 | michaelkemp2000/vader | /ex20.py | 1,186 | 4.375 | 4 | from sys import argv
# Pass in an argument from command line
script, input_file = argv
# Function to print the whole file
def print_all(f):
print f.read()
# Function to go the the begining of a file
def rewind(f):
f.seek(0)
#Function to print a line of the file that you pass in
def print_a_line(line_count, f):
print line_count, f.readline()
#Open file passed from the command line
current_file = open(input_file)
#Prints some text and print the whole file by passing calling the function that reads the whole file.
print "First let's print the whole file:\n"
print_all(current_file)
#Prints some text and calls the function that allows you to go the the begining of the file.
print "Now let's rewind, kind of like a tape."
rewind(current_file)
#Prints some text and then calls the functions that allow you to print one line of the file by passing the line of the file that you specify
#current line 1
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
#current line 2
current_line = current_line + 1
print_a_line(current_line, current_file)
#current line 3
current_line = current_line + 1
print_a_line(current_line, current_file)
| true |
d6edafab430c4d6585a2edc62ca1336901199f95 | michaelkemp2000/vader | /ex3.py | 1,104 | 4.375 | 4 | # Print the text
print "I will now count my chickens."
# Print test and the sum answer after the comma
print "Hens", 25.645 + 30.5943 / 6
# Print test and the sum answer after the comma
print "Roosters", 100 - 25 * 3 % 4
# Print the text
print "Now I will count the eggs."
# Prints the answer to the sum. Not sure what the % is doing????
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# Print the text
print "Is it true that 3 + 2 < 5-7?"
# checks if total of left sum is less that right some, if so - True, if not false.
print 3 + 2 < 5 - 7
# Print test and the sum answer after the comma
print "What is 3 + 2?", 3+ 2
# Print test and the sum answer after the comma
print "What is 5 - 7?", 5 - 7
#Text
print "Oh, that's why its False."
#Text
print "How about some more."
# Print test and the sum answer after the comma ( this will be boolean)
print "Is it greater?", 5 > -2
# Print test and the sum answer after the comma ( this will be boolean)
print "Is it greater or equal?", 5 >= -2
# Print test and the sum answer after the comma ( this will be boolean)
print "Is it less or equal?", 5 <= -2 | true |
210c5757a96f915bfdcba3d80cda9a7dddae74c1 | miguelgaspar24/BoardgamePrices | /utilities.py | 728 | 4.65625 | 5 | #!/usr/bin/env python
# coding: utf-8
def convert_chars(string):
'''
Converts problematic characters. Usually, tend to be accented vowels.
Takes the following parameters:
string (str): a string where one or more characters raise a UnicodeEncodeError.
Returns a modified string.
'''
if 'â\x80\x93' in string:
string = string.replace('â\x80\x93', '-')
if 'ä' in string:
string = string.replace('ä', 'ä')
if 'ù' in string:
string = string.replace('ù', 'ù')
if 'Å\x8d' in string:
string = string.replace('Å\x8d', 'ō')
if 'Ã\xa0' in string:
string = string.replace('Ã\xa0', 'à')
return string
| true |
ecccdec592c1cccb123c9ab92170438df90e8fed | jeffkt95/ProjectEuler | /problem0005.py | 945 | 4.15625 | 4 | import sys
import os
import math
def main():
highestNumber = 20
maxCheck = highestNumber * 100000000
# Starting with highestNumber, go up by multiples of highestNumber
# e.g. if your highestNumber was 10, check 10, 20, 30, 40, etc.
for numForCheck in range(highestNumber, maxCheck, highestNumber):
#Assume it's evenly divisible by all until proven otherwise
evenlyDivisibleByAll = True
for i in range(highestNumber, 0, -1):
if numForCheck % i != 0:
evenlyDivisibleByAll = False
break
#If you get through all the numbers and evenlyDivisibleByAll is still true,
# then you've found the answer
if evenlyDivisibleByAll:
print(str(numForCheck) + " is evenly divisible by all numbers from 1 to " + str(highestNumber))
return
print("Unable to find any number evenly divisible by all numbers from 1 to " + str(highestNumber))
print("I checked up to " + str(maxCheck))
if __name__ == "__main__":
main()
| true |
60cfdeffffb011a932a51daf21ddfb9d42c50bb4 | gvnaakhilsurya/20186087_CSPP-1 | /cspp1-pratice/m10/biggest Exercise/biggest Exercise/biggest_exercise.py | 1,025 | 4.125 | 4 | #Exercise : Biggest Exercise
#Write a procedure, called biggest, which returns the key corresponding to the entry with the largest number of values associated with it. If there is more than one such entry, return any one of the matching keys.
def biggest(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: The key with the largest number of values associated with it
'''
maxm=0
res=0
for i in aDict:
if type(aDict[i])==list or type(aDict[i])==tuple:
if len(aDict[i]) > maxm:
maxm = len(aDict[i])
res = i
if res==0 and maxm==0:
res=i
maxm=1
return (res,maxm)
def main():
# aDict={}
# s=input()
# l=s.split()
# if l[0][0] not in aDict:
# aDict[l[0][0]]=[l[1]]
# else:
# aDict[l[0][0]].append(l[1])
aDict = {1:[1,2,3],2:[1,5,3,4],4:[8,9,7,8]}
print((biggest(aDict)))
if __name__== "__main__":
main() | true |
f3b2c0443d86d4b7deedc30384e3a0aa7868b4c0 | gvnaakhilsurya/20186087_CSPP-1 | /cspp1-pratice/m3/hello_happy_world.py | 234 | 4.125 | 4 | '''
@author : gvnaakhilsurya
Write a piece of Python code that prints out
the string 'hello world' if the value of an integer
variable, happy,is strictly greater than 2.
'''
HAPPY = int(input())
if HAPPY > 2:
print("hello world")
| true |
68cc3286321708fcf077d10f169acfbe5e326715 | dineshagr/python- | /multiDimentionalLists.py | 641 | 4.40625 | 4 | # this is a one dimentional list
x = [2,3,4,5,6,7,8]
# this is a 2 dimentional list
y = [[5,4], [3,4], [7,9], [2,8]]
# 0 1 0 1 0 1 0 1 these are the individual positions of inner lists
# 0 1 2 3 these are the positions of outer lists
print(y)
print(y[3][1])
# this is a multidimentional list
y = [[[5,4], [3,4]], [[7,9], [2,8,3]], [4,6]]
# 0 1 2 outer lists index
# 0 1 0 1 inner lists index
# 0 1 0 1 0 1 0 1 2 0 1 inner most lists index
print(y[1][1][2]) the output will be three here
| true |
b689d8c576b9731b116d987bb1282437803f63a9 | onatsahin/ITU_Assignments | /Artificial Intelligence/Assignment 2/block_construction_constraint.py | 2,980 | 4.125 | 4 | #Onat Şahin - 150150129 - sahino15@itu.edu.tr
#This code include the Block class and the constraint function that is used for the csp problem.
#This code is imported from csp_str_1.py and csp_str_2.py which create the model and solve the problem.
blocklist = [] #A list that holds block objects. Filled in the other codes.
class Block: #Block class to define blocks
def __init__(self, orientation, top, bottom):
self.orientation = orientation #Vertical of horizontal
self.top = top #Top part of the block in coordinates (block itself if horizontal)
self.bottom = bottom #Bottom part of the block in coordinates (block itself if horizontal)
#For the coordinates, I assumed that the height of a horizontal block is 1 and its width is 6.
#The height of a vertical block is 3 and its width is 2. I put the whole structure in a coordinate system
#where left and downmost point of the structure is the point 0,0
def horizontal_center_check(block, placed): #Checks if the below of a horizontal block's center is filled
return ( (block[2][0] - 1, block[2][1]) in placed ) and ( (block[3][0] - 1, block[3][1]) in placed )
def horizontal_two_over_three_check(block, placed): #Checks if at least 2/3 of a horizontal block's below is filled
count = 0
for piece in block:
if (piece[0] - 1, piece[1]) in placed:
count += 1
return count >= (len(block) / 3 * 2)
def vertical_bottom_check(block_bottom, placed): #Checks if a vertical block's below is filled
return ((block_bottom[0][0]-1, block_bottom[0][1]) in placed) and ((block_bottom[1][0]-1, block_bottom[1][1]) in placed)
#The function below uses the functions above to implement the constraints given in the assignment. Every variable's value
#comes to this function in argv list. The order of this list corresponds to the order of blocks in blocklist
def is_order_valid(*argv):
block_count = len(argv)
list_to_check = []
for i in range(block_count): #For every block
if blocklist[i].bottom[0][0] == 0: #If a block touches the ground, continue since it satisfies the constraints
continue
del list_to_check[:] #clear the checklist
for j in range(block_count):
if argv[j] < argv[i]: #If a block j is placed before the block i, add block j to the checklist
list_to_check = list_to_check + blocklist[j].top
if blocklist[i].orientation == 'h': #Perform horizontal check if the block i is horizontal
if not (horizontal_center_check(blocklist[i].bottom, list_to_check) or horizontal_two_over_three_check(blocklist[i].bottom, list_to_check)):
return False
elif blocklist[i].orientation == 'v': #Perform vertical check if the block i is vertical
if not vertical_bottom_check(blocklist[i].bottom, list_to_check):
return False
return True #If no False is returned, the structure can be built with the given order. Return True.
| true |
41eec34b60ce8f0152543d9464e064039a974cae | sebutz/python101code | /Chapter 4 - Conditionals/conditionals.py | 2,148 | 4.34375 | 4 | # a simple if statement
if 2 > 1:
print("This is a True statement!")
# another simple if statement
var1 = 1
var2 = 3
if var1 < var2:
print("This is also True")
# some else
if var1 > var2:
print("This should not be printed")
else:
print("Ok, that's the good branch")
# -1 -----0 -------1
if var1 < -1:
print("not reachable")
elif var1 < 0:
print("not reachable also")
elif var1 < 1:
print("almost there")
else:
print("at last")
if var1 < -1:
print("not reachable")
elif var1 < 0:
print("not reachable also")
elif var1 <= 1:
print("right there")
else:
print("not reachable ")
# let's make it dynamic
user_says = input("give a price:")
user_says_int = int(user_says)
#simplified
if 0 < user_says_int <= 10:
print("you got the right price, boss")
elif 10 < user_says_int <= 20:
print("that's a lot")
elif user_says_int >= 20:
print("are you nuts?")
else:
print("what?")
# and, or, not
if (user_says_int > 0 and
user_says_int <= 10):
print("good price")
elif user_says_int > 10 and user_says_int < 20:
print("that's a lot")
elif user_says_int >= 20:
print("are you nuts?")
else:
print("what?")
if not False:
print("ola")
x = 4
if x != 2:
print("boom")
else:
print("kboom")
# in list checking
my_list = [1, 2, 3, 4]
x = 10
if x in my_list :
print("gotcha")
else:
print("keep looking")
# checking for Nothing
# different types (they are evaluated differently !!!!)
empty_list = []
empty_map = {}
empty_string = ""
nothing = None
# for ex:
print(empty_list == None) # False
if empty_list == []:
print("empty list")
else:
print("something")
# same as
if empty_list:
print(empty_list)
else:
print("something")
if not empty_list:
print("something")
else:
print("empty")
if not nothing:
print("some value exists")
else:
print("absolutely nothing")
'''
# execute this code only if this program is executed as standalone file
if __name__ == "__main__":
#whatever
'''
| true |
1d76d63c49fba58705754cb77cc6228a3bb891c0 | isaiahb/youtube-hermes-config | /python_publisher/logs/logger.py | 957 | 4.1875 | 4 | """This module creates a logger that can be used by any module to log information
for the user. A new logger is created each time the program is run using a timestamp
to ensure a unique name.
"""
import logging
from datetime import datetime
class Logger():
"""Creates a timestamped log file in the logs/ directory
and prints the systems errors in the log.
"""
def __init__(self):
self.logger = logging.getLogger()
self.logger.setLevel(logging.ERROR)
timestamp = str(datetime.now().strftime("%Y-%m-%d:%H:%M"))
file_title = "logs/" + "log-" + timestamp + ".log"
output_file_handler = logging.FileHandler(file_title)
self.logger.addHandler(output_file_handler)
def log(self, error_message):
"""Log an error message using the logger.
Args:
error_message (str): the error message to print in the log
"""
error_message = str(datetime.now()) + " " + error_message
self.logger.error(error_message)
| true |
c3298fa7e323160b821295148c7e7094e9d47364 | lradebe/simple_programming_problems | /largest_element.py | 219 | 4.1875 | 4 | def largest_element(mylist):
largest_element = 0
for element in mylist:
if element >= largest_element:
largest_element = element
print(largest_element)
largest_element([1, 2, 3, 4, 5])
| true |
0177a475d7829b46e61a98456b99d438e3250bb8 | lradebe/simple_programming_problems | /find_intersection.py | 726 | 4.375 | 4 | def find_intersection(Array):
'''This function takes in a list with two strings \
it must return a string with numbers that are found on \
both list elements. If there are no common numbers between \
both elements, return False'''
first = list(Array[0].split(', '))
second = list(Array[1].split(', '))
string = ''
both = []
for number in first:
if number in second:
both.append(number)
sorted(both)
if len(both) == 0:
return False
for number in both:
if not number == both[-1]:
string += f'{number}, '
else:
string += f'{number}'
print(string)
Array = ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"]
find_intersection(Array)
| true |
361d5439ded4c00ad770618c6c99cf927c8117a7 | Harsh-Modi278/dynamic-programming | /Fibonacci Sequence/solution.py | 534 | 4.3125 | 4 | # Initialising a dictionary to store values of subproblems
memo_dict = {}
def fibonacci(n):
# If answer to the nth fibonacci term is already present in the dictionary, return the answer
if(n in memo_dict):
return(memo_dict[n])
if n <= 2:
return (1)
else:
# Store the answer to the nth fibonacci term to the dictionary for further use
memo_dict[n] = (fibonacci(n-1)+fibonacci(n-2))
return(memo_dict[n])
if __name__ == '__main__':
n = int(input())
print(fibonacci(n))
| true |
ff45174dacc0319d4cb1faa28984f5ed10cf6662 | TheBrockstar/Intro-Python | /src/days-1-2/fileio.py | 468 | 4.1875 | 4 | # Use open to open file "foo.txt" for reading
foo = open('foo.txt', 'r')
# Print all the lines in the file
print(foo.read())
# Close the file
foo.close()
# Use open to open file "bar.txt" for writing
bar = open('bar.txt', 'w')
# Use the write() method to write three lines to the file
bar.write('''"To be, or not to be, that is the question:
Whether 'tis nobler to suffer the sling and arrows of outrageous fortune..."
--Hamlet
''')
# Close the file
bar.close() | true |
ac3e0974a676ea2cec4025da88171668aafa7062 | mukesh25/python-mukesh-codes | /pattern/pattern9.py | 332 | 4.1875 | 4 | # 1
# 2 2
# 3 3 3
# 4 4 4 4
# No. of spaces in every row:(n-i-1)
# which symbol: (i+1)
# How many times: (i+1)
# with in each row same symbol are taken
# inside row symbol are not changing that's why nested loop is not required.
n= int(input('Enter n value: '))
for i in range(n):
print(' '*(n-i-1)+(str(i+1)+' ')*(i+1))
| true |
90ee5d614355f201a11e5a5f8d64dd2632427dac | urskaburgar/python-dn | /naloga-8/calculator/calculator.py | 417 | 4.21875 | 4 | first_number = int(input("Enter the first number: "))
second_number = int(input("Enter the second number: "))
operation = input("Choose operation (+, -, *, /): ")
if operation == "+":
print(first_number + second_number)
elif operation == "-":
print(first_number - second_number)
elif operation == "*":
print(first_number * second_number)
elif operation == "/":
print(first_number / second_number)
| true |
f0eb2816abe1464ed57b923664a5a97737c8f1f0 | dgampel/passion-learn | /examples/binary_search.py | 908 | 4.28125 | 4 | def binary_search(array,first,last,x):
array.sort()
if last >= 1: #base case
middle = 1 + (last - 1) // 2
if array[middle] == x: #if element is present at middle
return middle
if array[middle] > x: #if element is in left half
return binary_search(array,first,middle-1,x)
else: #if element is in right half
return binary_search(array,middle+1,last,x)
else: #if element is not present in array
return -1
array = [1, 21, 14, 3, 2, 18, 10, 3, 47, 7] # test array
x = 10 #test element
first = 0
last = len(array)
answer = binary_search(array,first,last,x)
if answer != -1:
print("Element is present at index", str(answer))
else:
print("Element is not present in array")
| true |
e89644f9ae975b08815394c47a0669ee65627f07 | gopalanand333/Python-Basics | /dictionary-basic.py | 333 | 4.71875 | 5 | #! /usr/bin/env python03
# a dictionary is searchable item with key-value pair
x = {"one": 1, "two":2, "three":3, "four":4,"five":5} # a dictionary
for key in x:
print(key) # this will print the keys
for key, v in x.items():
print('key: {} , value:{}'.format(key, v)) # this will return the key value pair
| true |
cd93ecfa1c20132aa72909ed314b4ba3d2fe177b | blakexcosta/Unit3_Python_Chapter5 | /main.py | 1,208 | 4.3125 | 4 |
def main():
# booleans
number1 = 1
number5 = 5
# boolean values are written as True and False
if (number1 > number5):
print("this statement is true")
else:
print("this statement is false")
# list of comparison operators
# https://education.launchcode.org/lchs/chapters/booleans-and-conditionals/boolean-expressions.html
#len() example
text = "Don't panic"
if(len(text) >= 10):
print("{} has more than 10 character".format(text))
# logic operators (and, or, etc.)
name = "Bob"
if (len(name)>5 and len(name)<10):
print("{} is between 5 and 10 characters".format(name))
else:
print("{} is either less than 5 characters or greater than 10".format(name))
# table of operations for operators
# https://education.launchcode.org/lchs/chapters/booleans-and-conditionals/truth-tables.html
# chained conditionals, (elif)
num = 10
other_num = 20
if num > other_num:
print(num, "is greater than", other_num)
elif num < other_num:
print(num, "is less than", other_num)
else:
print(num, "is equal to", other_num)
if __name__ == "__main__":
main()
| true |
ba025910735dc60863ef5b6525cc20bace3675cb | CAWilson94/MachineLearningAdventures | /ex2/python/iris.py | 2,446 | 4.4375 | 4 | # Charlotte Wilson
# SciKit learn example
# How starting from the original problem data
# can shaped for consumption in scikit-learn.
# importing a dataset
from sklearn import datasets
# data member is an n_sample and n_features array
iris = datasets.load_iris();
digits = datasets.load_digits();
# digits.data accesses the features that can be used to classify the digit samples
# data --> features
# These features each belong to a class
print(iris.data);
print("\n");
print(digits.data);
# digits.target gives ground truth for the data set
# i.e. the number corresponding to each digit we are trying to learn
# target --> class
print("digits target yo!");
print(digits.target);
# Shape of the data arrays
# The data is always a 2d array
# shape(n_samples,n_features)
# Although the original data may have a different shape.
# Each original sample in an image of shape (8,8) can
# be accessed using:
print("\nShape of data arrays \n");
print(digits.images[0]);
###########LEARNING AND PREDICTING#########################
# The task here is to predict, given an image, what digit it represents
# Given samples of each of the ten classes (digits 0-9)
# We fit an ESTIMATOR on each of these, which is able to predict
# the classes to which unseen samples belong
# In scikit-learn: an estimator for classification is a python object that implements the method fit(x,y) and predict(T)
# Estimator for classification --> python object implementing fit(x,y) and predict(T)
# sklearn.svm.SVC is an estimator class that implements support vector classification
# Consider the estimator as a black box for now
from sklearn import svm
# Choosing the paramaters for the model:
# In this case we have selected the value of gamma manually
# Possible to select good values automatically using tools
# Tools for auto selection: grid search, cross validation
# Call our estimator clf, since it is a classifier
# Must now be fitted to the model
# i.e. it must learn from the model
clf = svm.SVC(gamma=0.001, C=100);
# We pas our training set to fit the method
# So we use all images in our dataset bar the last one, as a training set.
# We select this training set with the [:-1] python syntax,
# which produces a new array that contains all but the last entry of digits.data
something = clf.fit(digits.data[:-1], digits.target[:-1]);
print("\nclassifier shit...\n");
print(something);
array = clf.predict(digits.data[:-1])
(array[8]);
| true |
42733c4983449b3967f4b450f35c6b319f8cbd9b | alexgneal/comp110-21f-workspace | /exercises/ex01/hype_machine.py | 273 | 4.15625 | 4 | """Use concantonations to build up strings and print them out using my name."""
__author__ = "730332719"
name: str = input("What is your name? ")
print(name + ", you are awesome!")
print("You're killing it, " + name)
print("Wow, " + name + ", you are an absolute queen!") | true |
617bcc056e3011b6b303ab1c1de87d3e9af49417 | Benneee/PythonTrips | /Assignment_Wk4_Day1_QuadRoots_App.py | 2,135 | 4.34375 | 4 | #The Quadratic Roots Programme
#ALGORITHM
#1 Introduce the program to the user
#2 Give the required instructions to run program appropriately
#3 Request values for a, b, c
#4 Define a variable for the discriminant
#- Solve the discriminant
#- Solve the square root of the discriminant
#- import math module and do the print thingy
#5 Define variables for r1 and r2
#6 Define the conditional statements;
#- discriminant > 0
#- discriminant < 0
#- discriminant == 0
#- Implement the calculation for the two roots when discriminant > 0
#The Program
#1 Introduce the program to the user
greeting = 'welcome to the quadratic roots programme'
print(greeting.title())
#2 Give the required instructions to run program appropriately
instruction = 'please provide values where required'
print(instruction.title())
#3 Request values for a, b, c
a = float(int(input('Please provide a value for a: ')))
b = float(int(input('Please provide a value for b: ')))
c = float(int(input('Please provide a value for c: ')))
#4 Define a variable for the discriminant
d = 'discriminant'
#- Solve the discriminant
d = float(int((b ** 2) - (4 * a * c)))
print('The discriminant is ' + str(d))
#- Solve the square root of the discriminant
#- import math module and do the print thingy
import math
print('The square root of the discriminant is ' + str(math.sqrt(abs(float(d)))))
#The abs function returns the absolute value of d which can be negative depending on the values of a, b and c.
#The python math module sqrt method has a problem with negative values.
#5 Define variables for r1 and r2
r1 = float((-b) + (d) / (2 * a))
r2 = float((-b) - (d) / (2 * a))
#6 Define the conditional statements;
#- discriminant > 0
if d > 0:
print('The equation has two real roots: ' + str(r1) + ' and ' + str(r2))
#- Implement the calculation for the two roots when discriminant > 0
#- discriminant == 0
elif d == 0:
print('The equation has only one real root')
#- discriminant < 0
else:
print('The equation has no real root')
print('Thank you for using this app')
| true |
c76cf6d1d8d193a0f2a9036d06558344caf2f066 | jerthompson/au-aist2120-19fa | /1130-A/0903-primeA.py | 300 | 4.25 | 4 | n = 2
max_factor = n//2
is_prime = True # ASSUME it is prime
for f in range(2, max_factor + 1): # INCLUDE max_factor by adding 1
if n % f == 0:
print(n, "is not prime--it is divisible by", f)
#exit()
is_prime = False
break
if is_prime:
print(n, "is prime")
| true |
f28949cd50fe4a1d5e80c4f0fad20d6172a0531a | hbinl/hbinl-scripts | /Python/C5 - MIPS/T3 - new_power.py | 1,762 | 4.21875 | 4 | """
FIT1008 Prac 5 Task 3
@purpose new_power.py
@author Loh Hao Bin 25461257, Derwinn Ee 25216384
@modified 20140825
@created 20140823
"""
def binary(e):
"""
@purpose: Returns a binary representation of the integer passed
@parameter: e - The integer to be converted to binary
@precondition: A positive integer value is passed
@postcondition: A list of integers representing binary value of the integer,
@Complexity:
Best Case: O(1) if e is 0
Worst Case: O(e + log e) because the algorithm cuts e into half in the second loop
"""
if e > 0:
rev_binary = [0] * e
length = 0
while e > 0:
rev_binary[length] = int(e%2)
e = int((e - e%2) / 2)
length += 1
return rev_binary[0:length]
else:
return [0]
def power(b, e):
"""
@purpose: Using a binary list to calculate power of two integers
@param:
b: The base number
e: The exponent
@precondition: A valid positive base and exponent are input
@postcondition: The power of b^e is print out
@Complexity:
Best Case: O(1) if exponent < 0
Worst Case: O( )
"""
if e < 0:
return "Please input positive exponents"
else:
rev_binary = binary(e)
result = 1
idx = len(rev_binary) - 1
while idx >= 0:
result = result * result
if rev_binary[idx]:
result = result * b
idx -= 1
return result
if __name__ == "__main__":
try:
b = int(input("Please input a positive integer: "))
e = int(input("Please input a positive integer: "))
print(power(b,e))
except:
print("Please input a valid positive integer.") | true |
6f5abd237c95b6590f222c0e5c2dbaf1c7243e99 | itsformalathi/Python-Practice | /iteratingdictionery.py | 473 | 4.78125 | 5 | #No method is needed to iterate over a dictionary:
d = {'A': 'Apple', 'B': 'Ball', 'C': 'Cat'}
for Key in d:
print(Key)
#But it's possible to use the method iterkeys():
for key in d.iterkeys():
print(key)
#The method itervalues() is a convenient way for iterating directly over the values:
for val in d.itervalues():
print(val)
#The above loop is of course equivalent to the following one:
for key in d:
print(d[key])
| true |
8beb44bb1abf99b16cc7b4a05f3dca7b6b3f6c93 | derekyang7/WSIB-Coding-Challenge | /code-obfuscation.py | 811 | 4.15625 | 4 | def myfunction():
num = input("Enter string:")
a = ""
b = num
while len(b) > 0:
if len(b) > 0:
c = b[-1]
b = b[:-1]
a += c
else:
break
if a == num:
return True
else:
return False
"""Function that reverses the order of the words in a sentence, but not the words themselves"""
def reverse_sentence(sentence: str) -> str:
# lst = split list by whitespace
reversed_list = lst[::-1]
res = ""
for item in reversed_list:
res += item
res += " "
return res
def reverse_sentence2(sentence: str) -> str:
reversed_list = list(filter(reverse, sentence))
res = ""
for item in reversed_list:
res += item
res += " "
return res
print(myfunction())
| true |
b1e254e649b83072a1ea2a09f3e40d5a7f6b5a5d | siggij91/TileTraveller | /tile_traveller.py | 2,353 | 4.1875 | 4 | ##Project 5 Tile Traveler https://github.com/siggij91/TileTraveller
#Create tile structure and label it
#Append allowable moves to file structure
#N = +1 in second index and S = -1
#E = +1 in first index and W = -1
#Once in new tile, show the allowable moves
#Once player enters 3, 1 show them that they win.
def can_move(current_square):
prt_str = 'You can travel: '
length = len(current_square)
for char in current_square:
if char == 'N' and length == 1:
prt_str += '(N)orth.'
elif char == 'N':
length -= 1
prt_str += '(N)orth or '
if char == 'E' and length == 1:
prt_str += '(E)ast.'
elif char == 'E':
length -= 1
prt_str += '(E)ast or '
if char == 'S' and length == 1:
prt_str += '(S)outh.'
elif char == 'S':
length -= 1
prt_str += '(S)outh or '
if char == 'W' and length == 1:
prt_str += '(W)est.'
elif char == 'W':
length -= 1
prt_str += '(W)est or '
return print(prt_str)
def select_move(current_square, x, y):
loop_continue = True
while loop_continue:
move = str(input('Direction: '))
for char in current_square:
if move.upper() == 'N' and move.upper() == char:
y += 1
loop_continue = False
break
elif move.upper() == 'E' and move.upper() == char:
x += 1
loop_continue = False
break
elif move.upper() == 'S' and move.upper() == char:
y -= 1
loop_continue = False
break
elif move.upper() == 'W' and move.upper() == char:
x -= 1
loop_continue = False
break
else:
print('Not a valid direction!')
return x, y
SQ = [['N','N','N'],
['NES','SW','NS'],
['ES','EW','SW']]
x = 1
y = 1
current_square = SQ[y-1][x-1]
while True:
can_move(current_square)
x, y = select_move(current_square, x, y)
current_square = SQ[y-1][x-1]
if x == 3 and y == 1:
print('Victory!')
break
| true |
4a578dd7fcd9cc12e0a6e28051f5641d2a9c22fe | vijaypal89/algolib | /ds/linkedlist/intro2.py | 593 | 4.125 | 4 | #!/usr/bin/python
import sys
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while temp:
print temp.data,
temp = temp.next
def main():
#create link list and node
llist = LinkedList()
llist.head = Node(1)
second = Node(2)
third = Node(3)
#now combine nodes
llist.head.next = second
second.next = third
llist.printList()
if __name__ == '__main__':
main()
| true |
9114541f1b9aa4b177fafd0ac50ef8b81ce76da0 | AlreadyTakenJonas/pythonBootCamp2021 | /easyExercise_12_regression/easyExercise_12_regression.py | 2,208 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 14 17:20:35 2021
@author: jonas
"""
# IMPORT MODULES
# Handling linear regression
from sklearn.linear_model import LinearRegression
# Handling exponential regression
from scipy.optimize import curve_fit
# Handling numbers and arrays
import numpy as np
# Handling plots
from matplotlib import pyplot as plt
# Create some data to fit and plot
dummyData = { "x": np.array([ 0 , 1 , 2 , 3 , 4 ]),
"y": np.array([ 1.11, 2.23, 7.39, 29.96, 49.40]) }
# Perform a linear regression on the data
linearFit = LinearRegression().fit( dummyData["x"].reshape(-1,1),
dummyData["y"] )
# Perform an exponential regression on the data
# Define exponential function
expFct = lambda x, A, b : A*np.exp(b*x)
# Perform the fit
expFit = curve_fit(f = expFct,
# Training Data
xdata = dummyData["x"],
ydata = dummyData["y"],
# Initial values for fitting parameter
p0 = [1, 1])
# Compute the exponential curve to plot the fitting model
# Get sequence of x values in the interval of the training data
expCurve = {"x": np.arange( min(dummyData["x"]), max(dummyData["x"])+0.1, 0.1 )}
# Compute y values
expCurve["y"] = [ expFct(x, expFit[0][0], expFit[0][1]) for x in expCurve["x"] ]
#
# PLOT DATA AND MODELS
#
# Plot data
plt.plot("x", "y",
"o", # Plot the data as scatter plot
data=dummyData,
# Add label for legend and coloring
label="data")
# Plot linear model
plt.plot(dummyData["x"],
# Predict training data with linear model
linearFit.predict( dummyData["x"].reshape(-1,1) ),
# Add label for legend and coloring
label="linear model")
# Plot exponential model
plt.plot("x", "y",
"", # Add empty format string. There is a warning if this parameter is not passed.
data=expCurve,
# Add label for legend and coloring
label="exp model")
# Add legend to the plot
plt.legend()
# Add axis labels
plt.xlabel("x")
plt.ylabel("y")
# Save the plot as an image file
plt.savefig("regression.png") | true |
7736bd8f305be6ea6e633d1fd34a7fe4e3ec33e3 | missweetcxx/fragments | /segments/sorting/d_insert_sort.py | 2,061 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class InsertSort:
"""
Insert Sort
divide list into two lists: sorted one and unsorted one;
each time insert an element from unsorted list into sorted one at correct position;
Complexity: O(n^2) in worst case
Memory: O(1)
"""
@staticmethod
def solution(my_list):
for r in range(1, len(my_list)):
l = r - 1
if my_list[r] < my_list[l]:
temp = my_list[r]
my_list[r] = my_list[l]
l = l - 1
while l >= 0 and my_list[l] > temp:
my_list[l + 1] = my_list[l]
l = l - 1
my_list[l + 1] = temp
return my_list
@staticmethod
def solution_2(my_list):
for r in range(1, len(my_list)):
l = r - 1
point = r
while l >= 0:
if my_list[l] > my_list[point]:
my_list[l], my_list[point] = my_list[point], my_list[l]
point = l
l -= 1
return my_list
@staticmethod
def solution_3(my_list):
for i in range(len(my_list)):
for j in range(1, i + 1)[::-1]:
if my_list[j] < my_list[j - 1]:
my_list[j - 1], my_list[j] = my_list[j], my_list[j - 1]
else:
break
return my_list
@staticmethod
def solution_4(my_list):
for i in range(1, len(my_list)):
cur = my_list[i]
j = i - 1
while j >= 0 and my_list[j] > cur:
my_list[j + 1] = my_list[j]
j = j - 1
my_list[j + 1] = cur
return my_list
@staticmethod
def solution_5(my_list):
for i in range(1, len(my_list)):
cur = my_list[i]
for j in range(0, i):
if my_list[i] < my_list[j]:
my_list = my_list[:i] + my_list[i + 1:]
my_list.insert(j, cur)
return my_list
| true |
25d5e2d5f13b3580b96f8a8496ba1377b28171a6 | missweetcxx/fragments | /segments/binary_tree/binary_tree.py | 1,895 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from segments.binary_tree.node import Node
class BinaryTree(object):
"""
generate binary tree
"""
def __init__(self):
self.root = None
pass
# create a binary tree with nodes
def _add_node(self, val):
# create root node of binary tree
nodeStack = [self.root, ]
# if root node hasn't been created
if self.root is None:
self.root = Node(val)
print("Successfully add root node as {0}!".format(self.root.val))
return
while len(nodeStack) > 0:
# pop node stack
p_node = nodeStack.pop()
# if left child node not exist
if p_node.left is None:
p_node.left = Node(val)
print("Add left node as {0} ".format(p_node.left.val))
return
# if right child node not exist
if p_node.right is None:
p_node.right = Node(val)
print("Add right node as {0} ".format(p_node.right.val))
return
nodeStack.insert(0, p_node.left)
nodeStack.insert(0, p_node.right)
def gen_tree(self, nums):
for x in nums:
self._add_node(x)
# def __init__(self):
# self.root = Node(None)
# self.myQueue = []
#
# def add_node(self, elem):
# node = Node(elem)
# if self.root.val is None:
# self.root = node
# self.myQueue.append(self.root)
# else:
# tree_node = self.myQueue[0]
# if tree_node.left is None:
# tree_node.left = node
# self.myQueue.append(tree_node.left)
# else:
# tree_node.right = node
# self.myQueue.append(tree_node.right)
# self.myQueue.pop(0)
| true |
3db4db9c93004441a249355b1a923a8439e78aa8 | jgerity/talks | /2016/computing_workgroup/intro-to-python/firstclassfunctions_example.py | 1,431 | 4.59375 | 5 | #!/usr/bin/env python
def makeAddFunction(x):
"""
This function represents breaking the operation x+y into two steps, by
returning a function F(y) that "knows" what value of x to use. In more
specific terms, the value of x is stored in the "closure" of the function
that is created.
"""
def newFunc(y):
""" This function 'carries' knowledge about x with it """
return x+y
# Having defined newFunc, let's spit it out to whoever wants it
# Notice that we are *not* calling newFunc with parentheses
return newFunc
addOne = makeAddFunction(1)
addTwo = makeAddFunction(2)
print(addOne(1)) # 1 + 1 = 2
print(addOne(2)) # 1 + 2 = 3
print(addTwo(1)) # 2 + 1 = 3
print(addTwo(2)) # 2 + 2 = 4
def addManyTimes(addFunc):
"""
We can even pass functions as arguments to other functions. This function
calls the given function with the arguments [0,1,...,10]
"""
for num in range(0, 11):
print("addManyTimes: Adding %i, result is %i" % (num, addFunc(num)))
addManyTimes(addOne) # Notice that we're not calling addOne here, either
addManyTimes(addTwo)
# Python has a special type of function called a lambda that allows us to
# define a short function in-line
addManyTimes(lambda y: 3+y)
# Here, the lambda expression is a function that takes one argument (y) and
# returns the result of 3+y. This lambda is equivalent to makeAddFunction(3)
| true |
0062eb73333fbb36791f164a7d3743691eb36490 | vbanurag/python_set1 | /set_1/Ques_2.py | 687 | 4.125 | 4 | a=[1,1,2,3,5,8,13,21,34,55,98]
#part 1
#prints all elements of the list which are less than 5
print "\nThe no. are less than 5 is : ",[x for x in a if x<5]
#part 2
#print a seperate list and stored a no which is less than 5
new_a=[]
for x in a:
if x<5:
new_a.append(x)
print "\n New list is ",new_a
#part 3
#part 2 convert in one line code
new_single_line=[]
[new_single_line.append(x) for x in a if x<5]
print "\n New list using list comprehension is ",new_single_line
#part 4
#user input of number x and prints all elements which are less than that the orignal list
user_num=int(raw_input("\nEnter a number : "))
for x in a:
if user_num>x:
print x
| true |
aed55c61659e5efbc2c9330ca54947651c00bb67 | KareliaConsolidated/CodePython | /Basics/08_Functions.py | 1,431 | 4.125 | 4 | # Create variables var1 and var2
var1 = [1, 2, 3, 4]
var2 = True
# Print out type of var1
print(type(var1))
# Print out length of var1
print(len(var1))
# Convert var2 to an integer: out2
out2 = int(var2)
# Create lists first and second
first = [11.25, 18.0, 20.0]
second = [10.75, 9.50]
# Paste together first and second: full
full = first + second
# Sort full in descending order: full_sorted
full_sorted = sorted(full, reverse=True)
# Print out full_sorted
print(full_sorted)
# string to experiment with: place
place = "poolhouse"
# Use upper() on place: place_up
place_up = place.upper()
# Print out place and place_up
print(place)
print(place_up)
# Print out the number of o's in place
print(place.count("o"))
# Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Print out the index of the element 20.0
print(areas.index(20.0))
# Print out how often 9.50 appears in areas
print(areas.count(9.50))
# append(), that adds an element to the list it is called on,
# remove(), that removes the first element of a list that matches the input, and
# reverse(), that reverses the order of the elements in the list it is called on.
# Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Use append twice to add poolhouse and garage size
areas.append(24.5)
areas.append(15.45)
# Print out areas
print(areas)
# Reverse the orders of the elements in areas
areas.reverse()
# Print out areas
print(areas) | true |
23ce14c416b32d4aa28e7c342c9ab201b8f640df | KareliaConsolidated/CodePython | /Basics/49_Functions_Ex_09.py | 312 | 4.25 | 4 | # Write a function called multiply_even_numbers. This function accepts a list of numbers and returns the product all even numbers in the list.
def multiply_even_numbers(li):
total = 1
for num in li:
if num % 2 == 0:
total *= num
return total
print(multiply_even_numbers([1,2,3,4,5,6,7,8,9,10])) # 3840
| true |
873d59c466d5d1b9820cfb3ce30d8fce24f74876 | KareliaConsolidated/CodePython | /Basics/17_Conditional_Statements.py | 1,008 | 4.25 | 4 | # Conditional logic using if statements represents different paths a program can take based on some type of comparison of input.
name = "Johny Stark"
if name == "Johny Stark":
print("Hello, " +name)
elif name == "John Fernandes":
print("You are not authorized !" +name)
else:
print("Calling Police Now !")
# In Python, all conditional checks resolve to True or False
x = 1
x is 1 # True
x is 0 # False
# We can call values that will resolve to True "truthy", or values that will resolve to False "falsy".
# Besides False conditional checks, other things that are naturally falsy include: empty objects, empty strings, None, and Zero.
# is vs "=="
# In Python, "==" and "is" are very similar comparators, however they are not the same.
a = 1
a == 1 # True
a is 1 # True
a = [1,2,3] # A List of Numbers
b = [1,2,3]
a == b # True # Checking, if values are the same.
a is b # False # Checking, if values are stored in the same place in memory.
# "is" is only truthy, if the variables reference the same item in memory. | true |
4dac05e28d6efd9441100f9d70a9f61318e8bb65 | KareliaConsolidated/CodePython | /Basics/21_Loops.py | 613 | 4.34375 | 4 | # In Python, for loops are written like this:
for item in iterable_object:
# do something with item
# An iterable object is some kind of collection of items, for instance; a list of numbers, a string of characters, a range etc.
# item is a new variable that can be called whatever you want
# item references the current position of our iterator within the iterable. It will iterate over(run through) every item of the collection and then go away when it has visited all items.
for num in range(1,8):
print(num)
for letter in "coffee":
print(f"{letter}" * 10)
# A Range is just a slice of the number line. | true |
f6f144ae9939c97e2f3ee45dff82029100277512 | KareliaConsolidated/CodePython | /Basics/166_Python_Ex_27.py | 443 | 4.21875 | 4 | # nth
# Write a function called nth, which accepts a list and a number and returns the element at whatever index is the number in the list. If the number is negative, the nth element from the end is returned.
# You can assume that number will always be between the negative value of the list length, and the list length minus 1
def nth(lst, ind):
return lst[ind]
print(nth(['a','b','c','d'], 1)) # 'b'
print(nth(['a','b','c','d'], -2)) # 'c' | true |
84dea473a9911b96684c54d1f339a442ecac41a6 | KareliaConsolidated/CodePython | /Basics/158_Python_Ex_19.py | 400 | 4.25 | 4 | # Vowel Count
# Write a function called vowel_count that accepts a string and returns a dictionary with the keys as the vowels and values as the count of times that vowel appears in the string.
def vowel_count(string):
lower_string = string.lower()
return {letter:lower_string.count(letter) for letter in lower_string if letter in 'aeiou'}
print(vowel_count('awesome')) # {'a': 1, 'e': 2, 'o': 1} | true |
c06f926ba0c3bf416e403eed81a0497605ab1eeb | KareliaConsolidated/CodePython | /Basics/160_Python_Ex_21.py | 781 | 4.375 | 4 | # Write a function called reverse_vowels. This function should reverse the vowels in a string. Any characters which are not vowels should remain in their original position. You should not consider "y" to be vowel.
def reverse_vowels(s):
vowels = 'aeiou'
string = list(s)
i, j = 0, len(s) - 1
while i < j:
if string[i].lower() not in vowels:
i += 1
elif string[j].lower() not in vowels:
j -= 1
else:
string[i], string[j] = string[j], string[i]
i += 1
j -= 1
return "".join(string)
print(reverse_vowels('Hello!')) # Hello!
print(reverse_vowels('Tomatoes!')) # Tomatoes!
print(reverse_vowels('Reverse Vowels In A String!')) # Reverse Vowels In A String!
print(reverse_vowels('aeiou')) # ueioa
print(reverse_vowels('why try, shy fly?')) # why try, shy fly? | true |
bbbb95519e1f58642b25b4642b7ef20bc0bbbf05 | neoguo0601/DeepLearning_Python | /Python_basic/python_basic/python_basic_1.py | 2,066 | 4.5 | 4 | days = 365
print(days)
days = 366
print(days)
#Data Types
#When we assign a value an integer value to a variable, we say that the variable is an instance of the integer class
#The two most common numerical types in Python are integer and float
#The most common non-numerical type is a string
str_test = "China"
int_test = 123
float_test = 122.5
print(str_test)
print(int_test)
print(float_test)
print(type(str_test))
print(type(int_test))
print(type(float_test))
str_eight = str(8)
print (str_eight)
print (type(str_eight))
eight = 8
str_eight_two = str(eight)
str_eight = "8"
int_eight = int(str_eight)
int_eight += 10
print (type(int_eight))
str_test = 'test'
str_to_int = int(str_test)
"""
Addition: +
Subtraction: -
Multiplication: *
Division: /
Exponent: **
"""
china=10
united_states=100
china_plus_10 = china + 10
us_times_100 = united_states * 100
print(china_plus_10)
print(us_times_100)
print (china**2)
#LIST
months = []
print (type(months))
print (months)
months.append("January")
months.append("February")
print (months)
months = []
months.append(1)
months.append("January")
months.append(2)
months.append("February")
print (months)
temps = ["China", 122.5, "India", 124.0, "United States", 134.1]
countries = []
temperatures = []
countries.append("China")
countries.append("India")
countries.append("United States")
temperatures.append(30.5)
temperatures.append(25.0)
temperatures.append(15.1)
print (countries)
print (temperatures)
china = countries[0]
china_temperature = temperatures[1]
print (china)
print (china_temperature)
int_months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
length = len(int_months) # Contains the integer value 12.
print (length)
int_months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
index = len(int_months) - 1
last_value = int_months[index] # Contains the value at index 11.
print (last_value)
print (int_months[-1])
#Slicing
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"]
# Values at index 2, 3, but not 4.
two_four = months[2:4]
print (two_four)
three_six = months[3:]
print (three_six)
| true |
d78a38eb6e954225d81984b05cd5cc782b5b93b8 | bitlearns/TurtleGraphics | /Assignment14_RegularPolygonsWithTurtleGraphics.py | 2,672 | 4.9375 | 5 | #Program Description: The following program will use turtle graphics to draw
#polygons based on the user's input of how many sides it will have.
#Author: Madeline Rodriguez
#Imports turtle graphics and random
from turtle import *
import random
#The sides function will take in the user's input of number of sides and check to
#see if it is more than 3 or less than 3
def main():
numSides = int(input('Enter the number of sides, less than 3 to exit: '))
#This loop will call the polygon function if the number of sides is greater
#than 3, if not it will display a thank you message
while numSides >= 3:
polygon(numSides)
numSides = int(input('Enter the number of sides, less than 3 to exit: '))
else:
print('Thanks for using the polygon generator program.')
#The polygon function will calculate the polygon's side length and border width
#using the number of sides inputted along with the line(border) and fill(shape)
#color
def polygon(x):
#Calculates the polygon's side length
sidelength = 600/x
# Specify the colors list to choose the line color and fill color.
colors = ['coral', 'gold', 'brown', 'red', 'green', 'blue', 'yellow',
'purple', 'orange', 'cyan', 'pink', 'magenta', 'goldenrod']
#Randomly selects the color of the fill(shape)
shapecolor = random.choice(colors)
#Randomly selects the color of the fill(border)
bordercolor = random.choice(colors)
#Calculates the size of the border width
bordersize = (x%20) + 1
#Calls the makePolygon function to draw the shape
makePolygon(x, sidelength, bordercolor, bordersize, shapecolor)
# The makePolygon function draws a polygon with the number of sides,
# side length, border color, border width, and fill color as specified.
def makePolygon (sides, length, borderColor, width, fillColor):
#Clears the window for any previous drawing
clear()
#Calculates the angles of the polygon
angle = 360/sides
#Gives the the shape of the turtle to be a turtle
shape("turtle")
#Assigns the pen it's color
pencolor(borderColor)
#Assigns the color that the shape will be fill in with
fillcolor(fillColor)
#Assigns the pen it's width size
pensize(width)
#Using the length and angle sizes specified it will begin to draw the shape
begin_fill()
while True:
if sides != 0:
forward(length)
left(angle)
sides -= 1
else:
break
end_fill()
#Displays to user what the program will create
print('This program will draw a polygon with 3 or more sides.' + '\n')
#Call the main function
main()
| true |
a64fee29b65474879949c905b005046e61298a8e | Isaac-Tait/Deep-Learning | /Python/scratchPad4.py | 893 | 4.15625 | 4 | # Exponent functions
def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
print(raise_to_power(3, 2))
# 2D list
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10]
]
print(number_grid[2][2])
print("It is time to move on to nested for loops!")
# Nested for loop
for row in number_grid:
for element in row:
print(element)
# A translator that dislikes vowels and prefers the letter "G"
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "G"
else:
translation = translation + "g"
else:
translation = translation + letter
return translation
print(translate(input("Enter a phrase: ")))
| true |
e5dfd182fe3810d77335f56d8d73ff6d26603be0 | paulram2810/Python-Programs | /armstrong.py | 265 | 4.125 | 4 | num = eval(input("Enter number to check for armstrong : "))
x = num
flag = 0
while x!=0 :
temp = x%10
flag = flag+(temp**3)
x = x//10
if flag==num:
print(num," is an armstrong number.")
else:
print(num," is not an armstrong number.")
| true |
3be02701f737d06284c9a26f1c719cdab2c721d1 | bmlegge/CTI110 | /P3T1_AreasOfRectangles_Legge.py | 737 | 4.15625 | 4 | #CTI-110
#P3T1: Areas of Rectangles
#Bradley Legge
#3/3/2018
print("This program will compare the area of two rectangles")
recOneLength = float(input("Enter the length of rectangle one: "))
recOneWidth = float(input("Enter the width of rectangle one: "))
recOneArea = float(recOneLength * recOneWidth)
recTwoLength = float(input("Enter the length of rectangle two: "))
recTwoWidth = float(input("Enter the width of rectangle two: "))
recTwoArea = float(recTwoLength * recTwoWidth)
if recOneArea == recTwoArea:
print("The rectangles have the same area.")
elif recOneArea > recTwoArea:
print("Rectangle one has the greater area.")
elif recOneArea < recTwoArea:
print("Rectangle two has the greater area.")
| true |
f4757eb581419b63362df05cbdebee759ec302d3 | flerdacodeu/CodeU-2018-Group7 | /lizaku/assignment2/Q2.py | 2,129 | 4.15625 | 4 | from Q1 import Node, BinaryTree, create_tree
def find_lca(cur_node, node1, node2):
result = find_lca_(cur_node, node1, node2)
if not isinstance(result, int):
raise KeyError('At least one of the given values is not found in the tree')
return result
def find_lca_(cur_node, node1, node2):
# This algorithm is designed as follows: I start with the root and
# try to check whether one node is present in the left subtree and other node
# is present in the right subtree. If this is the case, then the current node
# is LCA. If the traversal reaches the leaves and the value is not found, the recursion step
# returns None. If required values are not found in the right subtree,
# Then LCA should be found in the left subtree, and I start to inspect it.
# Otherwise, I start to inspect the right subtree.
if cur_node is None:
#return None
raise KeyError('At least one of the given values is not found in the tree')
if cur_node.value == node1 or cur_node.value == node2: # reached one of the values
#print(cur_node.value, cur_node.left.value, cur_node.right.value)
return cur_node
try:
left_subtree = find_lca_(cur_node.left, node1, node2)
except KeyError:
left_subtree = None
#return None
try:
right_subtree = find_lca_(cur_node.right, node1, node2)
except KeyError:
right_subtree = None
#return None
if left_subtree is not None and right_subtree is not None: # found the node which has both values in the subtrees -- lca
return cur_node.value
elif right_subtree is None and left_subtree is not None:
return left_subtree
elif left_subtree is None and right_subtree is not None:
return right_subtree
else:
raise KeyError('At least one of the given values is not found in the tree')
if __name__ == '__main__':
data = [7, 3, 2, 1, 6, 5, None, None, 4, None, None, None, 8, None, None]
tree = BinaryTree()
tree.root = create_tree(data)
#tree.print_tree(tree.root)
print(find_lca(tree.root, 12, 11))
| true |
b93f8ec573992e03b78f890fc8218ff4404ed435 | flerdacodeu/CodeU-2018-Group7 | /EmaPajic/assignment4/assignment4.py | 1,923 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: EmaPajic
"""
def count_islands(rows,columns,tiles):
"""
I am assuming that we can change tiles (set some values to false).
If we couldn't do that, we could just make another matrix where
we would store flags so that we don't visit same tile twice.
In this function we are just going through matrix and if we find a part of island
we call function find_all_parts_of island to set all parts of that island to false
"""
numOfIslands = 0
for i in range(0,rows):
for j in range(0,columns):
if tiles[i][j] == True:
numOfIslands += 1
find_all_parts_of_island(rows,columns,i,j,tiles)
return numOfIslands
def valid_index(rows,columns,i,j):
# check if index is out of range
return not (i < 0 or i >= rows or j < 0 or j >= columns)
def find_all_parts_of_island(rows,columns,i,j,tiles):
#I am using dfs to find all connected tiles to one we found before we called this function from count_islands
tiles[i][j] = False
for move in [-1,1]:
if valid_index(rows,columns,i+move,j):
if tiles[i+move][j] == True:
find_all_parts_of_island(rows,columns,i+move,j,tiles)
if valid_index(rows,columns,i,j+move):
if tiles[i][j+move] == True:
find_all_parts_of_island(rows,columns,i,j+move,tiles)
def main():
#main class if we want to test something that is not in the tests
rows = int(input())
columns = int(input())
tiles = [0] * rows
for i in range(0,rows):
tiles[i] = [0] * columns
for i in range(0,rows):
for j in range(0,columns):
tmp = int(input())
if tmp == 0:
tiles[i][j] = False
else:
tiles[i][j] = True
num = count_islands(rows,columns,tiles)
print(num)
| true |
c318ca570f5bffa95560fc13a6db502472133dc5 | oskarmampe/PythonScripts | /number_game/program.py | 538 | 4.15625 | 4 | import random
print("----------------------------------")
print(" GUESS THAT NUMBER GAME ")
print("----------------------------------")
the_number = random.randint(0, 100)
while True:
guess_text = input("Guess a number between 0 and 100: ")
guess = int(guess_text)
if the_number > guess:
print("Your guess of {0} was too LOW.".format(guess))
elif the_number < guess:
print("Your guess of {0} was too HIGH.".format(guess))
else:
print("Congratulations! You won!")
break
| true |
3049443c9a563cdcecd50556ecd1aeb8e1db0e6b | StefGian/python-first-steps | /maxOfThree.py | 370 | 4.40625 | 4 | #Implement a function that takes as input three variables,
#and returns the largest of the three. Do this without using
#the Python max() function!
a = int(input("Type the first number: "))
b = int(input("Type the second number: "))
c = int(input("Type the thrid number: "))
if a>b and a>c:
print(a)
elif b>a and b>c:
print(b)
else:
print(c)
| true |
412a520a55edcaa026306556a477ff4fe01bed4a | Akhichow/PythonCode | /challenge.py | 632 | 4.125 | 4 | vowels = set(["a", "e", "i", "o", "u"])
print("Please enter a statement")
sampleText = input()
finalSet = set(sampleText).difference(vowels)
print(finalSet)
finalList = sorted(finalSet)
print(finalList)
# [' ', 'I', 'c', 'd', 'm', 'n', 'r', 's']
# My solution -
# finalList = []
#
# while True:
# print("Please enter a statement")
# text = input()
#
# for alphabet in text:
# if (alphabet not in vowels) and (alphabet != " "):
# finalList.append(alphabet)
#
# print(sorted(finalList))
# print()
# break
# ['I', 'c', 'c', 'd', 'd', 'm', 'n', 'r', 's']
| true |
60d00c0a404a950786d0f83affd95e35f8fe00f3 | JasmineEllaine/fit2004-algs-ds | /Week 1/Tute/8-problem.py | 623 | 4.25 | 4 | # Write code that calculates the fibonacci numbers iteratively.
# F(1) == F(2) == 1
def fibIter(x):
seq = [1, 1]
# Return fib(x) immediately if already calculated.
if (x <= len(seq)):
return 1
for i in range(1, x-1):
seq.append(seq[i]+ seq[i-1])
return seq[-1]
"""
Time complexity:
O(n)
Space complexity:
O(1)
"""
# Write code that calculates the fibonacci numbers recursively.
def fibRec(x):
if (x == 0):
return 0
elif (x == 1):
return 1
else:
return fibRec(x-1) + fibRec(x-2)
"""
Time complexity:
O(2^n)
Space complexity:
O(n)
""" | true |
1693a547bd0278f0675a13ee34e1fa63ee86a00c | davidcotton/algorithm-playground | /src/graphs/bfs.py | 1,790 | 4.1875 | 4 | """Breadth-First Search
Search a graph one level at a time."""
from collections import deque
from typing import List, Optional
from src.graphs.adjacencylist import get_graph
from src.graphs.graph import Graph, Vertex
def bfs_search(start: Vertex, goal: Vertex) -> Optional[List[Vertex]]:
"""Search for the goal vertex within a graph in a breadth-first manner.
Graph must have no loops and no edge weights to work.
Returns the path as a list of vertices if goal is found else None."""
frontier: deque[Vertex] = deque([start])
paths: deque[List] = deque([[]])
while frontier:
vertex = frontier.popleft()
path = paths.popleft()
path.append(vertex.key())
if vertex is goal:
return path
for neighbour in vertex.neighbours():
frontier.append(neighbour)
paths.append(path[:])
return None
def bfs(root: Vertex) -> List[List]:
"""Search a graph via Breadth-First-Search from a vertex.
Returns a tree describing every vertex that is reachable from the source vertex.
"""
frontier: deque[Vertex] = deque([root])
paths: deque[List] = deque([[]])
while frontier:
vertex = frontier.popleft()
path = paths.popleft()
path.append(vertex.key())
if vertex.neighbours():
for neighbour in vertex.neighbours():
frontier.append(neighbour)
paths.append(path[:])
else:
paths.append(path)
return list(paths)
if __name__ == '__main__':
graph: Graph = get_graph()
vertices: List[Vertex] = graph.vertices()
shortest_path = bfs_search(vertices[0], vertices[4])
print('shortest path', shortest_path)
all_paths = bfs(vertices[0])
print('all paths', all_paths)
| true |
660aea75a1024b16e007b6dcdef4aca6cdf6ae77 | blane612/for_loops | /tertiary.py | 470 | 4.40625 | 4 | # -------------------- Section 3 -------------------- #
# ---------- Part 1 | Patterns ---------- #
print(
'>> Section 3\n'
'>> Part 1\n'
)
# 1 - for Loop | Patterns
# Create a function that will calculate and print the first n numbers of the fibonacci sequence.
# n is specified by the user.
#
# NOTE: You can assume that the user will enter a number larger than 2
#
# Example Output
#
# >> size... 6
#
# 1, 1, 2, 3, 5, 8
#
# Write Code Below #
| true |
d6192566a5778e4c5ec9536c5f30db470bca7439 | WeeJang/basic_algorithm | /ShuffleanArray.py | 1,260 | 4.28125 | 4 | #!/usr/bin/env python2
#-*- coding:utf-8 -*-
"""
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();
// Resets the array back to its original configuration [1,2,3].
solution.reset();
// Returns the random shuffling of array [1,2,3].
solution.shuffle();
"""
import copy
import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.origin = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.origin
def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
nums_c = copy.deepcopy(self.origin)
l = len(nums_c)
for i in range(l):
j = random.randint(0,l-1)
nums_c[i],nums_c[j] = nums_c[j],nums_c[i]
return nums_c
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
| true |
023e609eb767a6e0ec588b79fd38567e82c84225 | JakeJaeHyongKim/I211 | /lab 3-4(list comp, combined number in list).py | 549 | 4.15625 | 4 | #lab practical example
#appeal only what I need as output, #1= sort it
nums = ["123", "321", "435", "2468"]
num_order = [num for num in nums if [digit for digit in num] == \
sorted([digit for digit in num])]
print(num_order)
lst1 = [1,2,3]
lst2 = sorted([1,2,3])
#2= only odd numbers as output
nums = ["123", "321", "435", "2468"]
num_odd = [num for num in nums if [digit for digit in num if int(digit) % 2 == 1] == \
sorted([ digit for digit in num if int(digit) % 2 == 1 ])]
print(num_odd)
| true |
5bf0db55a5bc7ca89f4e02cc1d0bbf195629bf45 | JakeJaeHyongKim/I211 | /lab 3-3(list comprehension, word to upper case).py | 378 | 4.1875 | 4 | #word list comprehension
#if word contains less than 4 letters, append as upper case
#if not, leave it as it is
words= ["apple", "ball", "candle", "dog", "egg", "frog"]
word = [i.upper() if len(i) < 4 else i for i in words]
#not proper: word = [word.upper() if len(words) < 4 else word for word in words]
#learn how to take only word less than 4 letters
print(word)
| true |
6168e7579f4d014b666e617f5ff9869cea0d68b4 | mayanksh/practicePython | /largestarray.py | 521 | 4.34375 | 4 | #def largest(array, n):
# max = array[0] #initialize array
# for i in range (1, n):
# if array[i] > max:
# max = array[i]
# return max
#array = [1,2,3,4,5]
#n = len(array)
#answer = largest(array, n)
#print("largest element is: " , answer)
arr=int(input('Enter the element of an array:')
n = len(arr)
def largest(arr,n):
max = arr[0]
for i in range(1, n):
if arr[i] > max:
max = arr[i]
return max
Ans = largest(arr,n)
print ("Largest in given array is",Ans)
| true |
617e98aa40ff5d01a7c2e83228c011705de0b928 | timlindenasell/unbeatable-tictactoe | /game_ai.py | 2,347 | 4.3125 | 4 | import numpy as np
def minimax(board, player, check_win, **kwargs):
""" Minimax algorithm to get the optimal Tic-Tac-Toe move on any board setup.
This recursive function uses the minimax algorithm to look over each possible move
and minimize the possible loss for a worst case scenario. For a deeper understanding
and examples see: 'Wikipedia <https://en.wikipedia.org/wiki/Minimax>'_.
:param board: 3x3 numpy ndarray where 0 is empty, 1 is X, 2 is O.
:param player: Determines player: 1 if X, 2 if O.
:param check_win: Function that takes a 'board' and returns: 0 if stale, 1 if X won, 2 if O won.
:param kwargs: Used in the recursion to pass the last move made.
:return: 'score' and index of optimal Tic-Tac-Toe 'move' given a 3x3 board.
:rtype: float, tuple (int, int)
"""
EMPTY = 0
STALE = 0
WIN = 1
PLAYER_X = 1
PLAYER_O = 2
assert isinstance(board, np.ndarray) and board.shape == (3,3), 'board must be a (3,3) numpy.ndarray'
assert player is PLAYER_X or PLAYER_O, 'player must be an int 1 (X) or 2 (O).'
# Get the constant integer value of the opponent.
opponent = PLAYER_X if player == PLAYER_O else PLAYER_O
# Return correct reward if there's a winner.
winner = check_win(board)
if winner == player:
board[kwargs['last_move']] = EMPTY
return WIN
elif winner == opponent:
board[kwargs['last_move']] = EMPTY
return -WIN
move = -1
score = float('-inf')
# Get indices of available moves.
available_moves = np.where(board == EMPTY)
am_indices = list(zip(*available_moves))
# Try each move
for move_index in am_indices:
# Make copy of current board grid.
board_copy = board
# Make move on copy
board_copy[move_index] = player
move_score = -minimax(board_copy, opponent, check_win, last_move=move_index)
if move_score > score:
score = move_score
move = move_index
if move == -1:
board[kwargs['last_move']] = EMPTY
return STALE
# If the keyword-argument is not found, it must be the last recursion and
# should therefore return the best move and its score.
try:
board[kwargs['last_move']] = EMPTY
except KeyError:
return score, move
return score | true |
167b3a56792d0be21f40e0e8d2208fd7943ccddc | Vibhutisavaliya123/DSpractice | /DS practicel 6.py | 1,624 | 4.4375 | 4 | P6#WAP to sort a list of elements. Give user the
option to perform sorting using Insertion sort,
Bubble sort or Selection sort.#
Code:Insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
# Driver code to test above
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i])
Code : selection sort
def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', end='')
print(alist)
Code:Bubble sort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i]),
| true |
5d7d4bc98ca3fc5b18b7206343bc8da663b29543 | sergady/Eulers-Problems | /Ej1.py | 354 | 4.15625 | 4 |
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
listNums = []
for i in range(1000):
if(i%3 == 0 or i%5 == 0):
listNums.append(i)
sum = 0
for s in (listNums):
sum = sum + s
print(sum)
| true |
076a1ff1556bf140d838529270121ebd99ecc86f | halljm/murach_python | /exercises/ch02/test_scores.py | 660 | 4.375 | 4 | #!/usr/bin/env python3
# display a welcome message
print("The Test Scores program")
print()
print("Enter 3 test scores")
print("======================")
# get scores from the user
score1 = int(input("Enter test score: "))
score2 = int(input("Enter test score: "))
score3 = int(input("Enter test score: "))
total_score = score1 + score2 + score3
# calculate average score
average_score = round(total_score / 3)
# format and display the result
print("======================")
print("Your Scores: " + " " + str(score1) + " " + str(score2) + " " + str(score3))
print("Total Score: ", total_score,
"\nAverage Score:", average_score)
print() | true |
c2c2bf4bcf47b7a4bc15bbf0b333ff6fe52eda3b | jhertzberg1/bmi_calculator | /bmi_calculator.py | 1,364 | 4.375 | 4 | '''
TODO
Greeting
Create commandline prompt for height
Create commandline prompt for weight
Run calculation
Look up BMI chart
Print results
'''
def welcome():
print('Hi welcome to the BMI calculator.')
def request_height():
height = 0
return height
def request_weight():
'''Commandline user input for weight
Returns:
int: Value representing user inputed weight as an int.
'''
while True:
try:
weight = int(input('What is your weight in pounds? >'))
break
except ValueError:
print('That is not a number')
return weight
def calculate_bmi(height_in_inches, weight_in_pounds):
bmi = 23
# TODO consider your units
return bmi
def look_up_word(bmi): # TODO fix word
if bmi >= 30:
return 'Obese'
if bmi >= 25:
return 'Overweight'
if bmi >= 19:
return 'Normal weight'
return 'Under weight'
def print_results(bmi, word):
'''Prints the results of your BMI.
Args:
bmi (int): calculated body mass index score
word (str):
'''
print(word)# look up string formatting
if __name__ == '__main__':
welcome()
height = request_height()
weight = request_weight()
print(weight)
bmi = calculate_bmi(height, weight)
word = look_up_word(bmi)
print_results(bmi, word)
| true |
7df861ce3467cb871fce042f17a4b839f2193379 | Liam-Hearty/ICS3U-Unit5-05-Python | /mailing_address.py | 1,981 | 4.21875 | 4 | #!/usr/bin/env python3
# Created by: Liam Hearty
# Created on: October 2019
# This program finds your mailing address.
def find_mailing_address(street, city, province, postal_code, apt=None):
# returns mailing_address
# process
mailing_address = street
if apt is not None:
mailing_address = apt + "-" + mailing_address
mailing_address = mailing_address + "\n" + city + " " + province + " " \
+ postal_code
return mailing_address
def main():
# this function gets info from user.
try:
# input
aptNum = str(input("Do you have an Apt. Number? Enter y or n: "))
if aptNum == "y":
aptNum_from_user = str(input("Enter your Apt. Number: "))
elif aptNum == "n":
aptNum_from_user = None
else:
print("Please enter a valid response.")
exit()
except ValueError:
print("Please enter a valid response.")
try:
# input
street_address_from_user = str(input("Enter your street address: "))
city_from_user = str(input("Enter what city: "))
province_from_user = str(input("Enter what province: "))
postal_code_from_user = str(input("Enter postal code: "))
print("")
apt = aptNum_from_user
street = street_address_from_user
city = city_from_user
province = province_from_user
postal_code = postal_code_from_user
# call functions
if apt is not None:
mailing_address = find_mailing_address(street, city, province,
postal_code, apt)
else:
mailing_address = find_mailing_address(street, city, province,
postal_code)
# output
print(mailing_address)
except ValueError:
print("Please enter a valid response.")
if __name__ == "__main__":
main()
| true |
cb7e966781a96121035c9489b410fcc1ace84537 | yashaswid/Programs | /LinkedList/MoveLastToFirst.py | 1,325 | 4.28125 | 4 | # Write a function that moves the last element to the front in a given Singly Linked List.
# For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4
class Node:
def __init__(self,val):
self.data=val
self.next=None
class Linkedlist:
def __init__(self):
self.head = None
def insert(self,val):
temp=Node(val)
temp.next=self.head
self.head=temp
def print(self):
temp=self.head
while (temp):
print(temp.data)
temp=temp.next
def move(self):
temp=self.head
pre=self.head
# can be done in two ways
# while(temp.next is not None): first method
# pre=temp
# temp=temp.next
# value=temp.data
# pre.next=None
# li.insert(value)
while(temp.next is not None):
# second method
pre=temp
temp=temp.next
pre.next = None
temp.next=self.head
self.head=temp
https://33souththird.activebuilding.com/
li =Linkedlist()
li.insert(6)
li.insert(5)
li.insert(4)
li.insert(3)
li.insert(2)
li.insert(1)
li.print()
print("Removing the duplicate values")
li.move()
li.print()
| true |
4e35112282fbaccdf62d4aea0ae67bd9446e6117 | Viole-Grace/Python_Sem_IV | /3a.py | 1,688 | 4.28125 | 4 | phones=dict()
def addentry():
global phones
name=raw_input("Enter name of the phone:")
price=raw_input("Enter price:")
phones.update({name:price})
def namesearch(name1):
global phones
for key,value in phones.items():
if name1==key:
print "Found, its price is ",value
def pricesearch(price):
global phones
searchlist=[k for k,v in phones.items() if v == price]
print searchlist[0]
def pricegroup():
global phones
pricelist = list(set(sorted(phones.values()))) #sorts and removes removes duplicate values
print "Phones grouped by same prices are :"
for i in range(len(pricelist)):
all_keys=pricelist[i]
print "Price : ",all_keys,"; Group : ",[k for k,v in phones.items() if v == all_keys]
def remove_entry():
global phones
print "Enter name of phone to delete :"
name=raw_input();
try:
del(phones[name])
print "Updated Dict : \n",phones.keys()
except:
print "Entry not found"
def sortdict():
print sorted(phones.items(),key=lambda x : x[1]) #sort by price, for sorting by name use x[0]
while True:
print "MENU : \n1. Add Entry \n2. Search by name \n3. Search by price \n4. Group by price \n5. Sort \n6. Delete Entry \n7. Exit \nEnter your choice :"
choice=int(input())
if choice==1:
addentry()
elif choice==2:
name=raw_input('Enter name of the phone: ')
namesearch(name)
elif choice==3:
price = (raw_input('Enter price of the phone: '))
pricesearch(price)
elif choice==4:
pricegroup()
elif choice == 5:
sortdict()
elif choice==6:
remove_entry()
else:
break
| true |
571c1db047fd45cf9a73414eb1b246f15ce3f3e3 | hickmanjv/hickmanjv | /CS_4085 Python/Book Examples/coin_toss_demo.py | 401 | 4.25 | 4 | import coin
def main():
# create an object of the Coin class
my_coin = coin.Coin()
# Display the side of the coin that is facing up
print('This side is up: ', my_coin.get_sideup())
# Toss the coin 10 times:
print('I am going to toss the coin 10 times:')
for count in range(10):
my_coin.toss()
print(my_coin.get_sideup())
# Call the main function
main()
| true |
94b508503ea89642213964b07b0980ca81e354e2 | lucaslb767/pythonWorkOut | /pythonCrashCourse/chapter6/favorite_languages.py | 567 | 4.375 | 4 | favorite_languages = {
'jen':'python',
'sarah':'C',
'jon':'ruby'
}
print('Jon favorite language is ', favorite_languages['jon'])
friends = ['sarah']
#using a list to sort a dictionary's value
for name in favorite_languages:
print(name.title())
if name in friends:
print('Hi', name.title(),'I see your favorite language is', favorite_languages[name],'!')
#using the value() method to only loop trhough values
print('the following values have been mentioned:')
for language in favorite_languages.values():
print(language.title()) | true |
6c543e8cfcb156f3265e3bbd01b287af45c318f3 | MariaBT/IS105 | /ex3.py | 961 | 4.34375 | 4 | # Only text describing what will be done
print "I will count my chickens:"
# Print the result of the number of hens
print "Hens", 25 + 30 / 6
# Print the result of the number of roosters
print "Roosters", 100 - 25 * 3 % 4
# Plain text explaining what will be done next
print "Now I will count the eggs:"
# The result of the action above
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# Print a question of plain text
print "Is it true that 3 + 2 < 5 - 7?"
# Print the answer: true or false
print 3 + 2 < 5 - 7
# Print text, followed by an answer
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
# Print text
print "Oh, that's why it's false."
print "How about some more."
# Print text in form of questions, followed by an answer: true og false
print "Is it greater?", 5> -2
print "Is it greater og equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
# Should add ".0" to every number to get more accurate results (floating point numbers)
| true |
879c5858fa8ab9debf0c78559777687fbd2e2d6f | saikrishna-ch/five_languages | /pyhton/NpowerN.py | 252 | 4.28125 | 4 | Number = int(input("Enter a number to multilply to itself by it's number of times:"))
print("{} power {} is".format(Number, Number), end = "")
Product = 1
for Counter in range(Number):
Product = Product * Number
print(" {}.".format(Product))
| true |
b4e26837cb1813bb939df3c6f783aea9f0d7eb88 | MahadiRahman262523/Python_Code_Part-1 | /operators.py | 883 | 4.53125 | 5 | # Operators in Python
# Arithmetic Operators
# Assignment Operators
# Comparison Operators
# Logical Operators
# Identity Operators
# Membership Operators
# Bitwise Operators
# Assignment Operator
# print("5+6 is ",5+6)
# print("5-6 is ",5-6)
# print("5*6 is ",5*6)
# print("5/6 is ",5/6)
# print("16//6 is ",16//6)
# print("5**6 is ",5**6)
# print("5%6 is ",5%6)
#Assignment operator
# x = 56
# print(x)
# x += 44
# print(x)
#Comparison operator
# i = 4
# print(i!=7)
#Logical operator
# a = True
# b = False
# print(a and b)
# print(a or b)
#Identity operator
# a = True
# b = False
# print(a is b)
# print(a is not b)
#Membership Operator
# list = [10,44,7,8,44,89,90,100]
# print(12 in list)
# print(10 in list)
# Bitwise operator
print(0 & 0)
print(0 & 1)
print(0 | 0)
print(0 | 1)
print(1 | 1)
| true |
6141032532599c2a7f307170c680abff29c6e526 | MahadiRahman262523/Python_Code_Part-1 | /practice_problem-25.py | 340 | 4.34375 | 4 | # Write a program to find whether a given username contaoins less than 10
# characters or not
name = input("Enter your name : ")
length = len(name)
print("Your Name Length is : ",length)
if(length < 10):
print("Your Name Contains Less Than 10 Characters")
else:
print("Your Name Contains greater Than 10 Characters") | true |
9ef906ae918956dbdb2f48ea660293284b719a94 | asselapathirana/pythonbootcamp | /2023/day3/es_1.py | 2,425 | 4.34375 | 4 | import numpy as np
"""Fitness function to be minimized.
Example: minimize the sum of squares of the variables.
x - a numpy array of values for the variables
returns a single floating point value representing the fitness of the solution"""
def fitness_function(x):
return np.sum(x**2) # Example: minimize the sum of squares
"""Evolves a population of candidate solutions using the evolutionary strategy algorithm.
fitness_function - the fitness function to be minimized
num_variables - the number of variables in each candidate solution
population_size - the number of candidate solutions in the population
num_generations - the number of generations to evolve the population
returns the best solution evolved"""
def evolutionary_strategy(fitness_function, num_variables, population_size, num_generations):
# Initialize the population randomly
population = np.random.uniform(low=-5.0, high=5.0, size=(population_size, num_variables))
for generation in range(num_generations):
# Evaluate the fitness of each individual in the population
fitness = np.array([fitness_function(individual) for individual in population])
# Select the best individuals for the next generation
elite_indices = np.argsort(fitness)[:int(population_size/2)]
elite_population = population[elite_indices]
# Create the next generation
next_generation = []
for x in range(population_size):
parent_indices = np.random.choice(range(len(elite_population)), size=2)
parents = elite_population[parent_indices]
child = np.mean(parents, axis=0) + np.random.normal(scale=0.1, size=num_variables)
next_generation.append(child)
population = np.array(next_generation)
print(np.argmin(fitness), np.min(fitness)) # Print the best individual from each generation
# Find the best individual in the final population
fitness = np.array([fitness_function(individual) for individual in population])
best_index = np.argmin(fitness)
best_individual = population[best_index]
return best_individual
# Example usage
num_variables = 5
population_size = 100
num_generations = 500
best_solution = evolutionary_strategy(fitness_function, num_variables, population_size, num_generations)
print("Best solution:", best_solution)
print("Fitness:", fitness_function(best_solution))
| true |
6c375d41e8430694404a45b04819ef9e725db959 | asselapathirana/pythonbootcamp | /archives/2022/day1/quad.py | 781 | 4.15625 | 4 | # first ask the user to enter three numbers a,b,c
# user input is taken as string(text) in python
# so we need to convert them to decimal number using float
a = float(input('Insert a value for variable a'))
b = float(input('Insert a value for variable b'))
c = float(input('Insert a value for variable c'))
# now print the values, just to check
print(a, b, c)
# calculate b^2-4ac as d
d = b**2 - 4 * a * c
if d > 0 : # if d is positive
x1 = (-b + d**0.5)/ (2*a)
x2 = (-b - d**0.5)/ (2*a)
print('You have two real and distincts root')
print(x1, x2)
elif d == 0 : # if d is zero
x1 = (-b / (2*a))
print('You have one real root')
print(x1)
else : # d is niether positive or zeoro, that means negative.
print('No real root can be defined') | true |
cddcfc2c1a2d3177bcf784c7a09fd3fb1f2a69ec | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 1/Problem/Mathematics/Exactly 3 Divisors.py | 1,438 | 4.25 | 4 | Exactly 3 Divisors
Given a positive integer value N. The task is to find how many numbers less than or equal to N have numbers of divisors exactly equal to 3.
Example 1:
Input:
N = 6
Output: 1
Explanation: The only number with
3 divisor is 4.
Example 2:
Input:
N = 10
Output: 2
Explanation: 4 and 9 have 3 divisors.
Your Task:
You don't need to read input or print anything. Your task is to complete the function exactly3Divisors() that takes N as input parameter and returns count of numbers less than or equal to N with exactly 3 divisors.
Expected Time Complexity : O(N1/2 * N1/4)
Expected Auxilliary Space : O(1)
Constraints :
1 <= N <= 109
Solution:
#{
#Driver Code Starts
#Initial Template for Python 3
import math
# } Driver Code Ends
#User function Template for python3
def exactly3Divisors(N):
# code here
def isPrime(i):
i=2
while i<=math.sqrt(N):
if N%i==0:
return False
i +=1
return True
count =0
i=2
while i<N and (i*i)<=N:
if isPrime(i):
count +=1
return count
#{
#Driver Code Starts.
def main():
T=int(input())
while(T>0):
N=int(input())
print(exactly3Divisors(N))
T-=1
if __name__=="__main__":
main()
#} Driver Code Ends | true |
519a1790c47049f2f6a47a6362d45a6821c3252b | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 3/Strings/Problems/Convert to Roman No.py | 1,354 | 4.3125 | 4 | Convert to Roman No
Given an integer n, your task is to complete the function convertToRoman which prints the corresponding roman number of n. Various symbols and their values are given below.
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Example 1:
Input:
n = 5
Output: V
Example 2:
Input:
n = 3
Output: III
Your Task:
Complete the function convertToRoman() which takes an integer N as input parameter and returns the equivalent roman.
Expected Time Complexity: O(log10N)
Expected Auxiliary Space: O(log10N * 10)
Constraints:
1<=n<=3999
Solution
#Your task is to complete this function
#Your function should return a String
def convertRoman(n):
#Code here
strrom=[["","I","II","III","IV","V","VI","VII","VIII","IX"],
["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"],
["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"],
["","M","MM","MMM","","","","","",""]]
i = 0
str=""
while(n != 0):
str = strrom[i][n%10] + str
n=n//10
i+=1
return str
#{
# Driver Code Starts
#Your Code goes here
if __name__=='__main__':
t = int(input())
for i in range(t):
n = int(input())
print(convertRoman(n))
# Contributed by: Harshit Sidhwa
# } Driver Code Ends | true |
dab1464351b112f48570a5bf6f23c42912163925 | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 9/Heap/Problems/Nearly sorted.py | 2,018 | 4.1875 | 4 | Nearly sorted
Given an array of n elements, where each element is at most k away from its target position, you need to sort the array optimally.
Example 1:
Input:
n = 7, k = 3
arr[] = {6,5,3,2,8,10,9}
Output: 2 3 5 6 8 9 10
Explanation: The sorted array will be
2 3 5 6 8 9 10
Example 2:
Input:
n = 5, k = 2
arr[] = {4,3,1,2,5}
Output: 1 2 3 4 5
Note: DO NOT use STL sort() function for this question.
Your Task:
You are required to complete the method nearlySorted() which takes 3 arguments and returns the sorted array.
Expected Time Complexity : O(nlogk)
Expected Auxilliary Space : O(n)
Constraints:
1 <= n <= 106
1 <= k <= n
1 <= arri <= 107
Solution
#User function Template for python3
def nearlySorted(a,n,k):
'''
:param a: given array
:param n: size of a
:param k: max absolute distance of value from its sorted position
:return: sorted list
'''
min_heap = [] # our min heap to be used
ans = [] # our resultant sorted array
for num in a:
if len(min_heap)<2*k : # if number of elements in heap is less than 2*k
# we take 2*k as ,distance can be on either side
# insert this element
heapq.heappush(min_heap,num)
else:
# insert the root of the heap to ans, as it must be its position
ans.append(heapq.heappop(min_heap))
# now insert the current value in the heap
heapq.heappush(min_heap,num)
# if heap is non - empty, put all the elements taking from root of heap one by one in ans
while(len(min_heap)):
ans.append(heapq.heappop(min_heap))
return ans
#{
# Driver Code Starts
#Initial Template for Python 3
import atexit
import io
import sys
import heapq
from collections import defaultdict
# Contributed by : Nagendra Jha
if __name__ == '__main__':
test_cases = int(input())
for cases in range(test_cases) :
n,k = map(int,input().strip().split()) | true |
741480f8b2500ef939b9951b4567f5b16172379a | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 1/Problem/Arrays/Find Transition Point.py | 1,237 | 4.1875 | 4 | Find Transition Point
Given a sorted array containing only 0s and 1s, find the transition point.
Example 1:
Input:
N = 5
arr[] = {0,0,0,1,1}
Output: 3
Explanation: index 3 is the transition
point where 1 begins.
Example 2:
Input:
N = 4
arr[] = {0,0,0,0}
Output: -1
Explanation: Since, there is no "1",
the answer is -1.
Your Task:
You don't need to read input or print anything. The task is to complete the function transitionPoint() that takes array and N as input parameters and returns the 0 based index of the position where "0" ends and "1" begins. If array does not have any 1s, return -1. If array does not have any 0s, return 0.
Expected Time Complexity: O(LogN)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 500000
0 ≤ arr[i] ≤ 1
Solution:
def transitionPoint(arr, n):
#Code here
for i in range(0,len(arr)):
if arr[i]==1:
return i
return -1
#{
# Driver Code Starts
#driver code
if __name__=='__main__':
t=int(input())
for i in range(t):
n = int(input())
arr = list(map(int, input().strip().split()))
print(transitionPoint(arr, n))
# } Driver Code Ends | true |
0e9e0bab41e6810a4b6c41d69ae01df699977570 | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 3/Matrix/Transpose of Matrix.py | 1,798 | 4.59375 | 5 | Transpose of Matrix
Write a program to find the transpose of a square matrix of size N*N. Transpose of a matrix is obtained by changing rows to columns and columns to rows.
Example 1:
Input:
N = 4
mat[][] = {{1, 1, 1, 1},
{2, 2, 2, 2}
{3, 3, 3, 3}
{4, 4, 4, 4}}
Output:
{{1, 2, 3, 4},
{1, 2, 3, 4}
{1, 2, 3, 4}
{1, 2, 3, 4}}
Example 2:
Input:
N = 2
mat[][] = {{1, 2},
{-9, -2}}
Output:
{{1, -9},
{2, -2}}
Your Task:
You dont need to read input or print anything. Complete the function transpose() which takes matrix[][] and N as input parameter and finds the transpose of the input matrix. You need to do this in-place. That is you need to update the original matrix with the transpose.
Expected Time Complexity: O(N * N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 100
-103 <= mat[i][j] <= 103
Solution
#User function Template for python3
def transpose(matrix, n):
# code here
tmp = 0
for i in range(n):
for j in range(i+1,n):
tmp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = tmp
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t = int (input ())
for _ in range (t):
n = int(input())
matrix = [[0 for j in range(n)] for i in range(n)]
line1 = [int(x) for x in input().strip().split()]
k=0
for i in range(n):
for j in range (n):
matrix[i][j]=line1[k]
k+=1
transpose(matrix,n)
for i in range(n):
for j in range(n):
print(matrix[i][j],end=" ")
print()
# } Driver Code Ends | true |
48c9c87ca2976207c5f379fd9b42df86faa877b5 | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 4/Linked LIst/Reverse a Linked List in groups of given size.py | 2,725 | 4.25 | 4 | Reverse a Linked List in groups of given size.
Given a linked list of size N. The task is to reverse every k nodes (where k is an input to the function) in the linked list.
Example 1:
Input:
LinkedList: 1->2->2->4->5->6->7->8
K = 4
Output: 4 2 2 1 8 7 6 5
Explanation:
The first 4 elements 1,2,2,4 are reversed first
and then the next 4 elements 5,6,7,8. Hence, the
resultant linked list is 4->2->2->1->8->7->6->5.
Example 2:
Input:
LinkedList: 1->2->3->4->5
K = 3
Output: 3 2 1 5 4
Explanation:
The first 3 elements are 1,2,3 are reversed
first and then elements 4,5 are reversed.Hence,
the resultant linked list is 3->2->1->5->4.
Your Task:
You don't need to read input or print anything. Your task is to complete the function reverse() which should reverse the linked list in group of size k and return the head of the modified linked list.
Expected Time Complexity : O(N)
Expected Auxilliary Space : O(1)
Constraints:
1 <= N <= 103
1 <= k <= N
Solution
"""Return reference of new head of the reverse linked list
The input list will have at least one element
Node is defined as
class Node:
def __init__(self, data):
self.data = data
self.next = None
This is method only submission.
You only need to complete the method.
"""
def reverse(head, k):
# Code here
current = head
prev = None
nextnode = None
count = 0
while(current!=None and count<k):
# print(current.data)
nextnode = current.next
current.next = prev
prev = current
count = count + 1
current = nextnode
if nextnode!=None:
head.next = reverse(nextnode,k)
return prev
#{
# Driver Code Starts
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# self.tail
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def printList(self):
temp = self.head
while (temp):
print(temp.data, end=" ")
# arr.append(str(temp.data))
temp = temp.next
print()
if __name__ == '__main__':
t = int(input())
while (t > 0):
llist = LinkedList()
n = input()
values = list(map(int, input().split()))
for i in reversed(values):
llist.push(i)
k = int(input())
new_head = LinkedList()
new_head = reverse(llist.head, k)
llist.head = new_head
llist.printList()
t -= 1
# } Driver Code Ends | true |
b1acad41a07b4a5a1b38fdad15619ebeec5dd70d | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 3/Bit Magic/Rightmost different bit.py | 1,708 | 4.15625 | 4 | Rightmost different bit
Given two numbers M and N. The task is to find the position of the rightmost different bit in the binary representation of numbers.
Example 1:
Input: M = 11, N = 9
Output: 2
Explanation: Binary representation of the given
numbers are: 1011 and 1001,
2nd bit from right is different.
Example 2:
Input: M = 52, N = 4
Output: 5
Explanation: Binary representation of the given
numbers are: 110100‬ and 0100,
5th-bit from right is different.
User Task:
The task is to complete the function posOfRightMostDiffBit() which takes two arguments m and n and returns the position of first different bits in m and n. If both m and n are the same then return -1 in this case.
Expected Time Complexity: O(max(log m, log n)).
Expected Auxiliary Space: O(1).
Constraints:
1 <= M <= 103
1 <= N <= 103
Solution
#{
#Driver Code Starts
#Initial Template for Python 3
import math
# } Driver Code Ends
#User function Template for python3
##Complete this function
def posOfRightMostDiffBit(m,n):
#Your code here
if m > n:
m, n = n, m
i=1
while (n > 0):
if (m % 2) == (n % 2):
pass
else:
return i
m = m // 2
n = n // 2
i=i+1
#{
#Driver Code Starts.
def main():
T=int(input())
while(T>0):
mn=[int(x) for x in input().strip().split()]
m=mn[0]
n=mn[1]
print(math.floor(posOfRightMostDiffBit(m,n)))
T-=1
if __name__=="__main__":
main()
#} Driver Code Ends | true |
27f267d66c25e89ed823ddd1f003b33fe09cc3cc | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 1/Problem/Arrays/Remove duplicate elements from sorted Array.py | 1,554 | 4.1875 | 4 | Remove duplicate elements from sorted Array
Given a sorted array A of size N, delete all the duplicates elements from A.
Example 1:
Input:
N = 5
Array = {2, 2, 2, 2, 2}
Output: 2
Explanation: After removing all the duplicates
only one instance of 2 will remain.
Example 2:
Input:
N = 3
Array = {1, 2, 2}
Output: 1 2
Your Task:
You dont need to read input or print anything. Complete the function remove_duplicate() which takes the array A[] and its size N as input parameters and modifies it in place to delete all the duplicates. The function must return an integer X denoting the new modified size of the array.
Note: The generated output will print all the elements of the modified array from index 0 to X-1.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 104
1 <= A[i] <= 106
Solution:
#User function template for Python
class Solution:
def remove_duplicate(self, A, N):
# code here
j=0
if N==0 or N==1:
return N
for i in range(0,N-1):
if A[i] != A[i+1]:
A[j]=A[i]
j +=1
A[j]=A[N-1]
j +=1
return j
#{
# Driver Code Starts
#Initial template for Python
if __name__=='__main__':
t = int(input())
for i in range(t):
N = int(input())
A = list(map(int, input().strip().split()))
ob = Solution()
n = ob.remove_duplicate(A,N)
for i in range(n):
print(A[i], end=" ")
print()
# } Driver Code Ends | true |
4a44a1c4851060d4114ea4ae3d509800781378e0 | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 3/Strings/Problems/Longest Substring Without Repeating Characters.py | 2,507 | 4.125 | 4 | Longest Substring Without Repeating Characters
Given a string S, find the length of its longest substring that does not have any repeating characters.
Example 1:
Input:
S = geeksforgeeks
Output: 7
Explanation: The longest substring
without repeated characters is "ksforge".
Example 2:
Input:
S = abbcdb
Output: 3
Explanation: The longest substring is
"bcd". Here "abcd" is not a substring
of the given string.
Your Task:
Complete SubsequenceLength function that takes string s as input and returns the length of the longest substring that does not have any repeating characters.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
0<= N <= 10^5
here, N = S.length
Solution
#User function Template for python3
def SubsequenceLength(s):
if (len(s) == 0 ):
return 0
count = 1 # length of current substring
answer = 1 # result
''' Define the visited array to represent all
256 ASCII characters and maintain their last
seen position in the processed substring.
Initialize the array as -1 to indicate that
no character has been visited yet. '''
visited = [-1]*256
''' Mark first character as visited by storing the index
of first character in visited array. '''
visited[ord(s[0])]=0;
'''Start from the second character. ie- index 1 as
the first character is already processed. '''
for end in range(1,len(s)):
idx = ord(s[end])
''' If the current character is not present in the
already processed string or it is not part of the
current non-repeating-character-string (NRCS),
increase count by 1 '''
if(visited[idx] == -1 or end-count > visited[idx]):
count+=1
# If current character is already present in NRCS
else:
''' check whether length of the previous
NRCS was greater than answer or not '''
answer = max(count, answer)
''' update NRCS to start from the next
character of the previous instance. '''
count = end - visited[idx]
# update the index of current character in visited array
visited[idx]=end
return max(count,answer)
#{
# Driver Code Starts
#Initial Template for Python 3
for _ in range(0,int(input())):
s = input()
print(SubsequenceLength(s))
# } Driver Code Ends | true |
d3d0dabc882f6021df69bebe4a00e4b97c6878bf | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 9/Heap/Problems/Heap Sort.py | 2,223 | 4.3125 | 4 | Heap Sort
Given an array of size N. The task is to sort the array elements by completing functions heapify() and buildHeap() which are used to implement Heap Sort.
Example 1:
Input:
N = 5
arr[] = {4,1,3,9,7}
Output:
1 3 4 7 9
Explanation:
After sorting elements
using heap sort, elements will be
in order as 1,3,4,7,9.
Example 2:
Input:
N = 10
arr[] = {10,9,8,7,6,5,4,3,2,1}
Output:
1 2 3 4 5 6 7 8 9 10
Explanation:
After sorting elements
using heap sort, elements will be
in order as 1, 2,3,4,5,6,7,8,9,10.
Your Task :
Complete the functions heapify() and buildheap().
Expected Time Complexity: O(N * Log(N)).
Expected Auxiliary Space: O(1).
Constraints:
1 <= N <= 106
1 <= arr[i] <= 106
Solution
#User function Template for python3
def heapify(arr, n, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is
# greater than root
if l < n and arr[i] < arr[l]:
largest = l
# See if right child of root exists and is
# greater than root
if r < n and arr[largest] < arr[r]:
largest = r
# Change root, if needed
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i] # swap
# Heapify the root.
heapify(arr, n, largest)
# The main function to sort an array of given size
def buildHeap(arr,n):
# Build a maxheap.
for i in range(n, -1, -1):
heapify(arr, n, i)
# One by one extract elements
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
#{
# Driver Code Starts
#Initial Template for Python 3
import atexit
import io
import sys
# Contributed by : Mohit Kumara
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
if __name__ == '__main__':
test_cases = int(input())
for cases in range(test_cases):
n = int(input())
arr = list(map(int, input().strip().split()))
buildHeap(arr,n)
print(*arr)
# } Driver Code Ends
| true |
0bb5128f7e3bbd1ee480e189c182cb7933143ae1 | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 3/Strings/Problems/Isomorphic Strings.py | 2,802 | 4.4375 | 4 | Isomorphic Strings
Given two strings 'str1' and 'str2', check if these two strings are isomorphic to each other.
Two strings str1 and str2 are called isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2 while preserving the order.
Note: All occurrences of every character in ‘str1’ should map to the same character in ‘str2’
Example 1:
Input:
str1 = aab
str2 = xxy
Output: 1
Explanation: There are two different
charactersin aab and xxy, i.e a and b
with frequency 2and 1 respectively.
Example 2:
Input:
str1 = aab
str2 = xyz
Output:
Explanation: There are two different
charactersin aab but there are three
different charactersin xyz. So there
won't be one to one mapping between
str1 and str2.
Your Task:
You don't need to read input or print anything.Your task is to complete the function areIsomorphic() which takes the string str1 and string str2 as input parameter and check if two strings are isomorphic. The function returns true if strings are isomorphic else it returns false.
Expected Time Complexity: O(|str1|+|str2|).
Expected Auxiliary Space: O(Number of different characters).
Note: |s| represents the length of string s.
Constraints:
1 <= |str1|, |str2| <= 103
Solution
#User function Template for python3
'''
Your task is to check if the given strings are
isomorphic or not.
Function Arguments: str1 and str2 (given strings)
Return Type: boolean
'''
def areIsomorphic2(str1,str2):
dict1 = {}
len1 = len(str1)
len2 = len(str2)
# print(dict1,len1,len1)
if len1 == len2:
for i in range(len1):
if str1[i] in dict1.keys():
if dict1[str1[i]] == str2[i]:
pass
else:
return False
else:
dict1[str1[i]] = str2[i]
else:
return False
return True
def areIsomorphic(s,p):
first = areIsomorphic2(s, p)
second = areIsomorphic2(p, s)
# print(first, second)
if (first == True and second == True):
return True
else:
return False
#{
# Driver Code Starts
#Initial Template for Python 3
import atexit
import io
import sys
from collections import defaultdict
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
if __name__=='__main__':
t = int(input())
for i in range(t):
s=str(input())
p=str(input())
if(areIsomorphic(s,p)):
print(1)
else:
print(0)
# } Driver Code Ends | true |
261cfa1feb28124e9113c400707c5dedf9e30249 | Technicoryx/python_strings_inbuilt_functions | /string_08.py | 609 | 4.40625 | 4 | """Below Python Programme demonstrate expandtabs
functions in a string"""
#Case1 : With no Argument
str = 'xyz\t12345\tabc'
# no argument is passed
# default tabsize is 8
result = str.expandtabs()
print(result)
#Case 2:Different Argument
str = "xyz\t12345\tabc"
print('Original String:', str)
# tabsize is set to 2
print('Tabsize 2:', str.expandtabs(2))
# tabsize is set to 3
print('Tabsize 3:', str.expandtabs(3))
# tabsize is set to 4
print('Tabsize 4:', str.expandtabs(4))
# tabsize is set to 5
print('Tabsize 5:', str.expandtabs(5))
# tabsize is set to 6
print('Tabsize 6:', str.expandtabs(6))
| true |
cf11c056ca6697454d3c585e6fa6eea6a153deae | Technicoryx/python_strings_inbuilt_functions | /string_06.py | 204 | 4.125 | 4 | """Below Python Programme demonstrate count
functions in a string"""
string = "Python is awesome, isn't it?"
substring = "is"
count = string.count(substring)
# print count
print("The count is:", count)
| true |
da915e308927c3e5ed8eb0f96937f10fd320c8ab | Technicoryx/python_strings_inbuilt_functions | /string_23.py | 360 | 4.46875 | 4 | """Below Python Programme demonstrate ljust
functions in a string"""
#Example:
# example string
string = 'cat'
width = 5
# print right justified string
print(string.rjust(width))
#Right justify string and fill the remaining spaces
# example string
string = 'cat'
width = 5
fillchar = '*'
# print right justified string
print(string.rjust(width, fillchar))
| true |
68285e9fdf5413e817851744d716596c0ff2c926 | anton515/Stack-ADT-and-Trees | /queueStackADT.py | 2,893 | 4.25 | 4 |
from dataStructures import Queue
import check
# Implementation of the Stack ADT using a single Queue.
class Stack:
'''
Stack ADT
'''
## Stack () produces an empty stack.
## __init__: None -> Stack
def __init__(self):
self.stack = Queue ()
## isEmpty(self) returns True if the Stack is empty, False otherwise
## isEmpty: Stack -> Bool
def isEmpty(self):
return self.stack.isEmpty ()
## len(self) returns the number of items in the stack.
## __len__: Stack -> Int
def __len__(self):
return self.stack.__len__()
## peek(self) returns a reference to the top item of the Stack without
## removing it. Can only be done on when Stack is not empty and does
## not modify the stack contents.
## peek: Stack -> Any
## Requires: Stack cannot be empty
def peek(self):
assert len(self.stack) > 0, "Cannot peek from empty Stack"
delta = len(self.stack) - 1
while delta != 0:
item = self.stack.dequeue()
self.stack.enqueue(item)
delta -= 1
item = self.stack.dequeue()
self.stack.enqueue(item)
return item
## pop(self) removes and returns the top (most recent) item of the Stack,
## if the Stack is not empty. The next (2nd most recent) item on the
## Stack becomes the new top item.
## pop: Stack -> Any
## Requires: Stack cannot be empty
## Effects: The next (2nd most recent) item on the Stack becomes the new
## top item.
def pop(self):
assert len(self.stack) > 0, "Cannot pop from Empty Stack."
delta = len(self.stack) - 1
while delta != 0:
item = self.stack.dequeue()
self.stack.enqueue(item)
delta -= 1
return self.stack.dequeue()
## push(self,item) adds the given item to the top of the Stack
## push: Stack Any -> None
## Effects: adds the given item to the top of the Stack
def push(self, item):
self.stack.enqueue(item)
## print(self) prints the items in the Stack (for testing purposes)
## __str__: Stack -> Str
## Requires: Stack cannot be empty
def __str__(self):
assert not self.isEmpty(), "Cannot print from an empty Stack."
return self.stack.__str__()
## Test
t1 = Stack()
check.expect("Q1T1",t1.isEmpty(),True)
check.expect("Q1T2",len(t1),0)
t1.push(1)
check.expect("Q1T3",t1.isEmpty(),False)
check.expect("Q1T4",t1.peek(),1)
check.expect("Q1T5",len(t1),1)
t1.push(100)
check.expect("Q1T6",t1.isEmpty(),False)
check.expect("Q1T7",t1.peek(),100)
check.expect("Q1T8",len(t1),2)
check.expect("Q1Ta",t1.pop(),100)
check.expect("Q1T9",t1.isEmpty(),False)
check.expect("Q1T10",t1.peek(),1)
check.expect("Q1T11",len(t1),1)
check.expect("Q1Tb",t1.pop(),1)
check.expect("Q1T12",t1.isEmpty(),True)
check.expect("Q1T13",len(t1),0)
| true |
ce6d86586bb5d7030312ade00c8fc3ca7a0d2273 | vamsi-kavuru/AWS-CF1 | /Atari-2.py | 1,182 | 4.28125 | 4 | from __future__ import print_function
print ("welcome to my atari adventure game! the directions to move in are defined as left, right, up, and down. Enjoy.")
x = 6
y = -2
#move = str(input('Make your move! Type in either "Left", "Right", "Up", "Down" or type "Exit" to exit the game:')).lower()
def game():
global x
global y
move = str(input('Make your move! Type in either "Left", "Right", "Up", "Down" or type "Exit" to exit the game:')).lower()
if move == ('left'):
x = x-3
print ('your x position is', x, '.' 'your y position is', y, '.')
game()
elif move == ('up'):
y = y+3
print ('your x position is', x, '.' 'your y position is', y, '.')
game()
elif move == ('right'):
x = x+2
print ('your x position is', x, '.' 'your y position is', y, '.')
game()
elif move == ('down'):
y = y-2
print ('your x position is', x, '.' 'your y position is', y, '.')
game()
elif move == ('exit'):
exit()
else:
print ("Oops!!! You have entered a wrong input, please enter either up, down, left, right or exit only.")
game()
game() | true |
562c78526d055d1ca782cc39096decf79a585bb6 | AmbyMbayi/CODE_py | /Pandas/Pandas_PivotTable/Question1.py | 310 | 4.125 | 4 | """write a pandas program to create a pivot table with multiple indexes from a given excel sheet
"""
import pandas as pd
import numpy as np
df = pd.read_excel('SaleData.xlsx')
print(df)
print("the pivot table is shown as: ")
pivot_result = pd.pivot_table(df, index=["Region", "SalesMan"])
print(pivot_result) | true |
8b0716fd554604776390c6f6ab40619d19fc5e12 | KWinston/PythonMazeSolver | /main.py | 2,559 | 4.5 | 4 | # CMPT 200 Lab 2 Maze Solver
#
# Author: Winston Kouch
#
#
# Date: September 30, 2014
#
# Description: Asks user for file with maze data. Stores maze in list of lists
# Runs backtracking recursive function to find path to goal.
# Saves the output to file, mazeSol.txt. If no file given, it will
# default to using maze.txt. It then checks if the file exists.
# if it does, it will proceed with solving the maze. If it
# doesn't exist it will print an error message and stop.
#
# Syntax: getMaze() - Asks user for file with maze data
#
#
# import my Maze class
from Maze import *
# To load the maze, this function is used to ask user for maze filename
# After it is entered, it will load the maze or
def getMaze():
# Ask user to input maze file name
filename = input("Please enter the maze file name: ")
# if user enters nothing during input, it will default to maze.txt and try to open it.
if (filename == ""):
filename = "maze.txt"
# try to open the file
try:
inputFile = open(filename, 'r')
except FileNotFoundError:
# If it doesnt exist, prints error message and stops
print ("Error, The file", filename, "does not exist.")
return None
# Read the map data into theMaze
theMaze = inputFile.readlines()
# close the file
inputFile.close()
# Set up the map size, start point, end point
# Grab from first line of map data
mapSize = theMaze[0].split()
# Split the 2 numbers into rows, cols
mapSize[0] = 2*int(mapSize[0])+1
mapSize[1] = 2*int(mapSize[1])+1
# Grab start and end point from line 2 and 3 of file
startPoint = theMaze[1].split()
endPoint = theMaze[2].split()
# Set up a display window for graphics.py
win = GraphWin ("Maze Path", 10 * (mapSize[1]), 10 * (mapSize[0]))
# Generate the board in a list of lists
generatedMaze = Maze(mapSize[0],mapSize[1])
# Map the maze into my list of lists
generatedMaze.mappingMaze(theMaze, mapSize)
# Place the start and end points onto the board
generatedMaze.setPositions(startPoint, endPoint, mapSize)
# Display translated Maze
generatedMaze.display(generatedMaze, 10, win)
# Solve the maze
generatedMaze.solveMaze()
# Display the solution in graphics
generatedMaze.displaysol(generatedMaze, 10, win)
# Run getMaze
getMaze() | true |
b37a727c6653dafcfa480283e68badbd87c408f2 | skynette/Solved-Problems | /Collatz.py | 1,737 | 4.3125 | 4 | question = """The Collatz Sequence
Write a function named collatz() that has one parameter named number. If
number is even, then collatz() should print number // 2 and return this value.
If number is odd, then collatz() should print and return 3 * number + 1. Then write a program that
lets the user type in an integer and that keeps calling collatz() on
that number until the function returns the value 1.
(Amazingly enough, this sequence actually works for any integer—sooner
or later, using this sequence, you’ll arrive at 1! Even mathematicians aren’t
sure why. Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”)
Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value.
Hint: An integer number is even if number % 2 == 0, and it’s odd if
number % 2 == 1."""
output = """The output of this program could look something like this:
Enter number:
3
10
5
16
8
4
2
1
"""
def collatz(number):
if number%2 == 0:
result = number//2
else:
result = 3*number+1
return result
number = int(input("Enter a starting number: "))
print(number)
while collatz(number) != 1:
print(collatz(number))
number = collatz(number)
print(1)
times = int(input())
nums = []
len_of_nums = []
for i in range(times):
nl = []
n = int(input())
n = n-1
nums.append(n)
count = 0
while count < len(str(n)):
while n!=1:
n = collatz(n)
nl.append(n)
count+=1
len_of_nums.append(len(nl))
d = list(zip(len_of_nums, nums))
m = (max(d))
print(m[-1])
| true |
0081eac284bb86e948aeef7e933796385df12000 | ddbs/Accelerating_Dual_Momentum | /functions.py | 374 | 4.15625 | 4 | from datetime import datetime, date
def start_of_year(my_date):
"""
Gives the starting date of a year given any date
:param my_date: date, str
:return: str
"""
my_date = datetime.strptime(my_date, '%Y-%m-%d')
starting_date = date(my_date.year, my_date.month, 1)
starting_date = starting_date.strftime('%Y-%m-%d')
return starting_date
| true |
d545e90149dfca91045aed7666b8456644c8f9a8 | jyotisahu08/PythonPrograms | /StringRev.py | 530 | 4.3125 | 4 | from builtins import print
str = 'High Time'
# Printing length of given string
a = len(str)
print('Length of the given string is :',a)
# Printing reverse of the given string
str1 = ""
for i in str:
str1 = i + str1
print("Reverse of given string is :",str1)
# Checking a given string is palindrome or not
str2 = 'abba'
str3 = ''
for i in str2:
str3 = i + str3
assert str2==str3,"given string is not a palindrome"
print("given string is a palindrome")
# Displaying the string multiple times
for i in range(0,3):
print(str)
| true |
d5e49df7f61a6e15cf1357aa09e33a81e186627b | Botany-Downs-Secondary-College/password_manager-bunda | /eason_loginV1.py | 2,002 | 4.4375 | 4 | #password_manager
#store and display password for others
#E.Xuan, February 22
name = ""
age = ""
login_user = ["bdsc"]
login_password = ["pass1234"]
password_list = []
def menu(name, age):
if age < 13:
print("Sorry, you do not meet the age requirement for this app")
exit()
else:
print("Welcome", name)
mode = input("Choose a mode by entering the number: \n"
"1: Add passwords 2: Veiw passwords 3: Exit \n"
"").strip()
return mode
def login():
while True:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
if username in login_user and password in login_password:
print("Welcome back,", username)
else:
print("do it again")
print("Welocome to the password manager")
while True:
user_login = input("Please enter, L to login or, N to sign up: ").strip().title()
if user_login == "L":
login()
break
elif user_login == "N":
print("make account")
break
else:
print("enter either L or N")
print("If you are over the age of 12, you are able to store your passwords on this app")
name = input("What is your name?: ")
while True:
try:
age = float(input("How old are you?: "))
option = menu(name, age)
if option == "1":
new_password = input("please enter a password: ")
password_list.append(new_password)
elif option == "2":
print("Here are your passwords")
for password in password_list:
print(password)
elif option == "3":
print("Goodbye")
break
else:
print("That is not a valid number please enter a valid value")
except ValueError:
print("Please enther numbers")
print("Thank you for using the password manager") | true |
baa45a884596594e89c2ca311973bf378c756e77 | SinCatGit/leetcode | /00122/best_time_to_buy_and_sell_stock_ii.py | 1,574 | 4.125 | 4 | from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions
as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock
before you buy again).
Parameters
----------
prices: List[int]
Returns
-------
int
Examples
--------
>>> solution = Solution()
>>> solution.maxProfit([7, 1, 5, 3, 6, 4])
7
>>> solution.maxProfit([1, 2, 3, 4, 5])
4
>>> solution.maxProfit([7, 6, 4, 3, 1])
0
Notes
-----
References
---------
"""
return sum([max(0, prices[i]-prices[i-1]) for i in range(1, len(prices))])
def maxProfitV01(self, prices: List[int]) -> int:
i, profit, prices_len = 0, 0, len(prices)
while i < prices_len:
while i < prices_len - 1 and prices[i] > prices[i+1]:
i += 1
min_val = prices[i]
i += 1
while i < prices_len - 1 and prices[i] <= prices[i+1]:
i += 1
if i < prices_len:
profit += prices[i] - min_val
return profit
| true |
c5eadaf692c43bc0ad5acf88104403ca6b7266dc | HarryVines/Assignment | /Garden cost.py | 323 | 4.21875 | 4 | length = float(input("Please enter the length of the garden in metres: "))
width = float(input("Please enter the width of the garden in metres: "))
area = (length-1)*(width-1)
cost = area*10
print("The area of your garden is: {0}".format(area))
print("The cost to lay grass on your garden is : £{0}".format(cost))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.