blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
21964a6a9150ffc373599207402aef774f5917a8 | rarezhang/ucberkeley_cs61a | /lecture/l10_data_abstraction.py | 1,233 | 4.4375 | 4 | """
lecture 10
Data Abstraction
"""
# data
print(type(1))
## <class 'int'> --> represents int exactly
print(type(2.2))
## <class 'float'> --> represents real numbers approximately eg. 0.2222222222222222 == 0.2222222222222227 True
print(type(1+1j))
## <class 'complex'>
print(type(True))
## <class 'bool'>
print(1+1.2)
## <class 'float'>
# object
# represent information
# (1) data (2) behavior --> abstraction
# object-oriented programming
from datetime import date
today = date(2016, 2, 29)
freedom = date(2016, 5, 20)
print(str(freedom - today))
print(today.year)
print(today.day)
print(today.strftime("%A %B %d")) # a method for the object 'today' string format of time
print(type(today))
## <class 'datetime.date'>
# data abstraction
# compound objects combine objects together
## parts -> how data are represented
## units -> how data are manipulated
# data abstraction: enforce an abstraction barrier between (1) representation (2) use
# pair representation
## normal way
def pair_1(x, y):
return [x, y]
def select_1(p, i):
return p[i]
## functional pair representation
def pair_2(x, y):
def get(index):
if index == 0:
return x
elif index == 1:
return y
return get
def select_2(p, i):
return p(i) | true |
efd57652ea766f2eead4561e8d9737163de0ef8a | cIvanrc/problems | /ruby_and_python/2_condition_and_loop/check_pass.py | 905 | 4.1875 | 4 | # Write a Python program to check the validity of a password (input from users).
# Validation :
# At least 1 letter between [a-z] and 1 letter between [A-Z].
# At least 1 number between [0-9].
# At least 1 character from [$#@].
# Minimum length 6 characters.
# Maximum length 16 characters.
# Input
# W3r@100a
# Output
# Valid password
import re
def check_pass():
passw = input("say a password: ")
if is_valid(passw):
print("Valid pass")
else:
print("wrong pass")
def is_valid(passw):
is_valid = True
if not (len(passw) >= 6 and len(passw) <= 16):
is_valid = False
if not re.search("[a-z]", passw):
is_valid = False
if not re.search("[A-Z]", passw):
is_valid = False
if not re.search("[0-9]", passw):
is_valid = False
if not re.search("[$#@]", passw):
is_valid = False
return is_valid
check_pass()
| true |
74d1f20b9a008084b1200a73a16d6e7d79866db0 | cIvanrc/problems | /ruby_and_python/8_math/binary_to_decimal.py | 484 | 4.40625 | 4 | # Write a python program to convert a binary number to a decimal number
class Convert():
def binary_to_decimal(self):
binary_num = list(input("Input a binary number: "))
value = 0
len_binary_num = len(binary_num)
for i in range(len_binary_num):
digit = binary_num.pop()
if digit == "1":
print("i:{}::digit:{}::val:{}".format(i, digit, pow(2,i)))
value += pow(2,i)
return value
| false |
5ca2ba498860e710f44477f96523c0413ed54cbe | cIvanrc/problems | /ruby_and_python/12_sort/merge_sort.py | 1,497 | 4.40625 | 4 | # Write a python program to sort a list of elements using the merge sort algorithm
# Note: According to Wikipedia "Merge sort (also commonly spelled mergesort) is an 0 (n log n)
# comparasion-baed sortgin algorithm. Most implementations produce a stable sort, which means that
# the implementation preserves the input order of equal elements on the sorted output.
# Algorithm:
# Concepcually, a merge sort works as follows:
# Divide the unsorted list into n sublist, each containing 1 element (a list of 1 element is considered sorted).
# Repeatedly merge sublist to produce new sorted sublist until there only 1 sublist remaining. This will be the sorted list"
def merge_sort(nlist):
print("Splitting ", nlist)
if len(nlist)>1:
mid = len(nlist)//2
left_half = nlist[:mid]
right_half = nlist[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
nlist[k] = left_half[i]
i+=1
else:
nlist[k] = right_half[j]
j+=1
k+=1
while i < len(left_half):
nlist[k] = left_half[i]
i+=1
k+=1
while j < len(right_half):
nlist[k] = right_half[j]
j+=1
k+=1
print("Merging: ",nlist)
nlist = [4,12,5,82,1,43,73,84,24,51,35,12]
merge_sort(nlist)
print(nlist)
| true |
68456f7fa3638ae327fc6874c22b74099b28f351 | cIvanrc/problems | /ruby_and_python/3_list/find_max.py | 648 | 4.28125 | 4 | # Write a Python program to get the smallest number from a list.
# max_num_in_list([1, 2, -8, 0])
# return 2
def find_max():
n = int(input("How many elements you will set?: "))
num_list = get_list(n)
print(get_max_on_list(num_list))
def get_list(n):
numbers = []
for i in range(1, n+1):
number = int(input("{}.-Say a number: ".format(i)))
numbers.append(number)
return numbers
def get_max_on_list(num_list):
max = num_list[0]
for i in range(1, len(num_list)):
if max < num_list[i]:
max = num_list[i]
return "The max value in the list is: {}".format(max)
find_max()
| true |
9600319f92cf09f3eef5ec5e5cdfbe80c2c8e81a | asingleservingfriend/PracticeFiles | /regExpressions.py | 1,796 | 4.125 | 4 | import re
l = "Beautiful is better than ugly"
matches = re.findall("beautiful", l, re.IGNORECASE)
#print(matches)
#MATCH MULTIPLE CHARACTERS
string = "Two too"
m = re.findall("t[wo]o", string, re.IGNORECASE)
#print(m)
#MATCH DIGITS
line = "123?34 hello?"
d = re.findall("\d", line, re.IGNORECASE)
#print(d)
#NON GREEDY REPITITION MATCHING
# the quesiton mark makes the expression non-greedy.
t= "__one__ __two__ __three__"
found = re.findall("__.*?__", t)
#print (found)
#ESCAPING
line2 = "I love $"
l = re.findall("\\$", line2, re.IGNORECASE)
#print(l)
#PRACTICE
txt="""
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
match = re.findall("Dutch", txt)
#print(match)
string2 = "Arizona 479, 501, 870. California 209, 213, 650"
dig = re.findall("\d", string2, re.IGNORECASE)
#print(dig)
sent = "The ghost that says boo haunts the loo"
doubla = re.findall("[bl]oo", sent, re.IGNORECASE)
print(doubla)
| true |
10a1d131ff6eb33d0f12d8aa67b3e9fd93e05153 | christianmconroy/Georgetown-Coursework | /ProgrammingStats/Week 8 - Introduction to Python/myfunctions.py | 2,006 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 07 18:33:25 2018
@author: chris
"""
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 07 18:29:10 2018
@author: chris
"""
# refer slide 41
# Program with functions
# Name this program withfunctions.py
# the entire program; there is one small change
# that small change is that the file name is not
# hard coded into the function
def get_input(filename):
"""Reads a file and returns the file contents.
Args:
filename: the name of the file including the path
Returns:
a list with the file contents
"""
myList = []
with open(filename) as f:
for line in f:
myList.append(int(line))
return myList
def getMean(myList):
"""returns the mean of numbers in a list
Args:
myList (list): contains numbers for which mean is calculated
Returns:
(float) the mean of numbers in myList
"""
mysum = 0.0
for i in range(len(myList)):
mysum = mysum + myList[i]
mymean = mysum/len(myList)
return mymean
def getSD(myList):
"""returns the standard deviation of numbers in a list
Args:
myList (list): contains numbers for which standard deviation is calculated
Returns:
(float) the standard deviation of numbers in myList
"""
import math
n = len(myList)
mean = sum(myList) / n
dev = [x - mean for x in myList]
dev2 = [x*x for x in dev]
mysd = math.sqrt( sum(dev2) / (n-1))
return mysd
def print_output(myList, mymean, mysd):
"""prints the output
Args:
myList (list): contains numbers to be counted
mymean (float): contains value of mean for numbers in myList
mysd (list): contains value of standard deviation for numbers in myList
"""
print ("The size of the sample is {:d}".format(len(myList)))
print ("The sample mean is {:10.2f} ".format(mymean))
print ("The sample standard deviation is {:<16.2f}".format(mysd))
| true |
3608552cce91138d629a3ad9cb2208b2b8f15b2f | Latoslo/day-3-3-exercise | /main.py | 617 | 4.1875 | 4 | # 🚨 Don't change the code below 👇
year = int(input("Which year do you want to check? "))
# 🚨 Don't change the code above 👆
# > `on every year that is evenly divisible by 4
# > **except** every year that is evenly divisible by 100
# > **unless** the year is also evenly divisible by 400`
#Write your code below this line 👇
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print('line12: This is a leap year')
else:
print('line14: This is not a leap year')
else:
print('line16: This is a leap year')
else:
print('line18: This is not a leap year')
| true |
80b2020aeabd82d5390c8ef044523e6d3fb616c4 | shubhamkanade/all_language_programs | /Evenfactorial.py | 363 | 4.28125 | 4 | def Evenfactorial(number):
fact = 1
while(number != 0):
if(number % 2 == 0):
fact = fact * number
number -= 2
else:
number = number-1
return fact
number = int(input("Enter a number"))
result = Evenfactorial(number)
print("the factorial is ", result) | true |
e0461c90da83c9b948352e729a91c80b24ed2817 | shubhamkanade/all_language_programs | /checkpalindrome.py | 460 | 4.21875 | 4 | import reverse
def checkpalindrome(number):
result = reverse.Reverse_number(number)
if(result == number):
return True
else:
return False
def main():
number = int(input("Enter a number\n"))
if(checkpalindrome(number)== True):
print("%d number is palindrome" % number)
else:
print("%d is not a palindrome number" % number)
if __name__ == "__main__":
main() | true |
a1a1c971e1fa7008b457aa67d8d784b054f0b671 | workwithfattyfingers/testPython | /first_project/exercise3.py | 553 | 4.40625 | 4 | # Take 2 inputs from the user
# 1) user name
# 2) any letter from user which we can count in SyntaxWarning
# OUTPUT
# 1) user's name in length
# 2) count the number of character that user inputed
user_name=input(print("Please enter any name"))
char_count=input(print("Please enter any character which you want to count"))
#name_count = len(user_name)
#Output
print("String/Name input by you:\t" + user_name)
print("Length of your name is:\t" + str(len(user_name)))
print("Characters which you want to count:\t" + str(user_name.count(char_count))) | true |
8ca6c553c9d2fcf7d142b730e5b455a781cf22da | Phone5mm/MDP-NTU | /Y2/SS/MDP/NanoCar (Final Code)/hamiltonianPath.py | 2,928 | 4.125 | 4 | # stores the vertices in the graph
vertices = []
# stores the number of vertices in the graph
vertices_no = 0
graph = []
#Calculate Distance
def distance(p1, p2):
return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) ** 0.5
#Add vertex to graph
def add_vertex(v):
global graph
global vertices_no
global vertices
if v in vertices:
print("Vertex ", v, " already exists")
else:
vertices_no = vertices_no + 1
vertices.append(v)
if vertices_no > 1:
for vertex in graph:
vertex.append(0)
temp = []
for i in range(vertices_no):
temp.append(0)
graph.append(temp)
# Add edge between vertex v1 and v2 with weight e
def add_edge(v1, v2, e):
global graph
global vertices_no
global vertices
# Check if vertex v1 is a valid vertex
if v1 not in vertices:
print("Vertex ", v1, " does not exist.")
# Check if vertex v1 is a valid vertex
elif v2 not in vertices:
print("Vertex ", v2, " does not exist.")
else:
index1 = vertices.index(v1)
index2 = vertices.index(v2)
graph[index1][index2] = e
graph[index2][index1] = e
# Print the graph
def print_graph():
global graph
global vertices_no
for i in range(vertices_no):
for j in range(vertices_no):
if graph[i][j] != 0:
print(vertices[i], " -> ", vertices[j], \
" edge weight: ", graph[i][j])
def shortestPath(obstacle_android):
obstacle_number = len(obstacle_android)
print('No. of obstacles:',obstacle_number)
origin = [0,0]
obstacle_list = []
visited_vertex = [0] * obstacle_number
obstacle_distance = []
list = []
for i in range(0, obstacle_number):
obstacle_list.append ([obstacle_android[i][0],obstacle_android[i][1]])
for i in range(0, obstacle_number):
obstacle_distance.append(distance(origin,obstacle_list[i]))
add_vertex(i) # Add vertices to the graph
first_vertex = obstacle_distance.index(min(obstacle_distance))
# Add the edges between the vertices with the edge weights.
for i in range(0, obstacle_number-1):
for j in range(i+1, obstacle_number):
add_edge(i, j, round(distance(obstacle_list[i],obstacle_list[j]),2))
# Update the current vertex
current_vertex = first_vertex
shortest_path = [400] * obstacle_number
for i in range(0, obstacle_number):
shortest_path[i] = current_vertex
minimum = 200
min_index = 0
visited_vertex[current_vertex] = 1
for j in range (0, obstacle_number):
if graph[current_vertex][j]<minimum and current_vertex!=j:
if visited_vertex[j] == 0 :
minimum = graph[current_vertex][j]
min_index = j
current_vertex = min_index
for i in range(len(shortest_path)):
list.append(obstacle_android[shortest_path[i]])
return list
| true |
863817a9ec431234468b53402deaccd657227c15 | brianabaker/girlswhocode-SIP2018-facebookHQ | /data/tweet-visualize/data_vis_project_part4.py | 2,586 | 4.25 | 4 | '''
In this program, we will generate a three word clouds from tweet data.
One for positive tweets, one for negative, and one for neutral tweets.
For students who finish this part of the program quickly,
they might try it on the larger JSON file to see how much longer that takes.
They might also want to try subjective vs objective tweets.
'''
import json
from textblob import TextBlob
import matplotlib.pyplot as plt
from wordcloud import WordCloud
#Wrap this in a function because we'll use it several times
def get_filtered_dictionary(tweetblob, tweet_search):
#Filter Words
words_to_filter = ["about", "https", "in", "the", "thing", "will", "could", tweet_search]
filtered_dictionary = dict()
for word in tweetblob.words:
#skip tiny words
if len(word) < 2:
continue
#skip words with random characters or numbers
if not word.isalpha():
continue
#skip words in our filter
if word.lower() in words_to_filter:
continue
#don't want lower case words smaller than 5 letters
if len(word) < 5 and word.upper() != word:
continue;
#Try lower case only, try with upper case!
filtered_dictionary[word.lower()] = tweetblob.word_counts[word.lower()]
return filtered_dictionary
#Wrap this in a function so we can use it three times
def add_figure(filtered_dictionary, plotnum, title):
wordcloud = WordCloud().generate_from_frequencies(filtered_dictionary)
plt.subplot(plotnum)
plt.imshow(wordcloud, interpolation='bilinear')
plt.title(title)
plt.axis("off")
#Search term used for this tweet
#We want to filter this out!
tweet_search = "automation"
#Get the JSON data
tweet_file = open("tweets_small.json", "r")
tweet_data = json.load(tweet_file)
tweet_file.close()
#Combine All the Tweet Texts
positive_tweets = ""
negative_tweets = ""
neutral_tweets = ""
for tweet in tweet_data:
tweetblob = TextBlob(tweet['text'])
#Play with the numbers here
if tweetblob.polarity > 0.2:
positive_tweets += tweet['text']
elif tweetblob.polarity < -0.2:
negative_tweets += tweet['text']
else:
neutral_tweets += tweet['text']
#Create a Combined Tweet Blob
positive_blob = TextBlob(positive_tweets)
negative_blob = TextBlob(negative_tweets)
neutral_blob = TextBlob(neutral_tweets)
#Create a matplotlib figure
plt.figure(1)
#Create the three word clouds
add_figure(get_filtered_dictionary(negative_blob, tweet_search), 131, "Negative Tweets")
add_figure(get_filtered_dictionary(neutral_blob, tweet_search), 132, "Neutral Tweets")
add_figure(get_filtered_dictionary(positive_blob, tweet_search), 133, "Positive Tweets")
#Show all at once
plt.show()
| true |
f0e1863b39362db65c98698eff2b6c7150984475 | G-Radhika/PythonInterviewCodingQuiestions | /q5.py | 1,469 | 4.21875 | 4 | """
Find the element in a singly linked list that's m elements from the end.
For example, if a linked list has 5 elements, the 3rd element from the end is
the 3rd element. The function definition should look like question5(ll, m),
where ll is the first node of a linked list and m is the "mth number from the
end". You should copy/paste the Node class below to use as a representation of
a node in the linked list. Return the value of the node at that position.
e.g. 10->20->30->40->50
"""
head = None
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
# Function to insert a new node at the beginning
def push(new_data):
global head
new_node = Node(new_data)
new_node.next = head
head = new_node
def question5(ll, m):
main_ptr = ll
ref_ptr = ll
count = 0
if(head is not None):
while(count < m ):
if(ref_ptr is None):
print "%d is greater than the no. of nodes in list" %(m)
return
ref_ptr = ref_ptr.next
count += 1
while(ref_ptr is not None):
main_ptr = main_ptr.next
ref_ptr = ref_ptr.next
return main_ptr.data
# Main program
def main():
global head
# Make linked list 10->20->30->40->50
push(50)
push(40)
push(30)
push(20)
push(10)
print question5(head, 4)
print question5(head, 2)
print question5(head, 7)
if __name__ == '__main__':
main() | true |
6ed2cd27f06b2bb4f00f0b14afd94e42e7173164 | MichaelAuditore/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 706 | 4.40625 | 4 | #!/usr/bin/python3
def add_integer(a, b=98):
"""
Add_integer functions return the sum of two numbers
Parameters:
a: first argument can be integer or float
b: Second argument initialized with value 98, can be integer or float
Raises:
TypeError: a must be an integer or float
TypeError: b must be an integer or float
Returns:
int:Sum of a + b
"""
if type(a) != int and type(a) != float:
raise TypeError("a must be an integer")
if type(b) != int and type(b) != float:
raise TypeError("b must be an integer")
if type(a) == float:
a = int(a)
if type(b) == float:
b = int(b)
return (a + b)
| true |
a30bd99e44e61f3223dfa2ba64adb89dc19ad0b2 | Debu381/Conditional-Statement-Python-Program | /Conditional Statement Python Program/Guss.py | 213 | 4.125 | 4 | #write a python program to guess a number between 1 to 9
import random
target_num, guess_num=random.randint(1,10), 0
while target_num !=guess_num:
guess_num=int(input('Guess a number'))
print('Well guessed') | true |
b6ace974b9b55f653fe3c45d35a1c76fd3322f7e | lucasloo/leetcodepy | /solutions/36ValidSudoku.py | 1,530 | 4.1875 | 4 | # Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
# The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
# A partially filled sudoku which is valid.
# Note:
# A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
# check rows
for i in range(len(board)):
containMap = {}
for k in range(len(board[i])):
if board[i][k] != '.' and board[i][k] in containMap:
return False
containMap[board[i][k]] = 1
# check columns
for i in range(len(board[0])):
containMap = {}
for k in range(len(board)):
if board[k][i] != '.' and board[k][i] in containMap:
return False
containMap[board[k][i]] = 1
# check square
i = 0
while i < len(board):
k = 0
while k < len(board[0]):
containMap = {}
for x in range(3):
for y in range(3):
if board[i + x][k + y] != '.' and board[i + x][k + y] in containMap:
return False
containMap[board[x + i][k + y]] = 1
k += 3
i += 3
return True
| true |
98c092348ce916622847924b48967ef75ce99d9e | SaralKumarKaviti/Problem-Solving-in-Python | /Day-3/unit_convert.py | 1,738 | 4.25 | 4 | print("Select your respective units...")
print("1.centimetre")
print("2.metre")
print("3.millimetre")
print("4.kilometre")
choice= input("Enter choice(1/2/3/4)"
unit1=input("Enter units from converting:")
unit2=input("Enter units to coverting:")
number=float(input("Enter value:"))
if choice == '1':
if unit1 == 'centimetre' and unit2 == 'metre':
value=number/100
print("Metre value is {}".format(value))
elif unit1 == 'metre' and unit2 == 'centimetre':
value=number*100
print("Centimetre value is {}".format(value))
else:
print("Please enter the valid units...")
elif choice == '2':
if unit1 == 'millimetre' and unit2 == 'centimetre':
value=number/10
print("Millimetre value is {}".format(value))
elif unit1 == 'centimetre' and unit2 == 'millimetre':
value=number*10
print("Centimetre value is {}".format(value))
else:
print("Please enter the valid units...")
elif choice == '3':
if unit1 == 'millimetre' and unit2 == 'metre':
value=number/1000
print("Millimetre value is {}".format(value))
elif unit1 == 'metre' and unit2 == 'millimetre':
value=number*1000
print("Metre value is {}".format(value))
else:
print("Please enter the valid units...")
elif choice == '4':
if unit1 == 'kilometre' and unit2 == 'metre':
value=number*1000
print("Kilometre value is {}".format(value))
elif unit1 == 'metre' and unit2 == 'kilometre':
value=number/1000
print("Metre value is {}".format(value))
elif unit1 == 'millimetre' and unit2 == 'kilometre':
value=number/1000000
else:
print("Please enter the valid units...")
| true |
e49dd0973443fb86684f5ef112091382d7afa607 | ClaudiaSianga/Python-para-Zumbis | /Lista3/exercicio03_guilhermelouro_01.py | 404 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor
seja inválido e continue pedindo até que o usuário informe um valor válido.
"""
nota = ""
while nota < 0 or nota > 10:
nota = float(input("Digite uma nota de 0 a 10: "))
print "Nota inválida, digite apenas uma nota de 0 a 10."
print("Nota: %.1f" %nota)
| false |
2d082dda2f464f6da9d9a043a90ca7599a4b92bd | anikanastarin/Learning-python | /Homework session 4.py | 1,516 | 4.375 | 4 | '''#1. Write a function to print out numbers in a range.Input = my_range(2, 6)Output = 2, 3, 4, 5, 6
def my_range(a,b):
for c in range(a,b+1):
print (c)
my_range(2,6)
#2. Now make a default parameter for “difference” in the previous function and set it to 1. When the difference value is passed, the difference between the numbers should change accordingly.
def increment(a,b,diff=1):
w=a;
while w<=b:
print(w)
w=w+diff
increment(2,6)
#3. Write a Python program to reverse a string. Go to the editor Sample String: "1234abcd" Expected Output: "dcba4321"
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "123abcd"
print ("Sample String: ",end="")
print (s)
print ("Reverse Output: ",end="")
print (reverse(s))
#4. Write a function to return the factorial of an input. Assign the value to a new variable and print it.
def factorial(x):
a=1;
for c in range (0,x):
a=a*(x-c)
return a
z=int(input("Input Number:"))
factorial(z)
w=factorial(z)
print("value of new variable:",w)
#5. Write a Python function that takes a number as a parameter and check the number is prime or not. Return True or False.
def prime(y):
f=0;
for x in range(2,y):
if y%x==0:
f=f+1
if f>=1:
return False
else:
return True
c=int(input("Enter any prime integer:"))
print(prime(c))'''
| true |
6ae607ac50b7fe370e6257fd083fc369a5ac7a14 | Dcnqukin/A_Byte_of_Python | /while.py | 383 | 4.15625 | 4 | number=23
running=True
while running:
guess=int(input("Enter an integer:"))
if guess==number:
print("Congratulation, you guessd it.")
running=False #this causes the while loop to stop
elif guess<number:
print("No, it is a little higher")
else:
print("No, it is a little lower")
else:
print("the while loop is over")
print("done")
| true |
b5cf0e1ec9d8ad7f5f60e89891ee08ef6e3bc6f9 | marieramsay/IT-1113 | /Miles_To_Kilometers_Converter.py | 2,618 | 4.5625 | 5 | # Marie Ramsay
# Prompts the user to select whether they want to convert Miles-to-Kilometers or Kilometers-to-Miles, then asks the user
# to enter the distance they wish to convert. Program converts value to the desired unit.
# Program will loop 15x.
import sys
# converts input from miles to kilometers
def convert_miles_to_km(amount):
the_answer = amount / 0.6214
return the_answer
# converts input from kilometers to miles
def convert_km_to_miles(amount):
the_answer = amount * 0.6214
return the_answer
print("Welcome to the conversion calculator. This program will run 15 times.")
# use for in loop to run the procedure below 15X
for x in range(15):
# keep track of what data set the process is on
data_number = x + 1
data_number = str(data_number)
# ask user which conversion they want to do
print("Please enter which conversion you need to be done for conversion " + data_number + ":")
print("A. Miles-to-Kilometers")
print("B. Kilometers-to-Miles")
# save the user's selection to a variable
conversion_selection = input()
# decide which unit the input will be in
if (conversion_selection == "A") or (conversion_selection == "a"):
unit_name = "miles"
elif (conversion_selection == "B") or (conversion_selection == "b"):
unit_name = "kilometers"
else:
sys.exit('Your input is invalid. Please enter A or B. The program will restart.')
# ask the user for the value they want to convert
print("Please enter how the amount of " + unit_name + " you want to convert:")
# save the value to a variable
convert_this = input()
# change string to float
convert_this = float(convert_this)
# decide which function to send the variable to
if unit_name == "miles":
converted_amount = convert_miles_to_km(convert_this)
converted_amount = str(converted_amount)
convert_this = str(convert_this)
print(convert_this + " " + unit_name + " converts to " + converted_amount + " kilometers.")
print(" ")
else:
converted_amount = convert_km_to_miles(convert_this)
converted_amount = str(converted_amount)
convert_this = str(convert_this)
print(convert_this + " " + unit_name + " converts to " + converted_amount + " miles.")
print(" ")
# if this is the last conversion, let the user know.
if data_number == "15":
print("You have converted 15 values.")
print("Thank you for using the Conversion Calculator!")
| true |
e07ac75e79a257241d4a467320e113247db4df8b | calebwest/OpticsPrograms | /Computer_Problem_2.py | 2,211 | 4.40625 | 4 | # AUTHOR: Caleb Hoffman
# CLASS: Optics and Photonics
# ASSIGNMENT: Computer Problem 2
# REMARKS: Enter a value for the incident angle on a thin lens of 2.0cm, and
# the focal length. A plot will open in a seperate window, which will display
# light striking a thin lens, and the resulting output rays. This program uses
# a derived ray transfer matrix equation to compute the ouput angle of a thin
# lens.
# DISCLAIMER: This program will be further developed to compute a series of
# lenses to achieve other various tasks.
import matplotlib.pyplot as plt
import math
from math import tan
from math import pi
# The primary function of this program is to compute the result of light
# striking a thin lens of a specific angle and focal length
def main():
d = 2.0 # centimeters
input_angle = float(input("Enter Incident Angle: "))*(pi/180)
f = float(input("Enter Focal Length: "))
# Declares domain for both sides of the lens as a list constrained to f input
xDomain = [x for x in range(int(-f*1.3), 1)]
xDomain_Output = [x for x in range(0, int(f*1.3))]
# The slope of the line is the tangent of the input angle
m = tan(input_angle)
# Chart labels
plt.title("Thin Lens-Object at Infinity")
plt.xlabel("Optical Axis (cm)")
plt.ylabel("Ray Elevation (cm)")
# Imposes a grid making the plot easier to read
plt.grid(color='black', linestyle=':', linewidth = 0.5)
# vlines (x=0, ymin, ymax) draws out the lens (in black)
plt.vlines(0, (-d/2), (d/2), color = 'black')
# This loop computes three identical rays striking
# the lens. Followed by the output
for i in range(3):
# This section computes incidents rays
zRange = [m*x+((1-i)*(d/2)) for x in xDomain]
plt.plot(xDomain, zRange, color = 'red')
# This section computes transmitted rays
output_angle = (input_angle) - (((1-i)*(d/2))/f)
m_Output = tan(output_angle)
zRange_Output = [m_Output*x+((1-i)*(d/2)) for x in xDomain_Output]
plt.plot(xDomain_Output, zRange_Output, color = 'blue')
# This displays the generated plot (ray trace display)
plt.show()
# Invokes main
main()
| true |
756a096e6c156f1f5be7347067903a3135008535 | 22fansje/python | /modb_challenge.py | 1,034 | 4.21875 | 4 | def main():
#Get's info on the user's name than greets them
first_name = input("What is your first name?: ")
last_name = input("What is your last name?: ")
print("Hello, %s %s!"%(first_name,last_name))
print()
#Lists the foods avaliable
food = ['Cookie', 'Steak', 'Ice cream', 'Apples']
for food in food:
print (food)
#showing age in days, weeks and months
print()
age_in_years = float(input("How old are you?: "))
days_in_years = age_in_years * 365
weeks_in_years = age_in_years * 52.143
months_in_years = age_in_years * 12
print("You're at least",days_in_years,"days old.")
print("You,re at least",weeks_in_years,"weeks old.")
print("You're at least",months_in_years,"months old.")
#Makes a humorous statement
noun = input("Enter a noun: ")
verb = input("Enter a verb: ")
adjective = input("Enter a adjective: ")
place = input("Enter a place: ")
print("Take your %s %s and %s it at the %s"%(adjective, noun, verb, place))
main() | true |
7f6071b0aa4ea291a567a7f766ffaef00349e373 | geronimo0630/2021 | /clases/operaciones.py | 683 | 4.15625 | 4 | # se utilizan dos int y se les da un valor designado
numeroA = 87
numeroB = 83
#se suman los int
sumar = numeroA + numeroB
#pone en pantalla el resultado
print ("el resultado es", sumar)
#se restan los int
restar = numeroA - numeroB
#pone en pantalla el resultado
print ("el resultado es ",restar)
#se multiplican los int
multiplicar = numeroA * numeroB
#pone en pantalla el resultado
print ("el resultado es",multiplicar)
#se dividen los int
dividir = numeroA / numeroB
#pone en pantalla el resultado
print ("el resultado es",dividir)
#un int a la exponencial del otro int
exponente = numeroA ** numeroB
#pone en pantalla el resultado
print ("el resultado es",exponente)
| false |
6fd29cfa6d3667c2316c0322e35451ee9bfeefc2 | dwlovelife/Python-Note | /code/basic/day05/test02.py | 249 | 4.1875 | 4 | def factorial(num):
"""
求阶乘
"""
result = 1
for x in range(1, num + 1):
result *= x
return result
m = int(input("请输入m:"))
n = int(input("请输入n:"))
print(factorial(m)//factorial(n)//(factorial(m - n))) | false |
acf5f7ff2b563f54375c5dbfeb24294d6673f2f8 | dwlovelife/Python-Note | /code/basic/day07/test04.py | 262 | 4.15625 | 4 | """
集合切片
"""
def main():
list = [1, 2, 3, 4]
list.append(5)
for x in list:
print(x, end = " ")
print()
list2 = list[2:4]
print(list2)
list3 = list[::-1]
print(list3)
if __name__ == "__main__":
main()
| false |
88222260f53d9cf84b52f5c4c74cf85ebafb8b82 | harry990/coding-exercises | /strings/generate-all-permutations-of-a-string.py | 534 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "David S. Batista"
__email__ = "dsbatista@inesc-id.pt"
"""
- Generate a list of all permutation of a string
"""
def permute(s):
res = []
if len(s) == 1:
res = [s]
else:
for i, c in enumerate(s):
for perm in permute(s[:i] + s[i+1:]):
res += [c + perm]
return res
def main():
s = "ABC"
for x in (enumerate(s)):
print x
for permutation in permute(s):
print permutation
if __name__ == "__main__":
main()
| false |
19eb4be275bd3a0477a42ec205be2596a5c459db | harry990/coding-exercises | /trees/tree-string-expression-balanced-parenthesis.py | 1,107 | 4.15625 | 4 |
from collections import defaultdict
"""
Given a tree string expression in balanced parenthesis format:
(A(B(C)(D))(E)(F))
A
/ | \
B E F
/ \
C D
The function is to return the root of the tree you build, and if you can please
print the tree with indentations like above.
You can print in the simplified format.
A
B E F
C D
"""
def parse_string(s):
levels = defaultdict(list) # dict of lists
level_count = 0
for i, c in enumerate(s):
if c == '(':
level_count += 1
elif c == ')':
level_count -= 1
else:
levels[level_count].append(c)
return levels
def print_levels(levels):
for level in levels:
for c in levels[level]:
print c,
print
def main():
#tree = "(A(B(C))"
#tree = "(A(B(C)D)"
tree = "(A(B(C)(D))(E)(F))"
levels = parse_string(tree)
# TODO make sure that levels are accesed in order
# sort the dict into a list
print_levels(levels)
if __name__ == "__main__":
main()
| true |
1c90e6c43a74e92dc37477692317ae008d9ec415 | btrif/Python_dev_repo | /Courses, Trainings, Books & Exams/Lynda - Python 3 Essential Training/11 Functions/generator_01_sequence_tuple_with_yield.py | 1,411 | 4.59375 | 5 | #!/usr/bin/python3
# A generator function is function that return an iterator object.
# So this is how you create functionality that can be used in a for loop or any
# place an iterator is allowable in Python
def main():
print("This is the functions.py file.")
for i in inclusive_range(2, 125, 4):
print(i, end =' ')
def inclusive_range(*args): # we make an inclusive range function
numargs = len(args)
if numargs < 1: raise TypeError('requires at least one argument')
elif numargs == 1:
start = 0
step = 1
stop = args[0]
elif numargs == 2:
(start, stop) = args
step = 1
elif numargs == 3:
(start, stop, step) = args
else: raise TypeError('inclusive_range expected at most 3 arguments, got {}'.format(numargs))
i = start
while i <= stop:
yield i # yield does it return 'i' but because we are using yield instead of return
i += step # the next time the function is called execution will continue right after
# the yield statement. It will get incremented with step.
# Difference between yield and return :
# as the function gets called over and over again, each time execution begins right after
# the yield and continues as if the function were running continually
if __name__ == "__main__": main()
| true |
89c5785788e5171d33ef0e2cc34622b8781004af | btrif/Python_dev_repo | /BASE SCRIPTS/Logic/basic_primes_generator.py | 980 | 4.125 | 4 | #!/usr/bin/python3
# comments.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
for n in primes(): #generate a list of prime numbers
if n > 100: break
print(n, end=' ')
def isprime(n):
if n == 1:
return False
for x in range(2, n):
if n % x == 0:
return False
else:
return True
def primes(n=1):
while(True):
if isprime(n): yield n
n += 1
print(isprime(31) == True)
#############################################
# from MITx.6.00.1x Course
# A Different Version :
def genPrimes():
primes = [] # primes generated so far
last = 1 # last number tried
while True:
last += 1
for p in primes:
if last % p == 0:
break
else:
primes.append(last)
yield last
if __name__ == "__main__": main()
| true |
6c9a13d67dea2ce2672fc0dad170207bdfce715f | btrif/Python_dev_repo | /BASE SCRIPTS/module bisect pickle.py | 2,002 | 4.46875 | 4 | import bisect, pickle
print(dir(bisect))
########################
# The bisect() function can be useful for numeric table lookups.
# This example uses bisect() to look up a letter grade for an exam score (say)
# based on a set of ordered numeric breakpoints: 90 and up is an ‘A’, 80 to 89 is a ‘B’, and so on:
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
i = bisect.bisect(breakpoints, score)
return grades[i]
print( [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]] )
#################################
# The above bisect() functions are useful for finding insertion points but
# can be tricky or awkward to use for common searching tasks.
# The following five functions show how to transform them into the standard lookups for sorted lists:
def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect.bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError
def find_lt(a, x):
'Find rightmost value less than x'
i = bisect.bisect_left(a, x)
if i:
return a[i-1]
raise ValueError
def find_le(a, x):
'Find rightmost value less than or equal to x'
i = bisect.bisect_right(a, x)
if i:
return a[i-1]
raise ValueError
def find_gt(a, x):
'Find leftmost value greater than x'
i = bisect.bisect_right(a, x)
if i != len(a):
return a[i]
raise ValueError
def find_ge(a, x):
'Find leftmost item greater than or equal to x'
i = bisect.bisect_left(a, x)
if i != len(a):
return a[i]
raise ValueError
print('\n-------------------pickle module---------------------\n')
print(dir(pickle))
# Save a dictionary into a pickle file.
import pickle
favorite_color = { "lion": "yellow", "kitty": "red" }
pickle.dump( favorite_color, open( "save.txt", "wb" ) )
# Load the dictionary back from the pickle file.
favorite = pickle.load( open( "save.txt", "rb" ) )
print(favorite,'\nWOW ! That was nice !') | true |
2dbae09466384658d5906425b8aeb6095495ac1a | btrif/Python_dev_repo | /BASE SCRIPTS/searching.py | 1,535 | 4.75 | 5 | # ### Python: Searching for a string within a list – List comprehension
# The simple way to search for a string in a list is just to use ‘if string in list’. eg:
list = ['a cat','a dog','a yacht']
string='a cat'
if string in list:
print ('found a cat!')
# But what if you need to search for just ‘cat’ or some other regular expression and return a list of the list
# items that match, or a list of selected parts of list items that match.
# Then you need list comprehension.
import re
list = ['a cat','a dog','a yacht','cats']
regex=re.compile(".*(cat).*")
print([m.group(0) for l in list for m in [regex.search(l)] if m])
print([m.group(1) for l in list for m in [regex.search(l)] if m])
# Lets work through that. Firstly we’re going to use the regular expression library so we import that. re.compile
# lets us create a regular expression that we can later use for search and matching.
#
# Now lets look at a simpler comprehension line:
print([m for l in list for m in [regex.search(l)]])
# This is creating a list of the results of running regex.search() on each item in l.
# Next we want to exclude the None values. So we use an if statement to only include the not None values:
print([m for l in list for m in [regex.search(l)] if m ])
# Lastly rather than returning just a list of the m’s, which are RE match objects, we get the information we want from them.
print([m.group(0) for l in list for m in [regex.search(l)] if m])
print([m.group(1) for l in list for m in [regex.search(l)] if m]) | true |
a42127989a11eabe0a112f58ec1e6ca0a4be9bcd | btrif/Python_dev_repo | /BASE SCRIPTS/OOP/static_variables.py | 2,037 | 4.5 | 4 | # Created by Bogdan Trif on 17-07-2018 , 3:34 PM.
# I noticed that in Python, people initialize their class attributes in two different ways.
# The first way is like this:
class MyClass:
__element1 = 123 # static element, it means, they belong to the class
__element2 = "this is Africa" # static element, it means, they belong to the class
def __init__(self):
pass
# pass or something else
# The other style looks like:
class MyClass:
def __init__(self):
self.__element1 = 123
self.__element2 = "this is Africa"
# Which is the correct way to initialize class attributes?
# ANSWER :
'''
Both ways aren't correct or incorrect, they are just two different kind of class elements:
1. Elements outside __init__ method are static elements, it means, they belong to the class.
2. Elements inside the __init__ method are elements of the object (self ), they don't belong to the class.
You'll see it more clearly with some code:
'''
class MyClass:
static_elem = 123
def __init__(self):
self.object_elem = 456
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
print('# Initial values of both elements')
print( ' c1 class : ',c1.static_elem, c1.object_elem)
# 123 456
print( ' c2 class : ', c2.static_elem, c2.object_elem )
# 123 456
# Nothing new so far ...
# Let's try changing the static element
print('\n# Lets try changing the static element')
MyClass.static_elem = 999
print( ' c1 class : ',c1.static_elem, c1.object_elem)
# 999 456
print( ' c2 class : ', c2.static_elem, c2.object_elem )
# 999 456
# Now, let's try changing the object element
print('\n# Now, let s try changing the object element')
c1.object_elem = 888
print( ' c1 class : ',c1.static_elem, c1.object_elem)
# 999 888
print( ' c2 class : ', c2.static_elem, c2.object_elem )
# 999 456
# As you can see, when we changed the class element, it changed for both objects. But, when we
# changed the object element, the other object remained unchanged.
| true |
0b4eae1855d2a62e6152419526c4f49d08c1085d | btrif/Python_dev_repo | /Courses, Trainings, Books & Exams/EDX - MIT - Introduction to Comp Science I/bank_credit_account.py | 844 | 4.65625 | 5 | '''
It simulates a credit bank account. Suppose you have a credit. You pay each month a monthlyPaymentRate
and each month an annualInterestRate is calculated for the remaining money resulting in a remaining balance
each month.
'''
balance = 5000 # Balance
monthlyPaymentRate = 2/100 # Monthly payment rate, %
annualInterestRate = 18/100 # Annual Interest Rate, %
#def bank_account(balance , annualInterestRate , monthlyPaymentRate ):
for i in range(1,13):
balance = balance - (monthlyPaymentRate * balance)
balance = balance + (balance * annualInterestRate /12)
print(round(balance , 2),' ; ', round(-monthlyPaymentRate*balance ,2) , ' ; ', round((balance * annualInterestRate /12),2))
print ('\nRemaining balance after a year : ',round(balance, 2))
#print(bank_account(484, 0.2, 0.04)) | true |
d8cd80845a11d5a6c9f469729cc42f3cf6f5a978 | btrif/Python_dev_repo | /BASE SCRIPTS/object_types_conversion.py | 2,527 | 4.125 | 4 | print('----------'*13)
print('........................Function which transforms a string into a list: ....................')
def string_to_list(strng):
if (type(strng) == str):
lst = list(strng)
print(lst)
print('The type of ',lst, 'is : ',type(lst))
return lst
else: print('Not a string type !')
string_to_list('1218565')
print('----------'*13)
print('........................Function which transforms a list into a string: ....................')
def list_to_string(lst):
if ( type(lst) == list ):
strng = ''.join(lst)
print(strng)
print('Type of ',strng,' is: ',type(strng))
return strng
else: print('Not a list (array) type !')
list_to_string(['4','5','7','9','1','8'])
print('----------'*13)
print('........................Function which transforms a tuple into a string: ....................')
def tuple_to_string(tup):
if ( type(tup) == tuple ):
strng = ''.join(map(str, (tup)))
print(strng)
print('Type of ',strng,' is: ',type(strng))
return strng
else: print('Not a tuple type !')
print('........................Function which transforms a tuple into a list: ....................')
def tuple_to_list(tup):
if ( type(tup) == tuple ):
lst = [str(i) for i in tup]
print(lst)
print('Type of ',lst,' is: ',type(lst))
return lst
else: print('Not a tuple type !')
tup = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'); print(tup, type(tup))
tuple_to_string(tup)
bic=(9, 8, 1); print(bic ,type(bic))
tuple_to_string(bic)
st=('4','3',3,2,2) ; print(type(st),st)
tuple_to_list((st))
# Simple command for TUPLE TO STRING Conversion :
mystring = ' '.join(map(str, (34.2424, -64.2344, 76.3534, 45.2344)))
print(mystring, type(mystring))
# Simple TUPLE TO LIST CONVERSION :
just_tuple=(34.2424, -64.2344, 76.3534, 45.2344); print(type(just_tuple), just_tuple)
A = [str(i) for i in (34.2424, -64.2344, 76.3534, 45.2344)] ;
print(type(A), A)
# String going backwards, REVERSE STRING:
#So, in a nutshell, if :
a = '12345'
print(a[::2]) # becomes 135
print(a[::-1]) #becomes 54321
print(a[::-2]) #becomes 531
print('-----'*20)
# Count unique items in a list :
words = ['a', 'b', 'c', 'a']
unique_words = set(words) # == set(['a', 'b', 'c'])
unique_word_count = len(unique_words) # == 3
print('Unique words : ',len(unique_words))
print('-----'*20)
b = [a for a in range(11)] ; print('The sum of a list of integers : ',sum(b))
| false |
53958a00677713402c549640639d87442b94d9d2 | btrif/Python_dev_repo | /plots exercises/line_animation.py | 1,087 | 4.40625 | 4 | __author__ = 'trifb' #2014-12-19
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure() #defining the figure
ax = plt.axes(xlim=(0, 10), ylim=(-8, 8)) # x-axes limits and y-axes limits
line, = ax.plot([], [], lw=4, ) # establishing two lists and lw = linewidth
# initialization function: plot the background of each frame
def init():
# line.set_data([], [])
return line,
'''The next piece is the animation function.
It takes a single parameter, the frame number i, and draws a sine wave with a shift that depends on i:'''
# animation function. This is called sequentially
def animate(i):
x = np.linspace(0, 1+ 0.09*i, 100)
y = (1 - 0.02 * i) # the 'i' variable makes the sine function flow
line.set_data(x, y)
return line,
print(line)
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
plt.grid(); plt.show() | true |
24e78bf77cad25af185baf4fd71d6953e86620c7 | fransikaz/PIE_ASSIGNMENTS | /homework8.py | 2,880 | 4.5 | 4 | import os
# import os.path
from os import path
'''
HOMEWORK #8:
Create a note-taking program. When a user starts it up, it should prompt them for a filename.
If they enter a file name that doesn't exist, it should prompt them to enter the text they want to write to the file.
After they enter the text, it should save the file and exit.
If they enter a file name that already exists, it should ask the user if they want:
A) Read the file
B) Delete the file and start over
C) Append the file
'''
# Notebook as existing file. For testing code
with open("Notebook.txt", "w") as existingFile:
for i in range(5):
notes = "This is a note for existing filename\n"
existingFile.write(notes)
def Notes():
Filename = input("Please enter the filename: ")
if path.exists("{}.txt".format(Filename)): # Do if filename already exists
print("The filename already exists. What what you like to do with this file?")
option = input(
"Enter 'r' to read, 'd' to delete, 'a' to append to file \n or 's' to replace a line in the file: ")
if option == "r": # if user wants to read from existing file
with open("{}.txt".format(Filename), "r") as NoteFile:
print(NoteFile.read())
elif option == "a": # If user wants to append new notes
with open("{}.txt".format(Filename), "a") as NoteFile:
notesTaken = input(
"Type your notes and hit enter when done: \n")
NoteFile.write("\n" + notesTaken)
with open("{}.txt".format(Filename), "r") as NoteFile:
print(NoteFile.read())
elif option == "s": # replacing a single line
with open("{}.txt".format(Filename), "r") as NoteFile:
lineNum = int(
input("Please enter line number you want to replace: "))
notesTaken = input(
"Type your notes and hit enter when done: \n")
NoteFileList = NoteFile.readlines()
NoteFileList[lineNum] = notesTaken + "\n"
with open("{}.txt".format(Filename), "w") as NoteFile:
for List in NoteFileList:
NoteFile.write(List)
with open("{}.txt".format(Filename), "r") as NoteFile:
print(NoteFile.read())
elif option == "d": # if user wants to delete existing file
os.remove("{}.txt".format(Filename))
Notes()
else: # Do if filename does not exist
with open("{}.txt".format(Filename), "w") as NoteFile:
notesTaken = input("Type your notes and hit enter when done: \n")
NoteFile.write(notesTaken)
with open("{}.txt".format(Filename), "r") as NoteFile:
print(NoteFile.read())
Notes()
| true |
d20f44d4150c21a96b178b3aac74b45e25c5fab1 | AndersenDanmark/udacity | /test.py | 2,516 | 4.5 | 4 | def nextDay(year, month, day):
"""
Returns the year, month, day of the next day.
Simple version: assume every month has 30 days.
"""
# YOUR CODE HERE
if day+1>30:
day=1
if month+1>12:
month=1
year=year+1
else:
month=month+1
else:
day=day+1
return (year,month,day)
def dateIsBefore(year1, month1, day1, year2, month2, day2):
"""Returns True if year1-month1-day1 is before
year2-month2-day2. Otherwise, returns False."""
if year1 < year2:
return True
if year1 == year2:
if month1 < month2:
return True
if month1 == month2:
return day1 < day2
return False
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar, and the first date is not after
the second. Assertation added for date order"""
# YOUR CODE HERE!
assert(dateIsBefore(year1, month1, day1, year2, month2, day2)==True),"the first date is not before the second date!"
dayCount=1
currentDay=nextDay(year1,month1,day1)
while currentDay[0]<year2:
currentDay=nextDay(currentDay[0],currentDay[1],currentDay[2])
dayCount=dayCount+1
while currentDay[1]<month2:
currentDay=nextDay(currentDay[0],currentDay[1],currentDay[2])
dayCount=dayCount+1
while currentDay[2]<day2:
currentDay=nextDay(currentDay[0],currentDay[1],currentDay[2])
dayCount=dayCount+1
return dayCount
def test():
"""This is a test function for the daysBetweenDates function"""
test_cases = [((2012,9,30,2012,10,30),30),
((2012,1,1,2013,1,1),360),
((2012,9,1,2012,9,4),3),
((2013,1,1,1999,12,31), "AssertionError")]
for (args, answer) in test_cases:
try:
result = daysBetweenDates(*args)
if result != answer:
print ("Test with data:", args, "failed")
else:
print ("Test case passed!")
except AssertionError:
if answer == "AssertionError":
print ("Nice job! Test case {0} correctly raises AssertionError!\n".format(args))
else:
print ("Check your work! Test case {0} should not raise AssertionError!\n".format(args))
test()
| true |
14389832de4c1e1317bd88f01b2686a83eb36017 | KeelyC0d3s/L3arning | /squareroot.py | 1,126 | 4.375 | 4 | # Keely's homework again.
# Please enter a positive number: 14.5
# The square root of 14.5 is approx. 3.8.
# Now, time to figure out how to get the square root of 14.5
#import math
#math.sqrt(14.5)
#print( "math.sqrt(14.5)", math.sqrt(14.5))
#Trying Newton Method.
#Found code here: https://tinyurl.com/v9ob6nm
# Function to return the square root of
# a number using Newtons method
def squareRoot(n, l) :
# Assuming the sqrt of n as n only
x = n
# To count the number of iterations
count = 0
while (1) :
count += 1
# Calculate more closed x
root = 0.5 * (x + (n / x))
# Check for closeness
if (abs(root - x) < l) :
break
# Update root
x = root
return root
# Driver code
if __name__ == "__main__" :
n = 14.5
l = 0.00001
print(squareRoot(n, l))
#I'll be honest, I still don't completely understand this.
#I searched the internet for Newton Method, square root Python
#and the above program is what I found. I'll need to spend more time with it.
| true |
dad8ce6b3d20dff1ffcaef7146ecfbd88c3b54b0 | adarshk007/DATA-STURCTURES-and-ALGORITHMS | /DATA STRUCTURE/QUEUE/queue_all.py | 886 | 4.15625 | 4 | # QUEUE
#SUB TOPICS :
"""
1}Enqueue
2}Dequeue
3}Print: rear element
front element
"""
# ADARSH KUMAR
#__________________________________CODE________________________________________#
class queue:
def __init__(self):
self.new_queue=[]
self.size=0
self.front=0
self.rear=0
def enqueue(self,data):
self.new_queue.append(data)
self.rear=self.rear+1
self.size=self.size+1
def dequeue(self):
self.new_queue.pop(0)
self.front=self.front+1
self.size=self.size-1
def printque(self):
print("front is on",self.front,sep=" ")
print("rear is on",self.rear,sep=" ")
print("size:",self.size,"and queue is:",self.new_queue,sep=" ")
que=queue()
que.enqueue(4)
que.enqueue(5)
que.printque()
que.dequeue()
que.printque()
| false |
8aaf6cd5b8634dfdcd5a6e6923dbea448100b983 | carlanlinux/PythonBasics | /9/9.6_ClonningLists.py | 418 | 4.25 | 4 | '''
If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of the
list itself, not just the reference. This process is sometimes called cloning, to avoid the ambiguity of
the word copy.
The easiest way to clone a list is to use the slice operator.
'''
a = [81,82,83]
b = a[:] # make a clone using slice
print(a == b)
print(a is b)
b[0] = 5
print(a)
print(b) | true |
ce9a774c06363afc1f03da671d9276d5ae11b758 | MalteMagnussen/PythonProjects | /week2/objectOriented/Book.py | 974 | 4.21875 | 4 | from PythonProjects.week2.objectOriented import Chapter
class Book():
"""A simple book model consisting of chapters, which in
turn consist of paragraphs."""
def __init__(self, title, author, chapters=[]):
"""Initialize title, the author, and the chapters."""
self.title = title
self.author = author
self.chapters = chapters
def __repr__(self):
return 'Book(%r, %r, %r)' % (self.title, self.author, self.chapters)
def __str__(self):
return '{name} by {by} has {nr_chap} chapters.'.format(
name=self.title, by=self.author, nr_chap=len(self.chapters))
def read(self, chapter=1):
"""Simulate reading a chapter, by calling the reading
method of a chapter."""
self.chapters[chapter - 1].read()
def open_book(self, chapter=1) -> Chapter:
"""Simulate opening a book, which returns a chapter
object."""
return self.chapters[chapter - 1]
| true |
0c209da23bd3717cad46e0bb0ad8d2e5401c177b | ReWKing/StarttoPython | /操作列表/创建数值列表/numbers.py | 208 | 4.34375 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# Author:William Gin
# 使用函数range()
for value in range(1, 5):
print(value)
# 使用函数range()创建数字列表
numbers = list(range(1, 6))
print(numbers)
| false |
3e31f087d0703727310e782ad61f60682fc50d2a | tizziana/GrafoMundial | /pruebas/heap.py | 2,062 | 4.1875 | 4 |
# -------------------------------------------------------------------
# PRIMITIVAS DEL HEAP |
# -------------------------------------------------------------------
class Heap:
"""Representa un heap de min con operaciones de encolar, desencolar,
ver_maximo, cantidad y verificar si está vacio."""
def __init__(self):
"""Crea un heap vacio."""
self.items = []
self.cantidad = 0
def encolar(self, elemento, peso):
"""Agrega el elemento como ultimo del heap."""
self.items.append([elemento, peso])
self.cantidad += 1
self.upheap(self.cantidad - 1)
def esta_vacio(self):
"""Devuelve True si el heap esta vacio, False si no."""
return self.cantidad == 0
def desencolar(self):
"""Desencola el primer elemento y devuelve su valor.
- En caso de que el heap este vacio, levanta ValueError."""
if self.esta_vacio():
raise ValueError("El heap esta vacio")
elemento = self.items.pop(0)
self.cantidad -= 1
self.downheap(self.cantidad, 0)
return elemento
def cantidad(self):
"""Devuelve la cantidad de elementos que tiene el heap."""
return self.cantidad
def ver_maximo(self):
"""Devuelve el elemento maximo del heap."""
return self.items[0]
def upheap(self, posicion):
if not posicion: return
pos_padre = int((posicion - 1) / 2)
if self.items[(posicion)][1] > self.items[(pos_padre)][1]:
return
self.items[posicion], self.items[pos_padre] = self.items[pos_padre], self.items[posicion]
self.upheap(pos_padre)
def downheap(self, tamanio, posicion):
if (posicion >= tamanio): return
pos_h_izq = 2 * posicion + 1
pos_h_der = pos_h_izq + 1
pos_max = posicion
if ((pos_h_izq < tamanio) and (self.items[pos_h_izq][1] < self.items[pos_max][1])):
pos_max = pos_h_izq
if ((pos_h_der < tamanio) and (self.items[pos_h_der][1] < self.items[pos_max][1])):
pos_max = pos_h_der
if (posicion != pos_max):
self.items[posicion], self.items[pos_max] = self.items[pos_max], self.items[posicion]
self.downheap(tamanio, pos_max)
self.downheap(tamanio, posicion + 1) | false |
875bc855207b37cedee6c9799951afcb63b2bf5f | JohnEstebanAP/FundamentosProgramacionPython | /Sesión1/sesion1.py | 1,894 | 4.46875 | 4 | #Instrucciones, Variables, y Operaciones Matemáticas
#Comencemos por lo más sencillo...
# Recuerda que programar significa
# darle instrucciones al computador
# para que haga lo que yo quiera.
# Podemos comenzar por pedirle que
# imprima algo para nosotros:
print("¡Hola soy john!")
print("\n")
# Para asignarle un valor a una variable lo reslisamos asi: {valor_uno=1}
# python es de tipado devil por lo qe no tenemos que indicar si es de tipo
# int, fload, string, buleano, etc
valor_uno = 5
valor_dos = 8
total = valor_uno + valor_dos
print (f"la suma del numero: {valor_uno} + {valor_dos} es: {total}") # con f"{}" podemor imprimir las variables o concatenar la variables conjunto el texto
#Y si quisieramos leer el valor?
# Python cuenta con la función
# input() para leer valores.
# Vamos a ver como usarla
print("\n")
valor_uno = int(input("digita un numero: ")) # de esta manera tanbien podemos imprimir a la hora de solicitar un valor
valor_dos = int(input("digita un numero: ")) # con int(input()) pasamos el valor que resibimos de tipo testo a un entero
total = valor_uno + valor_dos
print (f"la suma del numero: {valor_uno} + {valor_dos} es: {total}") # con f"{}" podemor imprimir las variables o concatenar la variables conjunto el texto
print("\n")
'''
print("\n")
print("División real")
print("división real ente 6 / 2: ",6/2)
print("división real ente 5 / 2: ",5/2)
print("\n")
print("Division con redondeo")
print("Division con redondeo ente 6 // 2: ",6//2)
print("Division con redondeo ente 5 // 2: ",5//2)
print("\n")
'''
#Actividad 3
#El área de un cuadrado puede
# calcularse como a^2.
# Escribe el código para
# calcular e imprimir el área del cuadrado
print("Por favor ingrese el lado del cuadrado en metros para calcual la Area")
area = float(input("Area: "))
area = area**2
print("El area del cuadrado es de:", area, "metros cuadrados") | false |
fdde0b3b81e7987289e4134ff4a523f5b6544587 | saurabh-pandey/AlgoAndDS | /leetcode/binary_search/sqrt.py | 1,075 | 4.25 | 4 | #URL: https://leetcode.com/explore/learn/card/binary-search/125/template-i/950/
#Description
"""
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of
the result is returned.
Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or
x ** 0.5.
Example 1:
Input: x = 4
Output: 2
Example 2:
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is
returned.
Constraints:
0 <= x <= 231 - 1
"""
def mySqrtImpl(x, start, end):
if end - start <= 1:
sq_end = end * end
if sq_end == x:
return end
else:
return start
mid = (start + end)//2
sq_mid = mid * mid
if sq_mid == x:
return mid
elif sq_mid > x:
return mySqrtImpl(x, start, mid)
else: # sq_mid < x
return mySqrtImpl(x, mid, end)
def mySqrt(x):
assert x >= 0
if x == 0:
return 0
if x == 1:
return 1
return mySqrtImpl(x, 1, x) | true |
7ff689c4e4d6f95ad27413579ee15919eee29e15 | saurabh-pandey/AlgoAndDS | /leetcode/bst/sorted_arr_to_bst.py | 1,129 | 4.25 | 4 | #URL: https://leetcode.com/explore/learn/card/introduction-to-data-structure-binary-search-tree/143/appendix-height-balanced-bst/1015/
#Description
"""
Given an integer array nums where the elements are sorted in ascending order, convert it to a
height-balanced binary search tree.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node
never differs by more than one.
Example 1:
Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:
Example 2:
Input: nums = [1,3]
Output: [3,1]
Explanation: [1,3] and [3,1] are both a height-balanced BSTs.
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is sorted in a strictly increasing order.
"""
from bst.node import Node
def createBST(nums, start, end):
if start >= end:
return None
else:
mid = (start + end)//2
node = Node(nums[mid])
node.left = createBST(nums, start, mid)
node.right = createBST(nums, mid + 1, end)
return node
def sortedArrayToBST(nums):
return createBST(nums, 0, len(nums)) | true |
c5361ad406f3da27f7960150fb6afbd44bbae03e | saurabh-pandey/AlgoAndDS | /leetcode/queue_stack/stack/target_sum.py | 2,326 | 4.1875 | 4 | #URL: https://leetcode.com/explore/learn/card/queue-stack/232/practical-application-stack/1389/
#Description
"""
You are given an integer array nums and an integer target.
You want to build an expression out of nums by adding one of the symbols '+' and '-' before each
integer in nums and then concatenate all the integers.
For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them
to build the expression "+2-1".
Return the number of different expressions that you can build, which evaluates to target.
Example 1:
Input: nums = [1,1,1,1,1], target = 3
Output: 5
Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
Example 2:
Input: nums = [1], target = 1
Output: 1
Constraints:
1 <= nums.length <= 20
0 <= nums[i] <= 1000
0 <= sum(nums[i]) <= 1000
-1000 <= target <= 1000
"""
add = lambda x, y: x + y
sub = lambda x, y: x - y
def checkTargetSumMatch(target, stackSum):
targetSum = target + stackSum
targetDiff = target - stackSum
count = 0
if targetSum == 0:
count += 1
if targetDiff == 0:
count += 1
return count
def findTargetSumRec(sz, nums, target, runningSum, stackSum, i, action):
newStackSum = action(stackSum, nums[i])
if i == sz - 1:
return checkTargetSumMatch(target, newStackSum)
sumRemainStack = runningSum[i + 1]
maxPositiveSum = newStackSum + sumRemainStack
minPositiveSum = newStackSum - sumRemainStack
minNegativeSum = -newStackSum - sumRemainStack
maxNegativeSum = -newStackSum + sumRemainStack
isTargetInPosRange = (target <= maxPositiveSum) and (target >= minPositiveSum)
isTargetInNegRange = (target <= maxNegativeSum) and (target >= minNegativeSum)
if isTargetInPosRange or isTargetInNegRange:
count = 0
count += findTargetSumRec(sz, nums, target, runningSum, newStackSum, i + 1, add)
count += findTargetSumRec(sz, nums, target, runningSum, newStackSum, i + 1, sub)
return count
else:
return 0
def findTargetSumWays(nums, target):
if len(nums) == 0:
return 0
sz = len(nums)
nums.sort(reverse=True)
runningSum = [sum(nums[i:]) for i in range(sz)]
return findTargetSumRec(sz, nums, target, runningSum, 0, 0, add)
| true |
72d27e13ba30f9d65f0e0b4e105389f80d2fcd03 | loolu/python | /CharacterString.py | 830 | 4.15625 | 4 | #使用字符串
#字符串不可改变,不可给元素赋值,也不能切片赋值
website = 'http://www.python.org'
website[-3] = 'com'
#
format = "Hello, %s. %s enough for ya?"
values = ('world', 'hot')
print(format % values)
from string import Template
tmpl = Template("Hello, $who! $what enough for ya?")
print(tmpl.substitute(who='Mars', what='Dusty'))
print("{}, {} and {}".format("first", "second", "third"))
print("{0}, {1} and {2}".format("first", "second", "third"))
print("{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to"))
from math import pi
print("{name} is approximately {value:.2f}.".format(value=pi, name="π"))
print("{name} is approximately {value}.".format(value=pi, name="π"))
from math import e
print(f"Euler's constant is roughly {e}.")
print("Euler's constant is roughly {e}.".format(e=e)) | true |
61bb1f7871db613627d1edd50128a7c5c88d0b4b | Stemist/BudCalc | /BudgetCalculatorCLI.py | 1,577 | 4.28125 | 4 | #!/usr/bin/env python3
people = []
class Person:
def __init__(self, name, income):
self._name = name
self._income = income
self.products = {}
def add_product():
try:
product = str(input("Enter product name: "))
cost = float(input("Enter product cost ($): "))
products[product] = price
except:
print("Error: Invalid entry format. Make sure cost is a number, e.g. '3.50'.")
def return_total_cost():
pass
def main():
start_menu()
# User enters people to be considered in the calculation.
while making_people == True:
try:
check = str(input("Add a person to the calculation? (y/n)"))
if check == 'y' or 'Y':
generate_person()
else:
break
except:
print("Error: Please enter 'y' or 'n'.")
# User enters items and prices.
while adding_items == True:
for person in people:
display_totals()
def start_menu():
print("### Monthly Budget Calculator. ###\n\n")
expected people =
def display_totals():
for each_person in people:
print("Name: ", each_person._name, ", Monthly income: $", each_person._income)
print("Items: ", each_person.products)
def generate_person():
try:
person_name = str(input("Enter the first person's name: "))
person_income = float(input("Enter their monthly income ($)"))
# Generate a new person with the above values.
person_instance = Person(person_name, person_income)
# Add them to the list of people.
people.append(person_instance)
except:
print("Input Error: Must input a name and a number value.")
if __name__ == '__main__':
main() | true |
36d1d6f8060a6e7dcdf58b48b12bfea2396d6023 | joshrili/rili | /cpt_05.py | 1,662 | 4.15625 | 4 | '''
Description: python code, exercises of chapter 5, python crash course
Author: joshrili
Date: 2020-03-22
'''
cars = ['audi', 'bmw', 'subaru', 'toyota']
print(cars)
for car in cars :
if car == 'bmw' :
print(car.upper())
print('I like ' + car.upper() + '\n')
else :
print(car.title())
print('I like ' + car.title() + '\n')
print('I like all these cars above!')
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')
alien_colors = ['green' , 'yellow' , 'red']
for alien_color in alien_colors :
if alien_color == 'green' :
#if alien_color == 'red':
print('Great! You have shotted a green alien, and earned 5 points.')
elif alien_color == 'yellow' :
print('Great! You have shotted a yellow alien, and earned 10 points.')
elif alien_color == 'red' :
print('Great! You have shotted a red alien, and earned 15 points.')
usernames = ['Admin' , 'chen' , 'li' , 'hu']
#usernames = []
if usernames :
for user in usernames :
if user == 'Admin' :
print('Hello Admin, see a report?')
else:
print('Hello ' + user + ', thank for logging.')
else:
print('we need some users.')
del usernames[:]
#del usernames #delete the elements and the list
print(usernames)
if usernames :
print('Not empty')
else :
print('empty')
available_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
| false |
4b67eb4c4a802e7980142f6a8ee644f1bda6d867 | huyilong/python-learning | /fibo_module.py | 720 | 4.25 | 4 | #fibonacci numbers module
#could directly input python3 on mac terminal to invoke version 3
def fib(n):
a, b = 0, 1
while b < n:
print( b),
#there is a trailing comma "," after the print to indicate not print output a new line
a, b = b, a+b
print #this is print out a empty line
#if you use print() then it will actually output a () rather than a new line
def fib2(n):
result = []
a, b =0, 1
while b<n:
result.append(b)
a, b = b, a+b
return result
if __name__=="__main__":
#here the __name__ and __main__ all have two underlines! not only one _!
import sys
fib(int(sys.argv[1]))
print("hello, this is my first module for fibonacci numbers generator")
print("Usage: fibo_module.fib(1000)") | true |
6d70e720d4424c0b948c20561fdec80afae21701 | gregxrenner/Data-Analysis | /Coding Challenges/newNumeralSystem.py | 1,752 | 4.46875 | 4 | # Your Informatics teacher at school likes coming up with new ways to help
# you understand the material. When you started studying numeral systems,
# he introduced his own numeral system, which he's convinced will help clarify
# things. His numeral system has base 26, and its digits are represented by
# English capital letters - A for 0, B for 1, and so on.
# The teacher assigned you the following numeral system exercise:
# given a one-digit number, you should find all unordered pairs of one-digit
# numbers whose values add up to the number.
# Example
# For number = 'G', the output should be
# newNumeralSystem(number) = ["A + G", "B + F", "C + E", "D + D"].
# Translating this into the decimal numeral system we get:
# number = 6, so it is ["0 + 6", "1 + 5", "2 + 4", "3 + 3"].
# Assume input is "A" <= number <= "Z".
def newNumeralSystem(number):
# Initialize and empty solution list
solution = []
# Define the number system.
system = {'A':0, 'B':1, 'C':2, 'D':3, 'E':4, 'F':5, 'G':6, 'H':7, 'I':8, 'J':9, 'K':10, 'L':11, 'M':12,
'N':13, 'O':14, 'P':15, 'Q':16, 'R':17, 'S':18, 'T':19, 'U':20, 'V':21, 'W':22, 'X':23, 'Y':24, 'Z':25}
# Invert the dict for reverse lookups.
system_inv = dict((v, k) for k, v in system.items())
print('System[number]=', system[number])
# Find unordered pairs of one-digit numbers that add up to 'number'.
for i in range(0, system[number]):
for j in range(i, system[number]+1):
if (i + j) == system[number]:
success = str(system_inv[i] + ' + ' + system_inv[j])
solution.append(success)
# Handle case where number = 'A'
if number == 'A': return ['A' + ' + ' + 'A']
return solution
newNumeralSystem('A')
| true |
2f74be1a461073ee407ec627e355281950a480a0 | miguel-osuna/PS-Algos-and-DS-using-Python | /Section6_Sorting_Searching/sorting/bubble_sort.py | 2,245 | 4.21875 | 4 | # Bubble Sort Algorithm
def bubble_sort(num_list):
""" Bubble Sort Algorithm """
for passnum in range(len(num_list) - 1, 0, -1):
for i in range(passnum):
# Exchanges items
if num_list[i] > num_list[i + 1]:
temp = num_list[i]
num_list[i] = num_list[i + 1]
num_list[i + 1] = temp
def short_bubble_sort(num_list):
""" Bubble Sort Algorithm with Interruption """
exchange = True
passnum = len(num_list) - 1
while passnum > 0 and exchange:
exchange = False
for i in range(passnum):
# Exchanges items
if num_list[i] > num_list[i + 1]:
temp = num_list[i]
num_list[i] = num_list[i + 1]
num_list[i + 1] = temp
exchange = True
passnum -= 1
def cocktail_sort(num_list):
""" Cocktail Sort Algorithm Implementation (Bubble Sort Variation) """
# Setting variables
start_index = 0
end_index = len(num_list) - 1
swapped = True
while swapped:
# Pass moves up
swapped = False
for i in range(start_index, end_index, 1):
# Exchanges items
if num_list[i] > num_list[i + 1]:
temp = num_list[i]
num_list[i] = num_list[i + 1]
num_list[i + 1] = temp
swapped = True
end_index -= 1
# Pass moves down
swapped = False
for i in range(end_index, start_index, -1):
# Exchanges items
if num_list[i] < num_list[i - 1]:
temp = num_list[i]
num_list[i] = num_list[i - 1]
num_list[i - 1] = temp
swapped = True
start_index += 1
def main():
num_list = [345, 23, 54, 64, 98, 22, 45, 18, 78]
bubble_sort(num_list)
print(num_list)
num_list2 = [345, 23, 54, 64, 98, 22, 45, 18, 78]
short_bubble_sort(num_list2)
print(num_list2)
numlist3 = [345, 23, 54, 64, 98, 22, 45, 18, 78]
print(numlist3)
cocktail_sort(numlist3)
print(numlist3)
charlist = list("PYTHON")
short_bubble_sort(charlist)
print(charlist)
if __name__ == "__main__":
main()
| false |
23de8de49110b4db71833b1b54041bd41fae2b43 | jmobriencs/Intro-to-Python | /O'Brien_Lab1/Lab1-6.py | 436 | 4.3125 | 4 | #John-Michael O'Brien
#w1890922
#CISP 300
#1/31/20
#This program calculates miles walked and calories lost for a specific day of the week.
dayWalked = input('Enter the day of the week you walked: ')
stepsTaken = int(input('Enter the number of steps taken that day: '))
milesWalked = (stepsTaken/2000)
caloriesLost = (stepsTaken/2000)*65
print ('You walked', milesWalked, 'miles on', dayWalked, 'and lost', caloriesLost, 'calories.')
| true |
2c2cd04d5893ebb5e05d463729a999f80e55266c | jmobriencs/Intro-to-Python | /O'Brien_Lab1/Lab1-4.py | 580 | 4.1875 | 4 | #John-Michael O'Brien
#w1890922
#CISP 300
#1/31/20
#This program calculates how many credits are left until graduation.
studentName = input('Enter student name. ')
degreeName = input('Enter degree program name. ')
creditsDegree = int(input('Enter the number of credits needed for the degree. '))
creditsTaken = int(input('Enter the number of credits taken so far. '))
creditsLeft = creditsDegree - creditsTaken
print ('The student\'s name is', studentName)
print ('The degree program name is', degreeName)
print ('There are', creditsLeft, 'credits left until graduation. ')
| true |
3434b25d66c2edefe39cc30ecc20b8a886d45639 | kundaMwiza/dsAlgorithms | /source/palindrome.py | 869 | 4.1875 | 4 | def for_palindrome(string):
"""
input: string
output: True if palindrome, False o/w
implemented with a for loop
"""
for i, ch in enumerate(string):
if ch != string[-i-1]:
return False
return True
def rec_palindrome(string):
"""
input: string
output: True if palidrome, False o/w
implemented with recursion
"""
string = string.lower()
n = len(string)
start = 0
stop = n-1
def is_palindrome(string, stop, start):
if stop == start:
return True
elif (stop - start) == 1 or (stop - start) == 2:
return string[start] == string[stop]
else:
x = string[start] == string[stop]
return x and is_palindrome(string, stop-1, start+1)
return is_palindrome(string, stop, start)
print(rec_palindrome('ara'))
| true |
5c30a3093ad4fca9ef738d7901f659eff9698700 | ase1590/python-spaghetti | /divide.py | 254 | 4.1875 | 4 | import time
print('divide two numbers')
# get the user to enter in some integers
x=int(input('enter first number: '))
y=int(input('enter number to divide by: '))
print('the answer is: ',int(x/y)),
time.sleep(3) #delay of a few seconds before closing
| true |
5cfd561fc32a028223208019bde4c60736e786a5 | ndvssankar/ClassOf2021 | /Operating Systems/WebServer/test_pipe.py | 1,316 | 4.3125 | 4 | # Python program to explain os.pipe() method
# importing os module
import os
import sys
# Create a pipe
pr, cw = os.pipe()
cr, pw = os.pipe()
stdin = sys.stdin.fileno() # usually 0
stdout = sys.stdout.fileno() # usually 1
# The returned file descriptor r and w
# can be used for reading and
# writing respectively.
# We will create a child process
# and using these file descriptor
# the parent process will write
# some text and child process will
# read the text written by the parent process
# Create a child process
pid = os.fork()
# pid greater than 0 represents
# the parent process
if pid > 0:
# This is the parent process
# Closes file descriptor r
# os.close(pr)
os.close(cw)
os.close(cr)
# print("Parent process is writing")
os.dup2(pw, stdout)
text = "n=10"
print(text)
os.close(pw)
os.dup2(pr, stdin)
st = input()
print(st)
# print("Written text:", text.decode())
else:
# This is the parent process
# Closes file descriptor w
# os.close(pw)
# os.close(pr)
# Read the text written by parent process
# print("\nChild Process is reading")
# print(open("scripts/odd.py").read())
os.dup2(cr, stdin)
os.dup2(cw, stdout)
exec(open("scripts/odd.py").read())
| true |
6e2a320b1cf178caf81248050e0184467c000675 | Minaksh1012/If_else_python | /questions.py/loop/if else.py/maximum number.py | 287 | 4.15625 | 4 | num1=int(input("enter the number"))
num2=int(input("enter the number"))
num3=int(input("enter the numbers"))
if num1>num2>num3:
print("num1 is gratest number",num1)
elif num2>num1>num3:
print("num2 is greatest number",num2)
else:
print("num3 is greatest number",num3) | false |
bfafa045df5c449cac9b43b3ab66c0bda07ba5a2 | Minaksh1012/If_else_python | /alphabet digit special character.py | 234 | 4.25 | 4 | ch=input("enter the character")
if (ch>='a'and ch<='z') or (ch>='A'and ch<='Z'):
print("these character is alphabet")
elif ch>='0'and ch<='9':
print("these character is digit")
else:
print("these is special character") | false |
564be3d797b4993009205db721f2fb1c1513c820 | koussay-dellai/holbertonschool-higher_level_programming | /0x06-python-classes/3-square.py | 415 | 4.125 | 4 | #!/usr/bin/python3
class Square:
'''defining a sqaure'''
def __init__(self, size=0):
'''initialize an instance'''
self.__size = size
if type(size) is not int:
raise TypeError("size must be an integer")
elif (size < 0):
raise ValueError("size must be >= 0")
def area(self):
'''defining a public method'''
return (self.__size ** 2)
| true |
99f7f46430267a6ee17e0288b14511e3cbef57fc | koussay-dellai/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 350 | 4.1875 | 4 | #!/usr/bin/python3
"""
module to print lines of a file
"""
def read_lines(filename="", nb_lines=0):
"""
function to print n lines of a file
"""
number = 0
with open(filename, encoding="UTF8") as f:
for i in f:
number += 1
print(i, end="")
if nb_lines == number:
break
| true |
fce2be88790287f25b5d6cf863720bbf172f772c | katealex97/python-programming | /UNIT2/homework/hw-1.py/hw-3.py | 394 | 4.21875 | 4 | odd_strings = ['abba', '111', 'canal', 'level', 'abc', 'racecar',
'123451' , '0.0', 'papa', '-pq-']
count = 0
for string in odd_strings:
#find strings greater than 3 and have same
#first and last character
first = string[0]
last = string[len(string) - 1] #python allows neg. indexes last = string[-1]
if len(string) > 3 and first = last:
count += 1
print(count)
| true |
cde77dfa50a8a370bf1c589bc8d262488dc81e29 | thecipherrr/Assignments | /New Project/Number1.py | 488 | 4.25 | 4 | # Main Function
def convert_to_days():
hours = float(input("Enter number of hours:"))
minutes = float(input("Enter number of minutes:"))
seconds = float(input("Enter number of seconds:"))
print("The number of days is:", get_days(hours, minutes, seconds))
# Helper Function
def get_days(hours, minutes, seconds):
days = (hours / 24) + (minutes / (24 * 60)) + (seconds / (24 * 3600))
days_final = round(days, 4)
return days_final
convert_to_days() | true |
1414aef6db7b039b2f065d68376d903c79e7ba3f | seangrogan-archive/datastructures_class | /TP2/BoxClass.py | 1,691 | 4.28125 | 4 | class BoxClass:
"""class for easy box handling"""
def __init__(self, name, width, height):
"""init method"""
self._name = name
self._width = width
self._height = height
self._rotate = False
def __lt__(self, other):
"""for sorting"""
return self._name < other.name()
def __gt__(self, other):
"""for sorting"""
return self._name > other.name()
def __eq__(self, other):
"""for sorting"""
return self._name == other.name()
def __str__(self):
"""pretty printing"""
pp = '(' + self._name + ',' + str(self._width) + ',' + str(self._height) + ')'
return pp
def rotate_box(self):
"""class to rotate the box"""
self._rotate = not self._rotate
def reset_rotate(self):
"""rotates the box to original"""
self._rotate = False
def is_rotated(self):
"""class to tell if a box is rotated"""
return self._rotate
def name(self):
"""return thy name"""
return self._name
def height(self):
"""returns the height"""
if self._rotate:
return self._width
else:
return self._height
def width(self):
"""returns the width"""
if self._rotate:
return self._height
else:
return self._width
# unit testing
if __name__ == '__main__':
print('unit testing')
box = BoxClass('A', 5, 3)
print(box.height())
print(box.is_rotated())
box.rotate_box()
print(box.height())
print(box.is_rotated())
print(box) | true |
31c4f9cfd348ce0f411785c3f38933964b76701e | seangrogan-archive/datastructures_class | /Demo 3/Sorts.py | 2,040 | 4.25 | 4 | def main():
liste = ['B','C','D','A','E','H','G','F']
print(liste)
insert = InsertSort(liste)
print(insert)
merge = MergeSort(liste)
print(merge)
quick = inplace(liste, 0, len(liste) - 1)
print(quick)
def InsertSort(element):
for i in range(len(element)):
j = i
while((j > 0) & (element[j-1] > element[j])):
element[j], element[j-1] = element[j-1], element[j]
j = j - 1
return element
def MergeSort(element):
if len(element) <= 1:
return element
left = []
right = []
mid = len(element)//2
for x in range(mid):
left.append(element[x])
for x in range(mid,len(element)):
right.append(element[x])
left = MergeSort(left)
right = MergeSort(right)
retlist = []
for i in range(len(left)):
retlist.append(left[i])
for i in range(len(right)):
retlist.append(right[i])
return retlist
def inplace(S, a , b ):
'''Sort the list from S[a] to S[b] inclusive using the quick-sort algorithm.'''
if a >= b: return # range is trivially sorted
pivot = S[b] # last element of range is pivot
left = a #will scan rightward
right = b - 1 #will scan rightward
while left <= right:
# scan until reaching value equal or larger than pivot (or right marker)
while left <= right and S[left] < pivot:
left += 1
# scan until reaching value equal or smaller than pivot (or left marker)
while left <= right and pivot < S[right]:
right -= 1
if left <= right: # scans did not strictly cross
S[left], S[right] = S[right], S[left] # swap values
left, right = left + 1, right - 1# shrink range
# put pivot into its final place (currently marked by left index)
S[left], S[b] = S[b], S[left]
# make recursive calls
inplace(S, a, left - 1)
inplace(S, left + 1, b)
main()
| false |
a761dad436a049421f7e6fa8b0bf3c478df6b8aa | pavanjavvadi/leet_code_examples | /anagram.py | 1,681 | 4.3125 | 4 | """
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
"""
from collections import defaultdict
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
# create a default dictionary using collections module
# defaultdict keys must be immutable and unique
res = defaultdict(list)
# looping the list elements using for loop
for s in strs:
# sort the value of the each element using sorted() function
sorted_values = sorted(s)
# this assigns values to the key where keys are unique
# here the keys are sorted ones but the values are original elements
res[''.join(sorted_values)].append(s)
# print the defaultdict values() elements for printing the group anagrams
print(res.values())
solution = Solution()
strs = ["eat","tea","tan","ate","nat","bat"]
solution.groupAnagrams(strs)
"""
detailed explaination:
_2d_list_value = [] , eg: [[a, b], [c, d]]
for s i strs:
values = [''.join(sorted(s)), s]
_2d_list_value.append(values)
result = defaultdict(list)
for k, v in _2d_list_value:
result[k].append(v)
print(result.values())
""" | true |
6a82cb3ca8845b3b2c9837d3d16d91025cffabf1 | pavanjavvadi/leet_code_examples | /sorting/inserion_sort.py | 369 | 4.125 | 4 | def insertion_sort(array):
for i in range(len(array)):
key = array[i]
j = i - 1
while j>=0 and key < array[j]:
array[j + 1] = array[j]
j = j - 1
array[j + 1] = key
return array
array = [21, 4, 19, 16, 54, 86, 70]
array = insertion_sort(array)
for i in range(len(array)):
print(array[i], end=", ") | false |
66d180a6bfbc522549ac68db6d3b04d940455159 | Rinatik79/PythonAlgoritms | /Lesson 1/lesson1-7.py | 609 | 4.21875 | 4 | sides = input("Enter length of every side of triangle, separated by ';' : ")
sides = sides.split(";")
sides[0] = float(sides[0])
current = sides[0]
sides[1] = float(sides[1])
if sides[1] > sides[0]:
sides[0] = sides[1]
sides[1] = current
current = sides[0]
sides[2] = float(sides[2])
if sides[2] > sides[0]:
sides[0] = sides[2]
sides[2] = current;
if sides[0] > sides[1] + sides[2]:
print("Triangle with given sides doesn't exist.")
elif sides[1] == sides[2]:
print("This is isosceles triangle.")
if sides[0] == sides[1] == sides[2]:
print("This is equilateral triangle.")
| true |
4977a7a7e99f1f571ade665a927e97a059287ae4 | AtharvBagade/Python | /Question7.py | 304 | 4.28125 | 4 | string=input("Enter the string")
def Most_Duplicate_Character(str1):
count = 0
for i in str1:
count2 = str1.count(i)
if(count2 > count):
count = count2
num = i
print(num,"Count:",count)
Most_Duplicate_Character(string)
| true |
3ab954e552bb38cea30ad5bf3bea69592c6988f6 | LyunJ/pythonStudy | /08_list/sort.py | 473 | 4.28125 | 4 | # sort() reverse() sorted()
# #리스트를 정렬
# a = [3,6,0,-4,1]
# a.sort()
# print(a)
# a.reverse()
# print(a)
# # 정렬 후 새로운 리스트를 반환
# new_a = sorted(a,reverse=True)
# print(new_a)
# string = ['Apple','Banana','melon','apple']
# string.sort()
# print(string)
# # 대소문자 구분 없이 정렬
# string.sort(key=str.upper)
# print(string)
# index(n) 메소드 : n의 위치 반환 없으면 에러
a = [3,6,0,-4,1]
b = a.index(6)
print(b) | false |
6b7843bef67b2a2c9f1782b7200c3ff40b9edab6 | LyunJ/pythonStudy | /1_OT/hello.py | 1,990 | 4.125 | 4 | # 첫번째 프로그램
# print('Lee YunJae')
'''
# 변수에 값을 저장
x = 10
y = 20
z = 30
print(x,y,z)
# 여러개의 변수에 여러개의 값을 저장
x, y, z = 10, 20, 30
print(x,y,z)
# 여러개의 변수에 동일한 값을 할당
a = b = c = 100
print(a,b,c)
# 두 변수의 값을 교환
a, b = 10, 20
print('a=',a)
print('b=',b)
a,b = b,a
print('a=',a)
print('b=',b)
# 변수를 삭제
x = 100
print(x)
print(id(x))
print(type(x))
del x
# 문자열에 큰 따옴표 사용
name = "이윤재"
age = 24
print(name,age)
address = "서울시"
print(name+'는 '+address+'에 삽니다')
# str() : 숫자형을 문자열로 변환
print(name+'는 '+str(age)+'살입니다')
print(name+'은 ',age,'살입니다')
# 사각형의 면적을 구하는 프로그램
width = 100
height = 50
area = width * height
print(area)
name = "홍길동"
no = "2016001"
year = 4
grade = 'A'
average = 93.5
# print('성명 : ' + name)
# print('학번 : ' + no)
# print('학년 :',year)
# print('학점 : ' + grade)
# print('평균 :',average)
# print('성명 : %s' % name)
# print('학번 : %s' % no)
# print('학년 : %d' % year)
# print('학점 : %c' % grade)
# print('평균 : %0.2f' % average)
#
# print('성명 : %s, 학번 : %s' %(name,no))
#
# rate = 80
# print('이름 : %s, 출석률: %d%%' %(name,rate))
print(format(average,'10.2f'))
INT_Rate = 0.03
deposit = 10000
interest = deposit * INT_Rate
balance = deposit + interest
print(balance)
print(int(balance))
print(format(int(balance),','))
a = 0b1010
b = 300
c = 0o123
d = 0x12fc
print(a,b,c,d)
f1 = 3.14
str = """여러줄로
나누어
출력가능"""
print(str)
# 특수 리터럴
# None
address = None
print(address)
a = 1+2+3+\
4+5+6
print(a)
print("c:\python\name")
print(r"c:\python\name")
'''
print("first")
print("second")
print("first",end="@")
print("second")
print("%f" % (10/4))
print("%d / %d = %5.1f" % (10, 4, 10 / 4))
print("%d / %d = %5.0f" % (10, 4, 10 / 4))
print("%1.1f" % 123.45) | false |
cf05f6410b6878b34067ecb3b89b38bef59f59b5 | Design-Computing/me | /set3/exercise2.py | 1,216 | 4.5 | 4 | """Set 3, Exercise 2.
An example of how a guessing game might be written.
Play it through a few times, but also stress test it. What if your lower bound
is 🍟, or your guess is "pencil", or "seven"
This will give you some intuition about how to make exercise 3 more robust.
"""
import random
def exampleGuessingGame():
"""Play a game with the user.
This is an example guessing game. It'll test as an example too.
"""
print("\nWelcome to the guessing game!")
print("A number between 0 and _ ?")
upperBound = input("Enter an upper bound: ")
print(f"OK then, a number between 0 and {upperBound} ?")
upperBound = int(upperBound)
actualNumber = random.randint(0, upperBound)
guessed = False
while not guessed:
guessedNumber = int(input("Guess a number: "))
print(f"You guessed {guessedNumber},")
if guessedNumber == actualNumber:
print(f"You got it!! It was {actualNumber}")
guessed = True
elif guessedNumber < actualNumber:
print("Too small, try again :'(")
else:
print("Too big, try again :'(")
return "You got it!"
if __name__ == "__main__":
exampleGuessingGame()
| true |
03f695385e9a5b6dd258029d10e11b9bb6ffa371 | ahmedzaabal/Beginner-Python | /Dictionary.py | 606 | 4.28125 | 4 | # Dictionary = a changeable, unorderd collecion of unique key:value pairs
# fast because they use hashing, allow us to access a value quickly
capitals = {'USA': 'Washington DC',
'India': 'New Delhi',
'China': 'Beijing',
'Russia': 'Moscow'}
capitals.update({'Germany': 'Berlin'})
capitals.update({'USA': 'Las Vegas'})
capitals.pop('China')
capitals.clear()
# print(capitals['Germany'])
# print(capitals.get('Germany'))
# print(capitals.keys())
# print(capitals.values())
# print(capitals.items())
for key, value in capitals.items():
print(key, value)
| true |
c5d91ba52a45b61a4442201fc22f7a20aa575c63 | malay1803/Python-For-Everybody-freecododecamp- | /files/findLine.py | 1,218 | 4.375 | 4 | # Exercise 2: Write a program to prompt for a file name, and then read through the file and look for lines of the form:
#X-DSPAM-Confidence: 0.8475
# When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart the line to extract the floating-point number on the line. Count these lines and then compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence.
fName = input("Enter your file name : ")
try:
fHand = open(fName)
except:
print("Invalid file name")
quit()
sum = 0
count=0
for line in fHand :
if line.startswith("X-DSPAM-Confidence:") :
rmNewLine = line.strip() #to remove /n from the end of each line
pos = rmNewLine.find(":") #to find the position of : in a line
num = float(rmNewLine[pos+1:]) #to select convert the string into number
sum = sum + num #to find sum of the numbers
count = count +1 #to count the number of lines
print(f'Average spam confidence: {sum/count}') #to print the output | true |
53c6e9853a06f737c8c43009c4ed2c154e11e107 | vmysechko/QAlight | /metiz/files_and_exceptions/file_writer.py | 720 | 4.21875 | 4 | filename = "programming.txt"
with open(filename, 'w') as file_object:
file_object.write("I love programming.\n")
# 'w' argument tells Python that we want to open a file in write mode.
# In the write mode Python will erase the content of the file.
# 'r' - read mode
# 'a' - append mode
# 'r+' - read/write mode
with open(filename, 'a') as file_object:
file_object.write("That should be the only stroke in the file.\n")
file_object.write("I also love finding meaning in large data-sets. \n")
file_object.write("I also love creating apps that can run in a browser. \n")
guest_name = input("Write your name, please: ")
with open(filename, 'a') as file_object:
file_object.write(guest_name + "\n")
| true |
7f26b982dd0543a277216ca671b882f9d1c1f3a1 | calder3/BCA_Project- | /hang_man2.py | 1,186 | 4.15625 | 4 | '''
This will play the game hangman. Need to have the random word modual installed.
'''
from random_word import RandomWords
r = RandomWords()
word = r.get_random_word(hasDictionaryDef = 'true')
word = word.lower()
space = list(word)
dash = []
dash.extend(word)
#print(word)
for i in range(len(dash)):
dash[i] = "_"
print(' '.join(dash))
print()
turns = 10
already_guessed = []
while turns > 0:
guess = input('If you think you know the word enter word. Other wise guess a letter: ')
guess = guess.lower()
if guess in space:
for i in range(len(space)):
if space[i] == guess:
dash[i] = guess
print('You got a letter right!')
elif guess == "word":
word_guess = input("\n What is the word? ")
word_guess = word_guess.lower()
if word_guess == word:
print(f'You win! \n The word was {word}')
break
else:
print("Wrong! \n")
already_guessed.append(guess)
print('You have wrongly guessed', already_guessed,'\n')
turns = turns - 1
print(f'You have {turns} fails before you lose.')
print(" ".join(dash))
print()
if turns == 0:
print('You lose!')
print(f'The word was {word}')
| true |
028e73aab6a25145064048c00eb5d9f35d8037c1 | PriyaRcodes/Threading-Arduino-Tasks | /multi-threading-locks.py | 995 | 4.375 | 4 | '''
Multi Threading using Locks
This involves 3 threads excluding the main thread.
'''
import threading
import time
lock = threading.Lock()
def Fact(n):
lock.acquire()
print('Thread 1 started ')
f = 1
for i in range(n,0,-1):
f = f*i
print('Factorial of',n,'=',f)
lock.release()
def Square(n):
lock.acquire()
print('Thread 2 started ')
sq = n*n
print('Square of',n,'=',sq)
lock.release()
def Task():
print('Thread 3 started ')
time.sleep(1) #represents any task that takes 1 sec
print('Task done')
print('This is the main thread')
n = int(input('Enter a number: '))
start_time = time.time()
T1 = threading.Thread(target=Fact,args=(n,))
T2 = threading.Thread(target=Square,args=(n,))
T3 = threading.Thread(target=Task)
T1.start()
T2.start()
T3.start()
T1.join()
T2.join()
T3.join()
print('All threads have been closed')
print('Processing time taken: ',time.time()-start_time,'seconds')
| true |
c30ede39f24692490d2d3530dfbba510118fdd7b | kevenescovedo/PYTHON-work_arquivos | /exercicio3.py | 2,320 | 4.53125 | 5 |
""""
Elabore uma estrutura para representar e armazenar 10 alunos
(matricula, nome, telfone). Utilize os recursos de arquivo para armazenar estes dados
permanentemente. O nome do arquivo deve ser o mesmo da estrutura. Construa um menu com as seguintes opções,
cada uma delas deve ter uma função e a main para chamar todas elas.
Menu de opções:
Cadastrar produtos
Visualizar todos os dados
Sair
"""
import emoji
class Alunos:
matricula = 0
nome = ''
telfone = ''
def cadastrar():
arquivo = open('Alunos.txt', 'w')
aluno = Alunos()
for x in range(10):
aluno.matricula = int(input("Digite a matricula, do {}º aluno -> ".format(x + 1)))
aluno.nome = (input("Digite o nome do {}º aluno -> ".format(x + 1))
aluno.telefone = input("Digite o número de telefone do aluno do {}º aluno -> ".format(x + 1))
print()
arquivo.write('{} {} {:.2f}\n'.format( aluno.matricula, aluno.nome, aluno.telefone))
arquivo.close()
print("\033[0;32mCadastro realizado com sucesso.\033[m")
input('\33[41mDigite qualquer tecla para voltar ao menu...\33[m')
return main()
def listar():
arquivo = open('Alunos.txt', 'r')
for z in arquivo.readlines():
print("-" * 120)
aluno = Alunos()
aluno.matricula, aluno.nome, aluno.telefone = z.strip().split(" ")
print("Matricula: {}\t\tNome do Aluno: {}\t\t Telefone do Aluno: {}".format( aluno.matricula, aluno.nome, aluno.matricula))
arquivo.close()
input('\33[7m\nDigite qualquer tecla para voltar ao menu...\33[m')
return main()
def sair():
print(emoji.emojize("\n\033[0;32mObrigado por usar nosso sistema! :sunglasses: \033[m", use_aliases=True))
def main():
print("-" * 100)
print("\t\t\t\t\t\033[95mMenu\033[00m")
print("-" * 100)
print("1 - Cadastrar Alunos")
print("2 - Consultar Alunos")
print("3 - Sair")
escolha = int(input("\033[41mDigite uma das opções acima para continuar -> \033[m"))
print()
if escolha != 1 and escolha !=2 and escolha != 3:
print('\033[41mDigite 1, 2 ou 3. Sem espaços ou pontos.\033[m\n')
input('\33[41mDigite qualquer tecla para voltar ao menu...\033[m')
return main()
elif escolha == 1:
cadastrar()
elif escolha == 2:
listar()
elif escolha == 3:
sair()
main()
| false |
5a6c3768825ef7ec1e97cae8e6f533457fcfba5c | eriDam/CursoPython | /Fase 4 - Temas avanzados/Tema 14 - Bases de datos con SQLite/Ejercicios/restaurante_ej_2_interfaz.py | 1,885 | 4.46875 | 4 | """
2) En este ejercicios debes crear una interfaz gráfica con tkinter (menu.py) que muestre de forma elegante el menú del restaurante.
Tú eliges el nombre del restaurante y el precio del menú, así como las tipografías, colores, adornos y tamaño de la ventana.
El único requisito es que el programa se conectará a la base de datos para buscar la lista categorías y platos.
Algunas ideas: https://www.google.es/search?tbm=isch&q=dise%C3%B1o+menu+restaurantes
"""
import sqlite3
from tkinter import *
# Configuracion de la raíz
root = Tk()
root.title("Food Lover - Menú")
root.resizable(0,0)
root.config(bd=25, relief="sunken")
# Título
Label(root, text=" Food Lover ", fg="blue", font=("Verdana", 28, "bold italic")).pack()
# Subtítulo
Label(root, text="Menú del día", fg="lightblue", font=("Verdana", 24, "bold italic")).pack()
# Separación de categorías
Label(root, text="").pack()
#conectar a la base de datos
conexion = sqlite3.connect("restaurante.db")
cursor = conexion.cursor()
# Buscar las categorias y platos de la base de datos
# Muestra al usuario las categorias disponibles
categorias = cursor.execute("SELECT * FROM categoria").fetchall()# hacemos directamente aquí el fetchall para devolver una lista
#recorremos las categorias
for categoria in categorias:
Label(root, text=categoria[1], fg="black", font=("Verdana", 20, "bold italic")).pack()
# Separación de categorías
Label(root, text="").pack()
platos = cursor.execute("SELECT * FROM plato WHERE categoria_id={}".format(categoria[0])).fetchall()
for plato in platos:# anidamos dentro otro for para consultar los platos
Label(root, text=plato[1], fg="grey", font=("Tahoma", 15, "italic")).pack()
conexion.close()
#Precio del menú
Label(root, text="12 € (IVA incl.)", fg="blue", font=("Verdana", 15, "italic")).pack(side="right")
#ejecutamos el bucle
root.mainloop() | false |
8cd40a51022bf66e2c94809f094e182b89710008 | nigeltart/Pythagorean-Triples | /Pythagorean_triples.py | 754 | 4.40625 | 4 | # A program to find Pythagorean triples
a_triple=[]
hypotenuse=5
triples=[]
triples.append(a_triple)
#print (triples)
while hypotenuse <100:
base = 1
height = hypotenuse-1
#print ("before loop: ", base, height, hypotenuse)
while height>base:
#print ("before if: , base, height, hypotenuse")
if base**2 + height**2 == hypotenuse**2:
a_triple = [base, height, hypotenuse]
height -=1
base +=1
print ("Found One: ", a_triple)
triples.append(a_triple)
elif base**2 + height**2 > hypotenuse**2:
height -=1
else:
base +=1
#base**2 + height**2 < hypotenuse**2
hypotenuse +=1
print ("There are", len(triples), "triples with hypotenuses up to", hypotenuse, ":")
print (triples)
| false |
a9cf859429a310242c31b3edcac61225feac869d | dzieber/python-crash-course | /ch3/every.py | 535 | 4.21875 | 4 | '''
exercise 3.8
'''
things = ['one', 'fish', 'two', 'fish']
print(things)
print(things[0])
print(things[-1])
things[0] = 'moose'
print(things)
things.append('squid')
print(things)
things.insert(2,'fish')
print(things)
print(things.pop(2))
print(things)
del things[1]
print(things)
bad = 'fish'
things.remove(bad)
print(things)
print(sorted(things))
print(sorted(things,reverse=True))
things.reverse()
print(things)
things.reverse()
print(things)
things.sort()
print(things)
things.sort(reverse=True)
print(things)
print(len(things))
| false |
6fe40fec45477da49060eb84fc699ce68e6075c7 | ant0nm/reinforcement_exercise_d23 | /exercise.py | 818 | 4.375 | 4 | def select_cards(possible_cards, hand):
for current_card in possible_cards:
print("Do you want to pick up {}?".format(current_card))
answer = input()
if answer.lower() == 'y':
if len(hand) >= 3:
print("Sorry, you can only pick up 3 cards.")
else:
hand.append(current_card)
return hand
available_cards = ['queen of spades', '2 of clubs', '3 of diamonds', 'jack of spades', 'queen of hearts']
new_hand = select_cards(available_cards, [])
while len(new_hand) < 3:
print("You have only picked up {} cards.\nYou are required to have 3 cards.\nPlease choose again.".format(len(new_hand)))
new_hand = select_cards(available_cards, [])
display_hand = "\n".join(new_hand)
print("Your new hand is: \n{}".format(display_hand))
| true |
28789e85fe5a651088aed96262a4ba1c9bb97bed | ntuong196/AI-for-Puzzle-Solving | /Week7-Formula-puzzle/formula_puzzle.py | 1,095 | 4.34375 | 4 | #
# Instructions:
#
# Complete the fill_in(formula) function
#
# Hints:
# itertools.permutations
# and str.maketrans are handy functions
# Using the 're' module leads to more concise code.
import re
import itertools
def solve(formula):
"""Given a formula like 'ODD + ODD == EVEN', fill in digits to solve it.
Input formula is a string; output is a digit-filled-in string or None."""
for f in fill_in(formula):
if valid(f):
return f
def fill_in(formula):
''' Return a generator that enumerate all possible fillings-in
of letters in formula with digits.'''
# INSERT YOUR CODE HERE
def valid(f):
"""Formula f is valid if and only if it has no
numbers with leading zero, and evals true."""
try:
return not re.search(r'\b0[0-9]', f) and eval(f) is True
except ArithmeticError:
return False
print(solve('ODD + ODD == EVEN'))
print(solve('A**2 + BC**2 == BD**2'))
# Should output
# >>>
## 655 + 655 == 1310
## 2**1 + 34**1 == 36**1
#print (re.split('([A-Z]+)', 'A**2 + BC**2 == BD**2'))
| true |
80cb9850a1ebed8a1569f0c6f46b9b23e54363bd | khalidprogrammer/python_tuts | /fault_calculator.py | 1,422 | 4.34375 | 4 | print("============================ Welcome To Faulty Calculator=========================")
print("================Please enter this operator +,*,/,_,%** =================================")
def calculator():
operator = input("Enter operator\n")
number1 = int(input("Enter num1 \n"))
number2 = int(input("Enter num2 \n"))
if operator == '+':
if number1 == 56 and number2 == 9:
print("77")
else:
print("sum is", number1 + number2)
elif operator == '*':
if number1 == 45 and number2 == 3:
print("556")
else:
print("multiplication", number1 * number2)
elif operator == '/':
if number1 == 56 and number2 == 6:
print("4")
else:
print("dividision:", float(number1) / float(number2))
elif operator == '-':
print("substraction :", number1 - number2)
elif operator == "%":
print("Module is :", number1 % number2)
elif operator == "**":
print("power is", number1 ** number2)
else:
print("Unexpect error ! please enter valid number and operator")
again()
def again():
cal_again = input(''' Do you want continoue the calculation please type Y and want To exit type N \n ''')
if (cal_again == 'Y'):
calculator()
elif (cal_again == 'N'):
print("calculator is exit")
else:
again()
calculator()
| false |
aa5bfc0a89a37962ee6178bf33ef5b21aa7a53da | MaxBranvall/practicepython.org-Exercises | /ex2.py | 482 | 4.28125 | 4 | # Ask user for number
# print appropriate message if it's odd or even
num = int(input("Please enter a number: "))
if num % 2 == 0 and num % 4 == 0:
print("Even and divisble by 4!")
elif num % 2 == 0:
print("Just even!")
elif num % 4 == 0:
print("Just divisible by 4")
else:
print("Odd!")
num = int(input("Enter a number to check: "))
check = int(input("Enter a number to check with: "))
if num % check == 0:
print("Divisble!")
else:
print("Not divisble") | false |
1c44fed92ef5e6e7c986f79a0f2473de31325184 | hansweni/UBC_PHYS_Python-crash-course | /2. Arduino for Data Collection/RGB_LED.py | 1,311 | 4.28125 | 4 | '''
Program to demonstrate how to flash the three colors of a RGB diode
sequentially using the Arduino-Python serial library.
'''
# import libraries
from Arduino import Arduino
import time
board = Arduino() # find and connect microcontroller
print('Connected') # confirms the microcontroller has been found
# give pins names, so they are easy to reference
RED = 3
GREEN = 5
BLUE = 6
# configure the pins as outputs
board.pinMode(RED, "OUTPUT")
board.pinMode(GREEN, "OUTPUT")
board.pinMode(BLUE, "OUTPUT")
# turn all LEDs off
board.analogWrite(RED, 0)
board.analogWrite(GREEN, 0)
board.analogWrite(BLUE, 0)
try:
while True:
board.analogWrite(RED, 255) # set RED to full brightness
time.sleep(1) # wait 1 second
board.analogWrite(RED, 0) # turn RED off
board.analogWrite(GREEN, 255) # set GREEN to full brightness
time.sleep(1) # wait 1 second
board.analogWrite(GREEN, 0) # turn RED off
board.analogWrite(BLUE, 255) # set GREEN to full brightness
time.sleep(1) # wait 1 second
board.analogWrite(BLUE, 0) # turn GREEN off
# press ctrl+c while the console is active to terminate the program
except:
board.close() # close the serial connection
| true |
65418f750afea14168ea6f8095b9bf1234b722a8 | KiranGowda10/Add-2-Linked-Lists---LeetCode | /add_2_num.py | 832 | 4.125 | 4 |
class Node:
def __init__(self, data = None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = Node()
def append(self, data):
new_node = Node(data)
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = new_node
def display(self):
elements1 = []
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
elements1.append(current_node.data)
add1 = LinkedList()
add1.append(1)
add1.append(2)
add1.append(3)
print(add1.display())
add2 = LinkedList()
add2.append(4)
add2.append(5)
add2.append(6)
print(add2.display())
| true |
25a39a23d66108f8909741e94c7e9e290479c044 | fatmazehraCiftci/GlobalAIHubPythonCourse | /Homeworks/homework2.py | 482 | 4.1875 | 4 | """
Create a list and swap the second half of the list with the first half of the list and
print this list on the screen
"""
def DivideandSwap(list):
length=len(list)
list1=[]
list2=[]
for i in range(int(length/2)):
list1.append(list[i])
remainder=length-int(length/2)
for i in range(remainder):
list2.append(list[i-remainder])
list=list2+list1
print(list)
list=[1,2,3,4,5,6]
DivideandSwap(list) | true |
3766e43d653c9e92a2fdb946a34de44c0e43905c | shivamagrawal3900/Python-crash-course | /chapter5-if_statements.py | 1,249 | 4.1875 | 4 | cars = ['Audi', 'BMW', 'Jaguar', 'LandRover']
for car in cars:
if car == 'Jaguar':
print(car.upper())
else:
print(car)
# == is case sensitive
print(cars[1]=='bmw')
# > False
# !=
print(cars[1]!='Audi')
# > True
# Numerical Comparisions
# ==, !=, <, >, <=, >=
# Checking multiple values
# 'and' and 'or' operations. NOTE: '&' and '|' does not work
print(cars[0]=='Audi' and cars[1] == 'BMW')
# >True
print(cars[2]=='Jaguar' or cars[3]=='Jaguar')
# >True
# First 'and' operations takes place then or
print(cars[2]=='Jaguar' and cars[3]=='Jaguar' or cars[0]=='Audi' and cars[1] == 'Audi')
# >False
# To check if the value is in list, use 'in' keyword
print('Jaguar' in cars)
# >True
# To check if the value is not in the list, use 'not in' keyword
print('Tata' not in cars)
# >True
# IF STATEMENTS
# NOTE: assignment in if won't work, i.e. if a=2 will give an error
# If - elif - else statements
value=15
if value%15 == 0:
print('buzzfizz')
elif value%3 == 0:
print('buzz')
elif value%5 == 0:
print('fizz')
else:
print('none')
# To check if list is empty
toppings = []
if toppings:
print('toppings are: '+str(toppings))
else:
print('no toppings')
# >no toppings
# For pEP 8 styling, use singe space both sides of operator | true |
d9d121a9240b4712f6cbacb802064f235ff57413 | Avis20/learn | /python/books/essential_algo/ch3-linked_list/main.py | 2,286 | 4.125 | 4 | class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self, head: Node | None = None):
self.head = head
def add_after(self, search_val: int, new_node: Node):
node = self.head
while node:
if node.val == search_val:
new_node.next = node.next
node.next = new_node
return None
node = node.next
raise Exception("Node Not Found")
def add_last(self, new_node: Node):
# Создадим фиктивную ноду чтобы не проверять is none в конце
# Даже если у нас пустой список, node.next не сломается
dummy = Node(..., next=self.head)
node = dummy
while node.next:
node = node.next
node.next = new_node
self.head = dummy.next
def add_first(self, new_node: Node):
new_node.next = self.head
self.head = new_node
def __repr__(self):
nodes = []
node = self.head
while node:
nodes.append(str(node.val))
node = node.next
nodes.append("None")
return " -> ".join(nodes)
def print_llist(self) -> None:
node = self.head
while node:
print(node.val)
node = node.next
def find_before(self, target: int) -> Node | None:
dummy = Node(..., next=self.head)
node = dummy
while node.next:
if node.next.val == target:
return node.next
node = node.next
return None
def find(self, target) -> Node | None:
node = self.head
while node:
if node.val == target:
return node
node = node.next
return None
if __name__ == "__main__":
node1 = Node(1)
node2 = Node(2)
node1.next = node2
node3 = Node(3)
node2.next = node3
llist = LinkedList(node1)
llist.print_llist()
print(llist.find(3))
print(llist.find_before(3))
print(llist)
llist.add_first(Node(4))
print(llist)
llist.add_last(Node(6))
print(llist)
llist.add_after(1, Node(7))
print(llist)
| false |
09ea43cd396693c775912dd83794f43c38de8ee5 | deepikaasharma/Parallel-Lists-Challenge | /main.py | 1,333 | 4.125 | 4 | """nums_a = [1, 3, 5]
nums_b = [2, 4, 6]
res = 0
for a, b in zip(nums_a, nums_b):
res += a * b"""
"""Write a function called enum_sum which takes a list of numbers and returns the sum of the numbers multiplied by their corresponding index incremented by one.
Ex: enum_sum([2, 4, 6]) -> (index 0 + 1)*2 + (index 1 + 1)*4 + (index 2 + 1)*6 -> 1*2 + 2*4 + 3*6 -> 28
num_list = []
def enum_sum(num_list):
num_sum = 0
for idx, elem in enumerate(num_list):
num_sum += (idx+1)*elem
return num_sum
print(enum_sum([2,4,6]))
"""
"""Implement the function dbl_seq_sum which takes two lists of positive integers and computes the summation
∑k=1(−1)**k⋅(ak+bk/ 1+ak⋅bk)
""enum = len(list1)
for a,b in zip(enum list1, list2):
sum += ((-1)**k)* ((a+b)/(1+(a*b)))
return sum""
Where ak
and bk refer to the k-th elements in the two given lists. Notice that there is no upper bound on the summation. This just means "sum over all the elements". Assume that both lists will be the same length, and take note of the starting index of the summation."""
nums_a = []
nums_b = []
def dbl_seq_sum(nums_a, nums_b):
sum_ = 0
enum = range(1, len(nums_a)+1)
for k, a_k, b_k in zip(enum, nums_a, nums_b):
sum_ += ((-1)**k)* ((a_k+b_k)/(1+(a_k*b_k)))
return sum_
print(dbl_seq_sum([1,2,3],[3,4,5])) | true |
8976ba885b018f928284de9128f6b2ce4725c4dc | BibhuPrasadPadhy/Python-for-Data-Science | /Python Basics/100_Python_Programs/Question2.py | 501 | 4.4375 | 4 | ##Write a program which can compute the factorial of a given numbers.
##The results should be printed in a comma-separated sequence on a single line.
##Suppose the following input is supplied to the program:
##8
##Then, the output should be:
##40320
##
##Hints:
##In case of input data being supplied to the question, it should be assumed to be a console input.
def factorial(num):
if num == 0:
return 1
else:
return num*factorial(num-1)
print(factorial(5))
| true |
6b68f861e8ba815ad33e546ca6d5ff28b2fb3add | navjo7/DataStructure | /python/sorting/sort.py | 489 | 4.1875 | 4 | unsortedArray = [ 5, 3, 6, 8, 2, 1, 4, 5, 6 ]
print("unsorted : ",*unsortedArray)
# selection sort
for i in range(len(unsortedArray)):
minimumIndex = i
for j in range(i+1,len(unsortedArray)):
if unsortedArray[j] < unsortedArray[minimumIndex]:
minimumIndex = j
temp = unsortedArray[i]
unsortedArray[i] = unsortedArray[minimumIndex]
unsortedArray[minimumIndex] = temp
for i in range(len(unsortedArray)):
print(unsortedArray[i],end=' ')
print() | false |
d68c9cf85a4f6a2cb377a94c2c124a55feccd66c | pmk2109/Week0 | /Code2/dict_exercise.py | 1,513 | 4.28125 | 4 | from collections import defaultdict
def dict_to_str(d):
'''
INPUT: dict
OUTPUT: str
Return a str containing each key and value in dict d. Keys and values are
separated by a colon and a space. Each key-value pair is separated by a new
line.
For example:
a: 1
b: 2
For nice pythonic code, use iteritems!
Note: it's possible to do this in 1 line using list comprehensions and the
join method.
'''
return "\n".join(["{}: {}".format(k,v) for k,v in d.iteritems()])
def dict_to_str_sorted(d):
'''
INPUT: dict
OUTPUT: str
Return a str containing each key and value in dict d. Keys and values are
separated by a colon and a space. Each key-value pair is sorted in ascending order by key.
This is sorted version of dict_to_str().
Note: This one is also doable in one line!
'''
return "\n".join(list(["{}: {}".format(k,v) for k,v in sorted(d.iteritems())]))
def dict_difference(d1, d2):
'''
INPUT: dict, dict
OUTPUT: dict
Combine the two dictionaries, d1 and d2 as follows. The keys are the union of the keys
from each dictionary. If the keys are in both dictionaries then the values should be the
absolute value of the difference between the two values. If a value is only in one dictionary, the
value should be the absolute value of that value.
'''
d3_dict = {}
for key in (set(d1) | set(d2)):
d3_dict[key] = abs(d1.get(key,0) - d2.get(key,0)))
return d3_dict
| true |
a63908c918a6b0cbd35b98485fc79683c3923138 | joy-joy/pcc | /ch03/exercise_3_8.py | 1,075 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 17 21:17:17 2018
@author: joy
"""
# Seeing the World
visit_list = ["Machu Picchu", "Phuket", "Bali",
"Grand Canyon", "Santorini", "Dubai",
"New York City", "Paris", "London", "Sydney"]
print("\nVisit List:")
print(visit_list)
print("\nSorted List:")
print(sorted(visit_list))
print("\nOriginal List still preserved:")
print(visit_list)
print("\nReverse List:")
print(sorted(visit_list, reverse=True))
# Using the reverse() method on original list:
visit_list.reverse()
print("\nOrder has changed in the Original List:")
print(visit_list)
# Using the reverse() method to revert back to the original list:
visit_list.reverse()
print("\nOrder back to that of the Original List:")
print(visit_list)
# Using the sort() method to sort it (permanent change):
visit_list.sort()
print('\nSorted List using "sort()":')
print(visit_list)
# Using the sort() method to reverse sort it:
visit_list.sort(reverse = True)
print('\nReverse Sorted List using "sort()":')
print(visit_list)
| true |
093fbab0a28da1fb96ac4cf105847729dccf9a35 | joy-joy/pcc | /ch03/exercise_3_10.py | 2,229 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 17 21:38:45 2018
@author: joy
"""
# Every function
countries = ['USA', 'UK', 'USSR', 'Brazil', 'India', 'Bangladesh',
'Pakistan', 'Mexico', 'Saudi Arabia', 'Australia']
print("\nHere's our initial list of countries:\n", countries)
# .append() - Adding an element/item:
countries.append('Peru')
print('\nList of countries with "Peru" added using ".append()":\n', countries)
# .insert() - Inserting an element/item:
print('\nCountry being deleted:', countries[-1])
del countries[-1]
print('List now with the country deleted\n', countries)
# .pop() - removing an element/item:
popped_country = countries.pop()
print("\nPopped country:", popped_country)
print('List now with the country popped:\n', countries)
# popping by index
popped_country = countries.pop(-1)
print("\nPopped country:", popped_country)
print('List now with the country popped:\n', countries)
# .remove() - removing an element/item by value:
print('\nRemoving country: "USSR"')
countries.remove('USSR')
print('List now with the country removed:\n', countries)
# .reverse() - reversing order of the list:
countries.reverse()
print("\nReverse order now:\n", countries)
countries.reverse()
print("\nRevert back:\n", countries)
# .sorted() - Returns a sorted list, keeping original list unchanged
print('\nList sorted using "sorted()":\n', sorted(countries))
print("\nHere's the original list unchanged:\n", countries)
# .sorted() - with parameter, reverse=True
print('\nList reverse-sorted using "sorted()":\n',
sorted(countries, reverse=True))
print("\nHere's the original list unchanged:\n", countries)
# .sort() - Permanently sorting a list
countries.sort()
print("\nList permanently sorted:\n", countries)
# .sort() - Permanent reverse sort
countries.sort(reverse=True)
print("\nList permanently reverse-sorted:\n", countries)
# len() function to find length of the list:
print("\nSize of the list (i.e. number of countries):",
len(countries))
# modifying an element in the list (i.e. changing a country)
countries[0] = 'China'
print("How the list looks with the first country changed "
+ "to 'China'\n", countries) | false |
7705715e8e7b21cfbc6b0b3c32d44f9463333c80 | janbalaz/ds | /selection_sort.py | 1,048 | 4.28125 | 4 | from typing import List
def find_smallest(i: int, arr: List[int]) -> int:
"""
Finds the smallest element in array starting after `i`.
:param i: index of the current minimum
:param arr: array of integers
:return: position of the smallest element
"""
smallest = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[smallest]:
smallest = j
return smallest
def swap_elements(i: int, j: int, arr: List[int]) -> None:
"""
Swaps the elements in array.
:param i: position i
:param j: position j
:param arr: array of integers
"""
arr[i], arr[j] = arr[j], arr[i]
def selection_sort(arr: List[int]):
"""
Returns sorted array using selection sort.
Places sorted values on the left side of the array
by swapping the smallest element with current position.
:param arr: array of integers
:return: sorted array of integers
"""
for i in range(len(arr) - 1):
j = find_smallest(i, arr)
swap_elements(i, j, arr)
return arr
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.