blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
d0bb4429e990189944bb9550488f7f5bbfcf5fe1
|
kamit17/Python
|
/PCC/Chp8/pizza.py
| 536
| 4.4375
| 4
|
#Passing an aribitrary Number of Arguments
def make_pizza(*toppings):
# the * in the parameter tells python to make an empty tuple andpack
#whatever value it receives into this tuple.
#"""Print the list of toppings you have requested"""
#print(toppings)
"""Summarize the pizza we are about to make"""
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
| true
|
e659f051f0d0730bdd8e2c8f60271db08151a2bb
|
kamit17/Python
|
/PCC/Chp7/Super_powers.py
| 1,077
| 4.4375
| 4
|
"""
7-10. Dream Vacation: Write a program that polls users about superpowers . Write a prompt similar to if you could have one superpower then what would it be?
Include a block of code that prints the results of the poll.
"""
#a place holder dictionary to store the responses
superpowers= {}
polling_active = True
#Write the prompts
#name_prompt = '\nWhat is your name? '
#question_prompt = '\nIf you could have one super power then what would it be ? '
while polling_active:
#each pass through the while loop prompts for the user name and response
name = input('\nWhat is your name? ')
superpower= input('\nIf you could have one super power then what would it be ? ')
#store the question in the dictionary
superpowers[name] = superpower
#find out if anyone else is going to take the quiz
repeat = input('Would someone else take the quiz? (yes/no)')
if repeat == 'no':
polling_active = False
#Showing the results
for name,superpower in superpowers.items():
print(name + ' Would like to have this superpower: ' + superpower)
| true
|
68e9fed9678b9c5996525d08c2d96df277844d0a
|
kamit17/Python
|
/W3Resource_Exercises/Strings/ex3.py
| 750
| 4.15625
| 4
|
"""
Write a Python program to get a string made of the first 2 and the last 2 chars
from a given a string. If the string length is less than 2, return instead of
the empty string.
Sample String : 'w3resource'
Expected Result : 'w3ce'
Sample String : 'w3'
Expected Result : 'w3w3'
Sample String : ' w'
Expected Result : Empty String
"""
def stringcon(str1):
if len(str1) < 2:
return ''
return str1[0:2] + str1[-2:]
response = ''
while True:
test_string = input('Enter the string to be tested: ')
print(stringcon(test_string))
print('Do you want another string to be tested? Yes to continue and No to exit ')
response= input()
if response == 'Yes':
continue
else:
break
print('Thank you!')
| true
|
ec326316fb546cf8ebcd25e18e1a81cdf845ef70
|
kamit17/Python
|
/PCC/Chp8/cities.py
| 560
| 4.65625
| 5
|
"""
8-5. Cities: Write a function called describe_city() that accepts the name
of a city and its country . The function should print a simple sentence,
such as Reykjavik is in Iceland . Give the parameter for the country a
default value . Call your function for three different cities, at least one
of which is not in the default country .
"""
def describe_city(name,country = "iceland"):
print(name.title() + " is the capital of " + country.title())
describe_city("reykjavik")
describe_city("new delhi","india")
describe_city("bucharest","romania")
| true
|
c205b507ef49f227a8535774a0373e95357a78a9
|
kamit17/Python
|
/W3Resource_Exercises/Strings/ex8.py
| 385
| 4.40625
| 4
|
#Write a Python function that takes a list of words and returns the length of the longest one
def length_longest(words_list):
word_len = words_list[0]
for i in words_list:
if len(i) > len(word_len):
word_len = i
return len(word_len)
a_list = ["Hello","Hi","Applebees","pineapple"]
print("The lenght of the longest word is: ",length_longest(a_list))
| true
|
b3d96325222b5bdb4866d55a6d7eb48c19ba8a55
|
kamit17/Python
|
/Think_Python/Chp3/Exercises/ex5.py
| 900
| 4.3125
| 4
|
# Use for loops to make a turtle draw these regular polygons(regular means all sides the same
# # lengths,all angles the same):
# • An equilateral triangle
# • A square
# • A hexagon (six sides)
# • An octagon (eight sides)
import turtle #Allows us to use turtles
wn = turtle.Screen() # creates a playground for turtles
tess = turtle.Turtle() # Create a turtle, assign to tess
for _ in range(3):
tess.left(120) # Move tess along
tess.forward(90)
tess.color("blue")
tess.forward (20)
# • A square
for _ in range(4):
tess.forward(40)
tess.left(90) # Move tess along
tess.right(120)
tess.color("red")
# • A hexagon
for _ in range(6):
tess.forward(90)
tess.left(60) # Move tess along
tess.forward(80)
tess.color("yellow")
# • An octagon (eight sides)
for _ in range(8):
# Move tess along
tess.forward(90)
tess.right(45)
window.mainloop()
| true
|
9da2414b95d9cf62789bc8fbecec341a686384b4
|
kamit17/Python
|
/PCC/Chp8/printing_models.py
| 868
| 4.3125
| 4
|
"""
Consider a company that creates 3D printed models of designs that users submit.
Designs that need to be printed are stored in a list, and after being printed
they’re moved to a separate list.
The following code does this without using functions:
"""
#Start with some designs that need to be printed
unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models = []
#Simulate printing each design, until none are left
#Move each design to completed_models after printing.
while unprinted_designs:
current_design = unprinted_designs.pop()
#simulate creating a 3D print fromo the design.
print("Printing model: " + current_design)
completed_models.append(current_design)
#Display all completed models.
print("\nTHe following models have been printed.")
for completed_model in completed_models:
print(completed_model)
| true
|
11fcf4fdd977a27405e64abbd6cfb89a1c266140
|
kamit17/Python
|
/W3Resource_Exercises/Strings/ex14.py
| 405
| 4.28125
| 4
|
# Write a Python program that accepts a comma separated sequence of words as input and prints the unique words in sorted form (alphanumerically). Go to the editor
#Sample Words : red, white, black, red, green, black
#Expected Result : black, green, red, white,red
sample_words = input('Enter a comma seperated list of words:')
words = sample_words.split(",")
words = sorted(words)
print(",".join(words))
| true
|
50ae04b492f9c9745132bbca770610cbd8f751bc
|
kamit17/Python
|
/W3Resource_Exercises/Strings/ex25.py
| 1,113
| 4.8125
| 5
|
#. Write a Python program to create a Caesar encryption.
#c = (x -n ) % 26 where x is the ASCII key of the source message, n is the key, and 26 since there are 26 characters
def encrypted(string,shift):
#empty string to hold the cipher
cipher = ""
#traversing the plain text
for char in string:
# if char is empty
if char == " ":
cpiher = cipher + char
# Encrpyt uppercase characters in plain text
#note: The chr() function (pronounced “char”, short for “character”) takes an integer ordinal and returns a single-character string. The ord() function (short for “ordinal”) takes a single-character string, and returns the integer ordinal value.
elif char.isupper():
cipher = cipher + chr((ord(char)+shift-65)%26 + 65)
#Encrypt lower case characters in plain text
else:
cipher = cipher + chr((ord(char)+shift-97)%26 + 97)
return cipher
text = input("enter the text: ")
s = int(input("Enter the shift key: "))
print("The original string is : ",text)
print('The encrypted msg is : ',encrypted(text,s))
| true
|
5fa4fc1436939b2fc55959ff69777aa79bf357f8
|
kamit17/Python
|
/AutomateTheBoringStuff/RegularExpressions/PhoneNumber.py
| 1,311
| 4.46875
| 4
|
#PhoneNumber.py - A simple program to find phone number in a string without regular expressions.
def isPhoneNumber(text): #415 - 555-
if len(text) !=12: #checks if string is exactly 12 characters
return False #not phone number -sized
for i in range(0,3):
if not text[i].isdecimal(): #checks if area code consists of only numeric characters
return False #no area code
if text[3] !='-': #nneds to have a hyphen after the area code
return False #missing -
for i in range(4,7):
if not text[i].isdecimal():
return False
if text[7] !='-':
return False
for i in range(8,12):
if not text[i].isdecimal():
return False
return True
#print('415-555-4242 is a phone number:')
#print(isPhoneNumber('415-555-4242'))
#print('Moshi moshi is a phone number:')
#print(isPhoneNumber('Moshi moshi'))
message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
foundNumber = False
for i in range(len(message)):
chunk = message[i:i+12]
if isPhoneNumber(chunk):
print('Phone number found: '+ chunk)
foundNumber = True
if not foundNumber:
print('Could not find any phone numbers.')
print('Done')
| true
|
5ea2af667b11e03c79aa1afd12dc28c5dfaa95ad
|
kamit17/Python
|
/AutomateTheBoringStuff/DataTypes/string_method2.py
| 1,161
| 4.53125
| 5
|
# -*- coding: utf-8 -*-
#python code to demonstrate working of string methods
str = '''Betty Botta bought a bit of butter.“But,” she said, “this butter's bitter!'''
str2 = 'butter'
#using startswith() to find if str starts with str2
if str.startswith(str2):
print("str begins with str2")
else:
print('str does not begin with str2')
#using endswith() to find if str ends with str2
if str.endswith(str2):
print('str ends with str2')
else:
print('str does not end with str2')
# checking if all characters in str are upper cased
if str.isupper():
print('All characters in str are upper case')
else:
print('All characers in str are not upper case')
# checking if all characters in str1 are lower cased
if str2.islower() :
print ("All characters in str1 are lower cased")
else : print ("All characters in str1 are not lower cased")
str =str.lower()
print('The lower case converted string is : '+str)
str2 = str2.upper()
print('The upper case converted string is : '+str2)
str3 = str.swapcase()
print('The swapped case string is : '+str)
str4 = str.title();
print ("The title case converted string is : " + str4)
| true
|
ac016d41898a659d95df620ec23aa30d21a52a5a
|
kamit17/Python
|
/AutomateTheBoringStuff/DataTypes/deepcopyexample.py
| 761
| 4.71875
| 5
|
# Python code to demonstarate copy operation
# importing "copy for copy Operations"
import copy
# initializing list 1
list1 = [1, 2, [3, 5], 4]
# using deepcopy to deep copy
list2 = copy.deepcopy(list1)
# original elements of the list
print("the original elements before deepcopy")
for i in range(0, len(list1)):
print(list1[i], end=' ')
print("\r")
# adding an element to the new list
list2[2][0] = 7
# checking if the change is being reflected
print('The new list of element after deep copy')
for i in range(0, len(list2)):
print(list2[i], end=' ')
print('\r')
# change not being reflected in Original list
# as it is deep copy
print('The original elements after deep copy are :')
for i in range(0, len(list1)):
print(list1[i], end=' ')
| true
|
ac4e5aea1c303989bd665f2ea804827e50c5d7c3
|
kamit17/Python
|
/examples/myMadlib.py
| 1,879
| 4.25
| 4
|
"""
Once upon a time, deep in an ancient jungle,
there lived a {animal}. This {animal}
liked to eat {food}, but the jungle had
very little {food} to offer. One day, an
explorer found the {animal} and discovered
it liked {food}. The explorer took the
{animal} back to {city}, where it could
eat as much {food} as it wanted. However,
the {animal} became homesick, so the
explorer brought it back to the jungle,
leaving a large supply of {food}.
The End
"""
storyFormat ='''Once {people} went on a journey together. On their way
there was a deep {place}. There was no {item}; so they swam across
the {place}. They all got safely to the other bank.
“Are we allsafe?” asked one of the Wise Men,
“Let us count and see,” said the others.
The first man counted, “One, two, three, four, five,” and
said, “Look ! one of us is missing. There are only five of us here.”
He counted only the others.
“You are silly,” said a second Wise Man. “Let me count,
'''
def tellStory():
userPicks = dict()
addPick('people', userPicks)
addPick('place', userPicks)
addPick('item', userPicks)
story = storyFormat.format(**userPicks)
print(story)
def addPick(cue, dictionary):
'''Prompt for a user response using the cue string,
and place the cue-response pair in the dictionary.
'''
prompt = 'Fill the blank for ' + cue + ': '
response = input(prompt).strip() # 3.2 Windows bug fix
dictionary[cue] = response
tellStory()
input("Press Enter to end the program.")
| true
|
3f7eb92c2a6cd9ba73ab5dd3c9692528ce9e5316
|
kamit17/Python
|
/Think_Python/Chp13/Examples/read_whole_file.py
| 434
| 4.125
| 4
|
"""Another way of working with text files is to read the complete contents of the file into a string, and then to use our string-processing skills to work with the contents."""
# A simple example to count the number of words in a file
f = open("/Users/maverick/GitHub/Python/Think_Python/Chp13/Examples/friends.txt")
content = f.read()
f.close()
words = content.split()
print("There are {0} words in the file.".format(len(words)))
| true
|
f877f83d6e29bb5f104414ae48403ba91be76d0e
|
kamit17/Python
|
/W3Resource_Exercises/Strings/ex2.py
| 407
| 4.4375
| 4
|
#Write a Python program to count the number of characters (character frequency) in a string.
def char_count(input_string):
"""Funciton to calculate the character frequency in a string"""
frequency = {}
for char in input_string:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
return frequency
print(char_count('Data science'))
| true
|
5efb695bfbc93a94fd87715af11c74efb748c25f
|
kamit17/Python
|
/W3Resource_Exercises/Loops and Conditionals/temperature_convert.py
| 718
| 4.1875
| 4
|
"""
Write a Python program to convert temperatures to and from celsius, fahrenheit.
[ Formula : c/5 = f-32/9 [ where c = temperature in celsius and f = temperature in fahrenheit ]
Expected Output :
60°C is 140 in Fahrenheit
45°F is 7 in Celsius
"""
def convert(temp,unit):
unit = unit.lower()
if unit == 'c':
temp = 9.0/5.0 * temp +32
#
return '%s degrees Farenheit'% temp
if unit == 'f':
temp =(temp-32) /9.0 * 5.0
return '%s degress Celcius'% temp
intemp = int(input('What is the temperature?\n'))
inunit = str(input('What is the measure of unit (f or c ):\n'))
#print(convert(intemp,inunit))
print('The converted temperature is :',convert(intemp,inunit))
| true
|
73ca90f6464b5b0d5c94006c89624062bd0510b2
|
kamit17/Python
|
/LPTHW/ex33_1.py
| 442
| 4.21875
| 4
|
"""
Convert this while-loop to a function that you can call,
and replace 6 in the test (i < 6) with a variable.
"""
def loop(max,step):
i = 0
numbers = []
for i in range(0,max,step):
print(f"At the top i is {i}")
numbers.append(i)
print("Numbers now: ",numbers)
print(f"At the bottom i is {i}")
return numbers
numbers = loop(10,2)
print('The numbers: ')
for num in numbers:
print(num)
| true
|
24031668fb0e494eb7c1197a0a27060d8a2d10a6
|
Gonz8088/ITEC3312
|
/Homework/Homework04.py
| 1,883
| 4.15625
| 4
|
# PROGRAMMER: Paul Gonzales
# DATE: month day, 2019
# ASSIGNMENT: Homework 04
# ALGORITHM: The StopWatch class is built according to the specification,
# and uses a datetime object, and timedelta object from the datetime moduleself.
# when a StopWatch object is created, the __startTime attribute is initialized
# using the now().time() method. The for loop adds the sum of integers from 1 to
# 1000000, and then the stopwatch.stop() method is called to get the current time
# at the end of the loop. The elapsed time is then determined by creating timedelta
# objects. One for the __startTime, and one for the __endTime. The __startTime
# timedelta object is subtracted from the __endTime timedelta object, and the
# result is returned as a string.
from datetime import datetime as dt
from datetime import timedelta as td
class StopWatch:
"""docstring for StopWatch."""
def __init__(self):
self.__startTime = dt.now().time()
self.__endTime = None
def get_startTime(self):
return self.__startTime
def get_endTime(self):
return self.__endTime
def get_ElapsedTime(self):
self.__c = td(hours=self.__startTime.hour, minutes=self.__startTime.minute, \
seconds=self.__startTime.second, milliseconds=self.__startTime.microsecond)
self.__d = td(hours=self.__endTime.hour, minutes=self.__endTime.minute, \
seconds=self.__endTime.second, milliseconds=self.__endTime.microsecond)
return str(self.__d-self.__c)
def start(self):
self.__startTime = dt.now().time()
return
def stop(self):
self.__endTime = dt.now().time()
return
def main():
stopwatch = StopWatch()
for i in range(1000001):
i += i
stopwatch.stop()
print("Sum:", i)
print("Elapsed Time:", stopwatch.get_ElapsedTime())
return
if __name__ == "__main__":
main()
| true
|
4a29a67f51e667bba2a0ab786253d0b7fe84e3cc
|
Alonski/superbootcamp
|
/sentence_statistics.py
| 626
| 4.4375
| 4
|
def word_lengths(s):
# ==== YOUR CODE HERE ===
return [len(word) for word in s.split()]
# =======================
result = word_lengths("Contrary to popular belief Lorem Ipsum is not simply random text")
print("Result:", result)
assert result == [8, 2, 7, 6, 5, 5, 2, 3, 6, 6, 4]
print("OK")
def max_word_length(s):
# ==== YOUR CODE HERE ===
return max(word_lengths(s))
# return max([len(word) for word in s.split()])
# =======================
result = max_word_length("Contrary to popular belief Lorem Ipsum is not simply random text")
print("Result:", result)
assert result == 8
print("OK")
| true
|
fe95c71fc27ea8a2215b44f62c96f43572f2e80e
|
shengyucaihua/leetcode
|
/Leetcode349_intersection.py
| 446
| 4.25
| 4
|
# 给定两个数组,编写一个函数来计算它们的交集。
#
# 示例 1:
#
# 输入: nums1 = [1,2,2,1], nums2 = [2,2]
# 输出: [2]
# 示例 2:
#
# 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
# 输出: [9,4]
def intersection(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
num1_set = set(nums1)
num2_set = set(nums2)
return list(num1_set.intersection(num2_set))
| false
|
4cde5a8cead3d59d99b0030cd22b2f1cd2f93238
|
kevin-sooter/Intro-Python-I
|
/src/dictionaries.py
| 1,360
| 4.71875
| 5
|
#<<<<<<< master
# Make an array of dictionaries. Each dictionary should have keys:
#
# lat: the latitude
# lon: the longitude
# name: the waypoint name
#
# Make up three entries of various values.
=======
#"""
#Dictionaries are Python's implementation of associative arrays.
#There's not much different with Python's version compared to what
#you'll find in other languages (though you can also initialize and
#populate dictionaries using comprehensions just like you can with
#lists!).
#The docs can be found here:
#https://docs.python.org/3/tutorial/datastructures.html#dictionaries
#For this exercise, you have a list of dictionaries. Each dictionary
#has the following keys:
# - lat: a signed integer representing a latitude value
# - lon: a signed integer representing a longitude value
# - name: a name string for this location
"""
#>>>>>>> master
waypoints = [
{
"lat": 43,
"lon": -121,
"name": "Spain"
},
{
"lat": 41,
"lon": -123,
"name": "Colombia"
},
{
"lat": 43,
"lon": -122,
"name": "Mexico"
}
]
# Write a loop that prints out all the field values for all the waypoints
for item in waypoints:
print(item.values())
# Add a new waypoint to the list
waypoints.append({
"lat": 22,
"lon": -181,
"name": "Texas"
})
print(waypoints)
| true
|
3f191e135d45d0984a84ccec412cd5337b7772cd
|
OlehHnyp/Home_Work_7
|
/Home_Work_7_Task_1_implisit.py
| 1,396
| 4.3125
| 4
|
import math as m
def triangle_area():
"""
This function calculate an area
of triangle
Input parameters:
Output: float
"""
while 1:
try:
triangle_side = float(input(
"Insert side of triangle:"
))
triangle_height = float(input(
"Insert triangle height taken from that side:"
))
return round(0.5 * triangle_side * triangle_height, 2)
except ValueError:
print("Try again!")
def rectangle_area():
"""
This function calculate
an area of rectangle
Input parameters:
Output: float
"""
while 1:
try:
rectangle_lenght = float(input(
"Insert rectangle lenght:"
))
rectangle_height = float(input(
"Insert rectangle height:"
))
return round(rectangle_lenght*rectangle_height, 2)
except ValueError:
print("Try again!")
def circle_area():
"""
This function calculate an area
of circle
Input parameters:
Output: float
"""
while 1:
try:
circle_radius = float(input(
"Enter circle radius:"
))
return round(m.pi * m.pow(circle_radius,2), 2)
except ValueError:
print("Try again!")
| true
|
5abddd2980f17f30104ea41795c648bab8a5fc43
|
bennywinefeld/CodiacClub
|
/ttt1.py
| 2,276
| 4.15625
| 4
|
# Board is represented by an array with indexes from 0 to 0
# each array element can contain values: ' ','X','O'
def drawBoard(board):
print(board)
print("+---+---+---+")
for i in range(3):
print("| {} | {} | {} |".format(board[3*i],board[3*i+1],board[3*i+2]))
print("+---+---+---+")
# Insert X or O to board, for ex: makeMove(myBoard,'X',3)
def makeMove(board,X_or_O,position):
if(board[position] != ' '):
print("This cell is already taken, choose another")
return False
board[position] = X_or_O
return True
# Check if current player won by the last move
# Variable b stands for board. Used one letter var name to make expressions look short
def checkIfWon(b,X_or_O):
w = X_or_O * 3
if ((b[0]+b[1]+b[2] == w) or (b[3]+b[4]+b[5] == w) or (b[6]+b[7]+b[8] == w) or (b[0]+b[3]+b[6] == w) or \
(b[1]+b[4]+b[7] == w) or (b[2]+b[5]+b[8] == w) or (b[0]+b[4]+b[8] == w) or (b[2]+b[4]+b[6] == w)):
return True
return False
#=====================================================================
# Main program starts here
#=====================================================================
# Initialize the global variables controlling the gamegame
# Reset the board with all ' ', set gameOver flag to False, player 'X' starts first
myBoard = [' ']*9
gameOver = False
nowPlays = 'X'
# Draw initial (empty)
drawBoard(myBoard)
# Start the game and continue until someone wins or board is full
while (not gameOver):
# Ask current player to make a move. Repeat asking if move is illegal
position = int(input(nowPlays + " where do you want to go (1-9)? ")) - 1
while (not makeMove(myBoard,nowPlays,position)):
position = int(input(nowPlays + " where do you want to go (1-9)? ")) - 1
# Draw the board to display all the cells filled so far
drawBoard(myBoard)
# Check if the last move has won the game
if (checkIfWon(myBoard,nowPlays)):
print(nowPlays + " , you have won!")
gameOver = True
# Check if board is full. If yes, it's a tie!
if (not ' ' in myBoard):
print("It's a tie!")
gameOver = True
# Switch current player
if (nowPlays == 'X'):
nowPlays = 'O'
else:
nowPlays = 'X'
| true
|
3a45484bb82aa4f372c847992d2de7a2edf5c974
|
dr34mh4ck/lca-python
|
/node.py
| 1,949
| 4.28125
| 4
|
'''
*** Binary tree structure is composed by Nodes (left and right) with a
*** reference to its parent and the value the Node holds
'''
class Node:
value = None
left = None
right = None
parent = None
'''
*** empty initialization for the Node
'''
def __init__(self):
pass
'''
*** Checks wether this node has value assigned or not
'''
def is_empty(self):
return self.value is None
'''
*** Inserts a Node into the tree assigning the correct parent for the Node
'''
def push_impl(self, _value, _parent):
if self.value is None:
self.value = _value
self.parent = _parent
elif self.value < _value:
if self.right is None:
self.right = Node()
self.right.push_impl(_value, self)
elif self.value > _value:
if self.left is None:
self.left = Node()
self.left.push_impl(_value, self)
'''
*** Inserts a Node into the tree
'''
def push(self, _value):
self.push_impl(_value, None)
def print_pre_order(self):
self.print_pre_order_impl('')
'''
*** Prints the tree with preorder path
'''
def print_pre_order_impl(self, prefix):
if self.value is None:
print('-')
else:
print(prefix + str(self.value))
if self.left is not None:
self.left.print_pre_order_impl(prefix + ' ')
if self.right is not None:
self.right.print_pre_order_impl(prefix + ' ')
def path_to(self, _value):
path = ''
if self.value is None:
return ''
else:
if self.value > _value:
path += self.left.path_to(_value)
elif self.value < _value:
path += self.right.path_to(_value)
path += str(self.value) + '-'
return path
| true
|
d97b71f4e3a18bcc8d8dc325210b70bd605ecf37
|
AkshadaSayajiGhadge594/Serial-Programming
|
/SerialParallelProg.py
| 222
| 4.21875
| 4
|
print("----------Serial Parallel Programming-----------");
def square(n):
return (n*n);
#input list:
arr=[1,2,3,4,5]
#empty list to store result:
result=[];
for num in arr:
result.append(square(num));
print(result)
| true
|
6ee4d8571be4770511c0e065d839ce17fb068e3d
|
aisha109/project-97
|
/guessingGame.py
| 202
| 4.15625
| 4
|
Question = "Guess a number between 1 and 9"
print(Question)
QuestionInput = input("Enter your guess")
if(QuestionInput == 8 ):
print("YOU ARE RIGHT")
else:
print("ANOTHER GUESS")
| true
|
27e5d8667b78815b1e9de92b49ea0d5d7958603b
|
VAEH/TiempoLibre
|
/Funciones.py
| 834
| 4.15625
| 4
|
"""
Escriba un programa que solicite repetidamente a un usuario números enteros hasta
que el usuario ingrese 'hecho'. Una vez que se ingresa 'hecho', imprima el número
más grande y el más pequeño. Si el usuario ingresa algo que no sea un número válido,
agárrelo con un try / except y envíe un mensaje apropiado e ignore el número. Ingrese 7, 2,
bob, 10 y 4 y coincida con la salida a continuación.
"""
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done" : break
num = int(num)
#print(num)
if largest is None or largest>num:
largest=num
elif smallest is None or smallest <num:
smallest=num
except:
print('Invalid input')
print ("Minium", smallest)
print("Maximum", largest)
| false
|
7fa04a5cc1765c0d51d5eab50fca0d294d5b1ec7
|
natsthomare/CS116
|
/assignment 3/final/Assignment3.2.py
| 2,175
| 4.125
| 4
|
import check
def print_top_half(i,n):
'''
Prints the top half of the X-wing formation\
given n which is the number of lines in the top half of the X-wing formation\
and i which is the variable used as a line counter.
print_top_half -> Int Int -> None
Requires
0 <= i < n
n > 0
'''
if i == n+1:
return
elif i < n:
print(" " * i, "\\\\", " " * (n - i - 1), "|||||", " " * (n - i - 1), "//", " " * i)
return print_top_half(i+1,n)
else:
print(" " * i, "\\\\", "|||||", "//", " " * i)
return print_top_half(i + 1, n)
def print_bottom_half(i, n):
'''
Prints the bottom half of the X-wing formation \
given n which is the number of lines in the bottom half of the X-wing formation\
and i which is the variable used as a line counter.
print_bottom_half -> Int Int -> None
Requires
0 <= i < n
n > 0
'''
if i == n + 1:
return
elif i == 0:
print(" " * (n-i), "//" , "|||||", "\\\\", " " * (n-i))
return print_bottom_half(i + 1, n)
else:
print(" " * (n - i), "//", " " * (i-1) , "|||||", " " * (i-1), "\\\\", " " * (n - i))
return print_bottom_half(i + 1, n)
def x_wing(n):
'''
Returns None and the X-wing formation given a positive integer n.
x_wing: Int -> None
Requires
Examples:
x_wing(1) -> None
x_wing(5) -> None
'''
print_top_half (0, n-1)
print (" "*(n+3)+ "||o||")
print_bottom_half(0, n-1)
##Examples:
check.set_screen("X-wing with 3 rows with one top,bottom,and center row")
check.expect("Test 1", x_wing(1),None)
check.set_screen("X-wing with 11 rows with five top and bottom rows and one center row")
check.expect("Example 2", x_wing(5),None)
##Tests:
check.set_screen("X-wing with 3 rows with one top,bottom,and center row")
check.expect("Test 1", x_wing(1),None)
check.set_screen("X-wing with 5 rows with two top and bottom rows and one center row")
check.expect("Test 2", x_wing(2),None)
check.set_screen("X-wing with 11 rows with five top and bottom rows and one center row")
check.expect("Test 3", x_wing(5),None)
| false
|
300636cb53b57670c93110ab7fce3f600f6f30ca
|
candopi-team1/Candopi-programming101
|
/7_data_structures_and_algorithms/sorts_python/merge_sort_dummies.py
| 2,018
| 4.46875
| 4
|
# Merge Sort
def merge_sort(list):
# Determine whether the list is broken into individual pieces.
if len(list) < 2:
return list
# Find the middle of the list.
middle = len(list)//2
# Break the list into two pieces.
left = merge_sort(list[:middle])
right = merge_sort(list[middle:])
"""
ku=[0,1,2,3,4,5]
ku[0:2] or ku[2:] ==> [0, 1] position 2 not included
ku[2:] ==> [2, 3, 4, 5] position 2 was included
"""
# Merge the two sorted pieces into a larger piece.
print("Left side: ", left)
print("Right side: ", right)
merged = merge(left, right)
print("Merged ", merged)
return merged
def merge(left, right):
# When the left side or the right side is empty,
# it means that this is an individual item and is already sorted.
if not len(left):
return left
if not len(right):
return right
# Define variables used to merge the two pieces.
result = []
leftIndex = 0
rightIndex = 0
totalLen = len(left) + len(right)
# Keep working until all of the items are merged.
while (len(result) < totalLen):
# Perform the required comparisons and merge
# the pieces according to value.
if left[leftIndex] < right[rightIndex]:
result.append(left[leftIndex])
leftIndex+= 1
else:
result.append(right[rightIndex])
rightIndex+= 1
# When the left side or the right side is longer,
# add the remaining elements to the result.
if leftIndex == len(left) or rightIndex == len(right):
result.extend(left[leftIndex:]
or right[rightIndex:])
break
return result
data = [9, 5, 7, 4, 2, 8, 1, 10, 6, 3]
data2 = [9, 5, 9, 5,9, 5,9, 5, 7, 4, 2, 8, 1, 10, 6, 7,7,7,7,7,7,3]
print(merge_sort(data))
| true
|
ef23474b4f89dae3b6933ad571e0b4067b6f07c9
|
kuzaster/python_training_2020
|
/HW7/task3/task03.py
| 1,267
| 4.1875
| 4
|
"""
Given a Tic-Tac-Toe 3x3 board (can be unfinished).
Write a function that checks if the are some winners.
If there is "x" winner, function should return "x wins!"
If there is "o" winner, function should return "o wins!"
If there is a draw, function should return "draw!"
If board is unfinished, function should return "unfinished!"
Example:
[[-, -, o],
[-, x, o],
[x, o, x]]
Return value should be "unfinished"
[[-, -, o],
[-, o, o],
[x, x, x]]
Return value should be "x wins!"
"""
from itertools import chain
from typing import List
def tic_tac_toe_checker(board: List[List]) -> str:
n = len(board)
board = list(chain.from_iterable(board))
win_combs = []
for i in range(0, n ** 2, n):
win_combs.append(slice(i, i + n)) # add win rows
for i in range(n):
win_combs.append(slice(i, n ** 2, n)) # add win columns
win_combs.append(slice(0, n ** 2, n + 1)) # add win diagonal
win_combs.append(slice(n - 1, n ** 2 - 1, n - 1)) # add second win diagonal
for comb in win_combs:
comb_slice = board[comb]
if len(set(comb_slice)) == 1 and "-" not in comb_slice:
return f"{comb_slice[0]} wins!"
return "draw!" if "-" not in board else "unfinished!"
| true
|
9e70185a45e593613d2c1e459ecf01b9fc4e4d2c
|
KFernandez1988/SSL
|
/rb_py_node/pygrader/grader.py
| 609
| 4.1875
| 4
|
# python grader file
from grader_class import Grader
name = raw_input(' Please Student enter your name ')
assignment = raw_input('What was your test about ')
grade = ''
# checkting for the right data type
while( grade is not int):
try:
grade = int(raw_input('Can you please enter your score '))
if(grade < 0 or grade > 100):
print('Your score is either 0 or 100')
grade = ''
else:
break
except ValueError:
print('Please enter a valid score')
# intatiantion and printing
student = Grader(name, assignment, grade)
student.print_results()
| true
|
23bc9f44eac6986b8a2f3326d8053feda2770650
|
stewartrowley/CSE111
|
/Week 8/convert_list_dictionaries.py
| 785
| 4.25
| 4
|
# Example 6
def main():
# Create a list that contains five student numbers.
numbers = ["42-039-4736", "61-315-0160",
"10-450-1203", "75-421-2310", "07-103-5621"]
# Create a list that contains five student names.
names = ["Clint Huish", "Michelle Davis",
"Jorge Soares", "Abdul Ali", "Michelle Davis"]
# Convert the numbers list and names list into a dictionary.
student_dict = dict(zip(numbers, names))
# Print the entire student dictionary.
print(student_dict)
# Convert the student dictionary into
# two lists named keys and values.
keys = list(student_dict.keys())
values = list(student_dict.values())
# Print both lists.
print(keys)
print(values)
# Call main to start this program.
if __name__ == "__main__":
main()
| true
|
ac1acc7efa9872384ae7ec869fe853c4e8eff770
|
stewartrowley/CSE111
|
/Week 3/get_initials_organization.py
| 530
| 4.25
| 4
|
# the function gets initials for the code
def get_initial(name):
initial = name[0:1].upper()
return initial
# Ask for someones name and return the initials
first_name = input("Enter your first name: ")
first_name_initial = get_initial(first_name)
middle_name = input("Enter your middle name: ")
middle_name_initial = get_initial(middle_name)
last_name = input("Enter your last name: ")
last_name_initial = get_initial(last_name)
print(f"Your initials are: {first_name_initial}{middle_name_initial}{last_name_initial} ")
| true
|
3290638a7b521dc61d24b72bf98c7340a20f65d3
|
Ckk3/python-exercises
|
/EstruturasDeRepetiçãoWhile/menuOpções.py
| 1,576
| 4.25
| 4
|
'''Crie um programa que leia dois valores e mostre um menu na tela:
[ 1 ] somar
[ 2 ] multiplicar
[ 3 ] maior
[ 4 ] novos números
[ 5 ] sair do programa
Seu programa deverá realizar a operação solicitada em cada caso.'''
import os
firstNumber = int(input('Type the first number: '))
secondNumber = int(input('Type the first number: '))
option = int(0)
finalAnswer = str('')
while option != 5:
option = int(input('What do you wanna do?\n[ 1 ] Sum\n[ 2 ] Multiply\n[ 3 ] Upper\n[ 4 ] New Numbers\n[ 5 ] Quit\nOption: '))
if option == 1:
finalAnswer = 'The sum of {} and {} is {}'.format(firstNumber, secondNumber, firstNumber + secondNumber)
elif option == 2:
finalAnswer = 'The multiply of {} and {} is {}'.format(firstNumber, secondNumber, firstNumber * secondNumber)
elif option == 3:
if firstNumber == secondNumber:
finalAnswer = '{} and {} are equals!'.format(firstNumber, secondNumber)
else:
finalAnswer = '{} is upper than {}'.format(firstNumber if firstNumber > secondNumber else secondNumber, firstNumber if firstNumber < secondNumber else secondNumber)
elif option == 4:
firstNumber = int(input('Type the first number: '))
secondNumber = int(input('Type the first number: '))
finalAnswer = 'Now the numbers are {} and {}'.format(firstNumber, secondNumber)
elif option == 5:
break
else:
finalAnswer = 'Choose a valid option!!'
os.system('cls')
print(finalAnswer)
os.system('pause')
os.system('cls')
| false
|
70cc1506aa7c540297cdb93b340a02fcfd43ee2b
|
Ckk3/python-exercises
|
/EstruturasDeRepetiçãoWhile/fatorial.py
| 869
| 4.25
| 4
|
#Faça um programa que leia um número qualquer e mostre o seu fatorial.
#Ex: 5! = 5 x 4 x 3 x 2 x 1 = 120
from time import sleep
from math import factorial
userNum = int(input('Type the number who you want to know the factorial: '))
print('Calculating.',end='')
sleep(0.3)
print('.',end='')
sleep(0.3)
print('.')
sleep(0.3)
#Using While
'''
num = int(userNum)
fat = int(userNum - 1)
res = int(0)
finalRes = int(1)
while fat > 0:
res = fat * num
finalRes *= res
fat -= 2
num -= 2
print('!{} = {}'.format(userNum, finalRes))
'''
#Using for
'''
num = int(userNum)
fat = int(userNum - 1)
res = int(0)
finalRes = int(1)
for fat in range (userNum - 1, 0, -2):
res = fat * num
finalRes *= res
num -= 2
print('!{} = {}'.format(userNum, finalRes))
'''
#Using factorial class
'''
print('!{} = {}'.format(userNum, factorial(userNum)))
'''
| false
|
3e43d7fd2a86300d241cbc7546322f92e14d0b87
|
zhaowangbo/python
|
/第一阶段/是否上班.py
| 443
| 4.1875
| 4
|
while True:
day = input("enter a day from monday to sunday, and enter 'q' to quit")
week = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
if day == 'q':
break
if day not in week:
print("you must enter a day from monday to sunday")
continue
if day in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']:
print("work")
else:
print("play")
| true
|
cb5c23e7e270aead77e49ab266ed88dcbeb748ed
|
Krit-NameWalker/6230401848-oop-labs
|
/Krit-623040184-8-lab5/P4.py
| 587
| 4.15625
| 4
|
def fac(num):
if num == 0:
return 1
if num == 1:
return 1
else:
return num * fac(num-1)
if __name__ == "__main__":
try:
num = input("Enter an integer:")
num = int(num)
if num < 0:
print("Please enter a positive integer. {} is not a positive integer".format(num))
else:
print("factorial {} is {}".format(num, fac(num)))
except ValueError:
num = str(num)
print("Please enter a positive integer. invalid literal for int() with base 10: {} ".format(num))
| true
|
9dfabf53905b32a03ef4d0fd4009ce606bf76000
|
Mistarcy/python-hello-world
|
/week6/high_low.py
| 1,012
| 4.28125
| 4
|
# Example by James Fairbairn <j.fairbairn@tees.ac.uk>
# We wrote this together in class.
#
# **DO NOT REMOVE THIS HEADER**
#
# Notes:
# + This file is for demonstration purposes only.
# + You must use this example to guide your own solution.
# **DO NOT SUBMIT THIS FILE AS IS FOR ASSESSMENT**
import random
MAX_GUESSES = 5
RANGE_START = 1
RANGE_END = 30
number = random.randint(RANGE_START,RANGE_END)
name = input("Hello! What is your name? ")
print(name, ", I am thinking of a number between ", RANGE_START, " and ", RANGE_END, ".", sep="")
guesses_taken = 0
while guesses_taken < MAX_GUESSES:
guess = int(input("Please enter a number: "))
guesses_taken += 1
if guess < number:
print("Your guess is too low!")
elif guess > number:
print("Your guess is too high!")
else:
break
# end while loop
if guess == number:
print("Awesome, ", name, "! You guessed correctly in ", guesses_taken, " attempts!", sep="")
else:
print("Nope. The number I was thinking of was", number)
| true
|
1c194054862028e0455f6894afae2563cb750792
|
joaoo-vittor/estudo-python
|
/OrientacaoObjeto/aula5.py
| 426
| 4.15625
| 4
|
"""
Aula 5
Atributos de Classe - Python Orientado a Objetos
"""
class A:
vc = 123
a1 = A()
a2 = A()
a3 = A()
print('#'*30)
a3.vc = 321 # aqui estou criando um atribudo
print(a3.__dict__)
print(a2.__dict__)
print(a1.__dict__)
print(A.__dict__)
print('#'*30)
print('Antes de Alterar vc')
print(a1.vc)
print(a2.vc)
print(A.vc)
print('Depois de Alterar vc')
A.vc = 321
print(a1.vc)
print(a2.vc)
print(A.vc)
| false
|
2476b8db009ab4cf5c9dbed329b4a3de2fa45bcd
|
hunterad96/unbeatable_tic_tac_toe
|
/tic_tac_toe/display_functions.py
| 1,237
| 4.1875
| 4
|
import platform
from os import system
"""
Functions to handle the rendering of the board in the terminal,
and ensuring that the terminal doesn't become cluttered with boards
other than the board representing the most recent state of the game.
"""
# Function that cleans up the terminal to avoid having too many boards
# visible at the same time.
#
# Takes no parameters and returns nothing. Only cleans things up.
def clean():
os_name = platform.system().lower()
if 'windows' in os_name:
system('cls')
else:
system('clear')
# Function that handles printing the board representing the current state
# of the game.
#
# @param board_state [2D array of ints] which is the current board.
# @param player_choice an X or O representing which value the user chose.
# @param computer_choice an X or O value representing the value with which
# the computer is playing.
# Returns nothing. Only prints the current board.
def render(board_state, player_choice, computer_choice):
chars = {
-1: player_choice,
+1: computer_choice,
0: ' '
}
str_line = '---------------'
print('\n' + str_line)
for row in board_state:
for cell in row:
symbol = chars[cell]
print(f'| {symbol} |', end='')
print('\n' + str_line)
| true
|
35e52395a0d1b999fd9696cc00955d3d1203ed49
|
simmihacks/python_projects
|
/hangmanpseudo.py
| 1,377
| 4.28125
| 4
|
#this is not code but a Pseudocode for an MIT coding challenge:
#https://courses.edx.org/courses/course-v1:MITx+6.00.1x+2T2017_2/courseware/530b7f9a82784d0cb57de334828e3050/bfe9eb02884a4812883ff9e543887968/?child=first
"""
Hangman Pseudo Code
1. Load the words
2. Randomly Select a word
3. Save the word in a string: secretword
4. Ask the user to guess a letter from the 26 letters
5. Save the letter in string: guess
6. def check: See if the letter in variable guess is in secretword, return boolean
7. def show: If the guess letter is present in secretword, only show the letters in the string that has been guessed right. This should return all the letters with _ (for the one not yet guessed) and the guessed letters.
8. def available: Take out the correctly guessed letter from the alphabet, and show the ones remaining
9. Make a counter that only lasts up to 8 guesses, and do the following:
a) Start a for-loop for the counter of 8 guesses
b) Ask the user to guess a letter by calling the 3rd def available function
c) Check secretword; call def check
d) If you guessed the letter twice, print: Oops! You've already guessed that letter
e) If the letter not in secretword, print: Oops! That letter is not in my word
f) If it is correct, print: Good guess
g) All of the above, call def show so that the use can see what s/he has gotten right
"""
#Hope this helps
| true
|
8d631dfa7af78f6522855cc4914209c5009a8e79
|
EoinStankard/pands-problem-set
|
/ProblemFive-primes.py
| 2,097
| 4.3125
| 4
|
#Name: Eoin Stankard
#Date: 28/03/2019
#Problem Five: Write a program that asks the user to input a positive integer and tells the user
#whether or not the number is a prime.
value=input("Please enter a positive integer: ")
#This code will keep looping until the done variable is given 1. I used this as i will need to do multiple cycles
#through each if statement to determine if it is a prime or not
def printprimes(value):
#initial number the input value will be divided by
divisor = 1
#Count for how may numbers can divide into the input
divisorCount = 0
#Variable that determines when the program finishes
done =0
while done != 1:
#This will look for the modulus of the input value divided by the divisor, I used this as the input value will always be divided by one to start
#so this will always give a value equal to zero, I will then increment divisorCount as a prime number can only be divided by itself and one.
#This means that once it enters the first if statement it already has 1/2 numbers
#It will also increment the divisor. so the divisor will now go to 2
if value%divisor ==0 and divisorCount == 0:
divisorCount = divisorCount +1
divisor = divisor+1
elif divisorCount ==1 and divisor == value and value%divisor==0:
print("This is a prime")
done = 1
#If the divisorCount is equal to one and the value divided by the divisor equals zero and
#The divisor does not equal the input value then this number is not a prime
elif value%divisor == 0 and divisorCount ==1 and divisor != value:
print("This is not a prime")
done=1
#For any other scenario, increment the divisor by one
else:
divisor=divisor+1
try:
if int(value)>0:
printprimes(int(value))#Call the function created above to calculate the output values
elif int(value)<0:#if number is less than zero
raise ValueError #raise exception
except ValueError:
print("Incorrect Input Given")# incorrect input
| true
|
1e218f276764d53945e4a79b13bb35f615ca3ef8
|
Pnickolas1/Code-Reps
|
/AlgoExpert/Recursion/tail_call_optimization.py
| 1,254
| 4.125
| 4
|
"""
Tail Call optimization:
- tail call optimization is when the recursion call is the last thing in the function before it returns
- hence the name "the recursive function call comes at the "tail" of the function
- the call stack never grows in size
- TCO prevents stack overflows
- tail call optimzation is a compiler trick,
- Cpython interpreter does not implement TCO, and it never will
- its not pythonic
- TCO is not used in python , its irrelevent
- understand the call stack
- a function call pushes a frame onto the call stack and a return pops a stack off
leetcode def:
Tail recursion is a recursion where the recursive call is the final instruction in the recursion function.
And there should be only one recursive call in the function.
"""
def tail_call_optimizatin(n, accumulator=1):
if n == 0:
return accumulator
else:
return tail_call_optimizatin(n - 1, n * accumulator)
print(tail_call_optimizatin(5))
def sum_non_tail_recursion(ls):
if len(ls) == 0:
return 0
return ls[0] + sum_non_tail_recursion(ls[1:])
def sum_tail_recursion(ls):
def helper(ls, acc):
if len(ls) == 0:
return acc
return helper(ls[1:], ls[0] + acc)
return helper(ls, 0)
| true
|
172bb99cf56fb5c77537340a1e9a1b00c9d103ff
|
Pnickolas1/Code-Reps
|
/Arrays/even_odd.py
| 570
| 4.125
| 4
|
# when working with arrays, take advantage of the fact you operate on both ends
# efficiently
# given an array of ints, sort evens first then odds
x = [2, 3, 7, 5, 10, 14, 15, 22, 27, 31]
print(len(x))
def even_odd(arr):
next_even = 0
next_odd = len(arr) -1
while next_even < next_odd:
if arr[next_even] % 2 == 0:
next_even += 1
else:
arr[next_even], arr[next_odd] = arr[next_odd], arr[next_even]
next_odd -= 1
return arr
if __name__ == "__main__":
print(len(x))
print(even_odd(x))
| true
|
f8b8a4c36802b6beb3a27326e7d05b204351ac4e
|
Pnickolas1/Code-Reps
|
/Algorithms/Bottom_Up_Algorithm.py
| 1,047
| 4.3125
| 4
|
# Bottom up algorithms offer another option in solving a problem. Bottom up algorithms are often used instead of a
# recursive approach. While recursion offers highly readable, succinct code, it is succeptible to a high memory cost
# O(n) and could lead to a stack overflow.
# recursion starts from the "end and works it's way back" (hence the need for a base case)
# bottom up algorithms start from the bottom (or start) and work their way up
# going bottom up is a common strategy for dynamic programming
# dynamic programming are coding problems where the solution is composed of solutions to the same problem with
# smaller inputs
# the other common strategy is memoization
# recursive approach
def product_1_to_n(n):
# we assume n >= 1
return n * product_1_to_n(n - 1) if n > 1 else 1
# to avoid this we can use a bottom up approach
def product_1_to_n_bottom_up(n):
# we assume n >= 1
result = 1
for num in range(1, n + 1):
result *= num
print result
product_1_to_n(15)
product_1_to_n_bottom_up(15)
| true
|
eca7a7ce6540b3979f21670b0aad8b9f676c7f6e
|
Pnickolas1/Code-Reps
|
/EOPI/array/check_if_decimal_integer_is_palindrome.py
| 797
| 4.21875
| 4
|
import math
"""
checking if a integer is a palindrome can be 2 waysL
Optimal:
space: O(1)
time:: O(n)
1. way, reverse the integer, and then compare to the given parameter
2. iterate through through the param, popping off the most significant int, and the
least significant digit, comparing, if they dont match, return false,
if they do match, remove the most/least significant arg and continue
edge case, if the given arg is less than 0
"""
def is_number_palindrome(x):
if x < 0:
return False
num_digits = math.floor(math.log10(x)) + 1
msd_mask = 10**(num_digits - 1)
for i in range( num_digits // 2):
if x // msd_mask != x % 10:
return False
x %= msd_mask
x //= 10
msd_mask //= 100
return True
print(is_number_palindrome(1234321))
| true
|
c08f3c18300548d6b77bbeb80e667a031b411960
|
Nicoconte/Programacion-1
|
/practica_2/ejercicio_6.py
| 918
| 4.1875
| 4
|
import random
# 3 Listas: 1- La original / 2- Palabras a eliminar / 3- La resultante
def ingresar_palabras_a_eliminar():
palabras_a_eliminar = []
entrada = input(("Que palabras deseas eliminar "))
while(entrada != "listo"):
palabras_a_eliminar.append(entrada)
entrada = input(("Que palabras deseas eliminar "))
return palabras_a_eliminar
def eliminar_palabras(l1,l2):
lista_resultante = []
for i in l1:
if i not in l2:
lista_resultante.append(i)
return lista_resultante
def main():
lista_original_palabras = ['hola','chau','nicolas','adios','linkin park']
lista_de_palabras = ingresar_palabras_a_eliminar()
lista_resultante = eliminar_palabras(lista_original_palabras, lista_de_palabras)
print("Lista original => ", lista_original_palabras,"\n","Lista de palabras a eliminar => ", lista_de_palabras)
print("\n","Lista resultante => ", lista_resultante)
main()
| false
|
d04d1642831395c1f8bed417c1138b4d8c89f804
|
gunnsa/Git_place
|
/git-python/sequence.py
| 349
| 4.15625
| 4
|
n = int(input("Enter the length of the sequence: ")) # Do not change this line
sequence = 0
x1 = 1
x2 = 2
x3 = 3
if n > 0:
print(1)
if n > 1:
print(2)
if n > 2:
print(3)
if n > 3:
for x in range(0,n-3):
sequence = x1 + x2 + x3
print(sequence)
x1 = x2
x2 = x3
x3 = sequence
print(sequence)
| true
|
16c36a6e26395be7996359701bd6373fc3036de5
|
himanig/py-path
|
/createmodule_circle.py
| 237
| 4.25
| 4
|
#creating my own module
from math import pi
radius = input('Enter the radius of circle: ')
print(end='\n')
print('The area of the circle is= ', float(radius) ** 2 * pi)
print(end='\n')
print('The circumference is= ', float(radius) * pi)
| true
|
bf0b3dde8a51d60ca5326d99eb3b7217622e50d8
|
couple-star/python-study
|
/exercise/excercise22.py
| 201
| 4.5
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Write a function that takes a string as input and returns the string reversed.
string=raw_input('please in put one string: ')
a=string[::-1]
print a
| true
|
fff1490edf893397e742018cb3519a579f1c27e5
|
choutos/winterchallenge_2019
|
/day01/day01.py
| 2,342
| 4.5625
| 5
|
'''
Fuel required to launch a given module is based on its mass.
Specifically, to find the fuel required for a module, take its mass,
divide by three, round down, and subtract 2.
For example:
- For a mass of 12, divide by 3 and round down to get 4,
then subtract 2 to get 2.
- For a mass of 14, dividing by 3 and rounding down still yields 4,
so the fuel required is also 2.
- For a mass of 1969, the fuel required is 654.
- For a mass of 100756, the fuel required is 33583.
The Fuel Counter-Upper needs to know the total fuel requirement.
To find it, individually calculate the fuel needed for the mass of
each module (your puzzle input), then add together all the fuel values.
'''
def calc_fuel(mass: int) -> int:
return mass // 3 -2
assert calc_fuel(12) == 2
assert calc_fuel(14) == 2
assert calc_fuel(1969) == 654
assert calc_fuel(100756) == 33583
with open("input.txt") as f:
masses = [int(line.strip()) for line in f]
fuel_part1 = 0
for mass in masses:
fuel_part1 += calc_fuel(mass)
print(fuel_part1)
'''
For each module mass, calculate its fuel and add it to the total.
Then, treat the fuel amount you just calculated as the input mass
and repeat the process, continuing until a fuel requirement
is zero or negative. For example:
A module of mass 14 requires 2 fuel. This fuel requires no
further fuel (2 divided by 3 and rounded down is 0, which
would call for a negative fuel), so the total fuel
required is still just 2.
At first, a module of mass 1969 requires 654 fuel. Then, this
fuel requires 216 more fuel (654 / 3 - 2). 216 then requires
70 more fuel, which requires 21 fuel, which requires 5 fuel,
which requires no further fuel. So, the total fuel required
for a module of mass 1969 is 654 + 216 + 70 + 21 + 5 = 966.
The fuel required by a module of mass 100756 and its fuel is:
33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346.
'''
def calc_fuel2(mass: int) -> int:
total = 0
new_fuel = calc_fuel(mass)
while new_fuel > 0:
total += new_fuel
new_fuel = calc_fuel(new_fuel)
return total
assert calc_fuel2(14) == 2
assert calc_fuel2(1969) == 966
assert calc_fuel2(100756) == 50346
fuel_part2 = 0
for mass in masses:
fuel_part2 += calc_fuel2(mass)
print(fuel_part2)
| true
|
dcf62d8f75a28a3c6de9cbc8800003e632f7cfc8
|
NitinJRepo/Linear-Algebra
|
/01-creating_vector.py
| 628
| 4.34375
| 4
|
import numpy as np
# Create a vector as a row
vector_row = np.array([1, 2, 3, 4, 5])
print("row vector: ", vector_row)
# Create a vector as a column
vector_column = np.array([[1],
[2],
[3],
[4],
[5]])
print("column vector: ", vector_column)
# Selecting elements
print("Select third element of vector:")
print(vector_column[2])
print("Select all elements of a vector:")
print(vector_row[:])
print("Select everything up to and including the third element:")
print(vector_column[:3])
print("Select everything after the third element:")
print(vector_column[3:])
print("Select the last element:")
print(vector_column[-1])
| true
|
d503bc0ac71fde9f617d693e3842e1572041a94b
|
bigplik/Python
|
/lesson_nana/functions.py
| 683
| 4.1875
| 4
|
#functions
hours = 24
minutes = 24 * 60
seconds = 24 * 60 * 60
#calculation to units eg. to seconds, or hours
calculation_to_units = seconds
name_of_unit = "seconds"
'''
def day_to_units(days):
num_of_days = days
print(f"{num_of_days} days are {num_of_days * calculation_to_units} {name_of_unit}")
day_to_units(176900)
'''
#2nd eg. for function with parameters without defining extra variable like above
def day_to_units(num_days, custom_message):
print(f"{num_days} days are {num_days * calculation_to_units} {name_of_unit}")
print(custom_message)
day_to_units(104343, "custom_message")
# common practice!!!! not to make too many parameters eg.10, better is use about two
| true
|
3f09381843b9d724563344d5d36ceb7df27d177b
|
pndiwakar/python_hello_word
|
/radius.py
| 309
| 4.4375
| 4
|
#!bin/python
# Impoort the required module for getting maths function PI
from math import pi
#assign the input to variable
r = float(input("Input the radius of circle : "))
# To make it square of r either use "r * r" or "r**2"
print ("Areas of circle with radius={} is : {}" .format(r, str(pi * (r * r))))
| true
|
622beb7f9d24e18d9fd844c2c57ea3ef648f456a
|
marmst10/Python-Examples
|
/Basic Python Manipulations.py
| 1,832
| 4.125
| 4
|
#!/usr/bin/env python
# coding: utf-8
# STAT 7900 – Python for Data Science<br>
# Homework 3<br>
# Connor Armstrong<br>
# <br>
# 1. Create a CSV (Comma Separated Values) file from the data below (copy and paste the data into Excel then save as a csv) and read in as a Pandas Dataframe. Then do the following using Pandas operations that we covered in class (10 points): <br>
# In[5]:
import numpy as np
import pandas as pd
data = pd.read_csv('C:/Users/conno/OneDrive/Desktop/STAT 7900 - Python for Data Science/Homework/HW3 Data.csv')
# <br>
# a. What percent of records represent flowers? <br>
# The mean of the binary indicator variable is equivalent to the percentage of records which represent flowers. This parameter is calculated as follows:<br>
# In[4]:
percent_flowers = data['Flower'].mean()
percent_flowers
# Therefore, the percent of records which represent flowers is 45%.<br><br>
# b. What is the average Costs by Color?<br>
# In[24]:
costbycolor = pd.DataFrame(data['Cost'].groupby(data['Color']).mean())
costbycolor
# <br>c. Create a new column, that bins the Probability column into 4 equal frequency count bins (from low to high).<br>
# In[25]:
data['Bin'] = pd.qcut(data['Probability'], q=4)
data
# In[26]:
data['Bin'].value_counts()
# The column 'Bin' grouped the data into 4 equal frequency count bins as directed.<br><br>
# d. Create a crosstab of color and flower that represents the total cost.<br>
# In[31]:
pd.crosstab(data['Color'], data['Flower'], values=data['Cost'], aggfunc='sum', rownames=['Cost'], colnames=['Flower'])
# The dataframe above is a crosstab of color and flower which represents the total cost of each unique combination of the two.<br><br>
# e. Create a dataframe that contains flowers, only.<br>
# In[32]:
flowersonly = data[(data['Flower']== 1)]
flowersonly
| true
|
f321231eb06846b84c88bcfcc274a875bbc16b6f
|
joyadas1999/calculator
|
/calculator.py
| 1,650
| 4.40625
| 4
|
#this function is an example of addition
def calculator_addvalue(addvalue_x,addvalue_y):
calc_add = addvalue_x + addvalue_y
return calc_add
add_x = calculator_addvalue(100,30)
print(add_x)
#this function is an example of subtraction
def calculator_subtvalue(subtvalue_x,subtvalue_y):
calc_subt = subtvalue_x - subtvalue_y
return calc_subt
subt_x = calculator_subtvalue(148,24)
print(subt_x)
#this function is an example of multiplication
def calculator_multvalue(multvalue_x,multvalue_y):
calc_mult = multvalue_x * multvalue_y
return calc_mult
mult_x = calculator_multvalue(247,35)
print(mult_x)
#this function is an example of squaring two numbers
def calculator_squarevalue(squarevalue_x,squarevalue_y):
calc_square_1 = squarevalue_x * squarevalue_x
calc_square_2 = squarevalue_y * squarevalue_y
return calc_square_1, calc_square_2
square_x, square_y = calculator_squarevalue(8,9)
print("This prints the square of " +str(square_x))
print("This prints the square of " +str(square_y))
#this function does an example of division
def division(div1,div2):
calc_div = div1 / div2
return calc_div
print(division(20,5))
print(division(30,10))
#this function gets a remainder
def remainder (rem1,rem2):
calc_rem = rem1 % rem2
return calc_rem
print("The remainder is:" + str(remainder(9,8)))
print("The remainder is:" + str(remainder(18,43)))
#this function is testing to see if the math is done correctly
def correctcheck(math1):
if math1 == str(5+5):
return " You are correct"
if math1 == str(5):
return " You are wrong"
math1 = str(10)
math1 = str(5)
print(correctcheck(math1))
| true
|
378e26693bc0fb641470307d5e6ed10dd9e0fc06
|
BryJC/LPtHW
|
/40-49/ex42.py~
| 2,203
| 4.28125
| 4
|
## Animal is-a object (yes, sort of confusing) look at the extra credit
class Animal(object):
pass
## Dog is-a(n) animal
class Dog(Animal):
def __init__(self, name):
## class Dog has-a(n) attribute name set to name
self.name = name
## Cat is-a(n) animal
class Cat(Animal):
def __init__(self, name):
## class Cat has-a(n) attribute name set to name
self.name = name
## Person is-a(n) object
class Person(object):
def __init__(self, name):
## Person has-a(n) attribute name set to name
self.name = name
## Person has-a(n) attribute pet of some kind
self.pet = None
## Employee is-a Person
class Employee(Person):
def __init__(self, name, salary):
## class Employee has-a(n) attribute name set to name (from Person class) ??
super(Employee, self).__init__(name)
## class Employee has-a(n) attribute salary set to salary
self.salary = salary
## class Fish is-a(n) object
class Fish(object):
pass
## class Salmon is-a Fish
class Salmon(Fish):
pass
## class Halibut is-a Fish
class Halibut(Fish):
pass
## rover is-a Dog
rover = Dog("Rover")
## satan is-a Cat
## set satan equal to an instance of class Cat that takes self, "Satan" parameters
satan = Cat("Satan")
## Mary is-a Person
## set mary equal to an instance of class Person that takes self, "Mary" parameters
mary = Person("Mary")
## mary has-a satan
## from (instance of class Person:) mary, get the pet attribute and set it to satan
mary.pet = satan
## frank is-a Employee
## set frank equal to an instance of class Employee that takes self, "Frank", and 120000 arguments
frank = Employee("Frank", 120000)
## frank has-a rover
## from (instance of class Employee:) frank, get the pet attribute (from superclass Person) and set it to rover
frank.pet = rover
## flipper is-a Fish
## set flipper to an instance of class Fish that takes parameter self
flipper = Fish()
## crouse is-a Salmon
## set crouse equal to an instance of class Salmon that takes parameter self
crouse = Salmon()
## harry is-a Halibut
## set harry equal to an instance of class Halibut that takes parameter self
harry = Halibut()
| true
|
ee456ae55757848df8f2c3cf1007748b735e4011
|
maoa20-gm/Algoritmos
|
/aula_01/practica_01.py
| 2,645
| 4.25
| 4
|
'''
def hello():
print("Oi mundo!")
print("Oi de novo!")
hello()
def continha():
print(798 - 2 * 378)
continha()
def somaQuadrados(a,b):
return print(a*a + b*b)
somaQuadrados(5,7)
pergunta1 = "Qual é a Capital da Nicaragua? \n a) Atahualpa\n b) Managua \n c) San Jose \n d) Tegucigalpa"
def passoumedia(nota):
if nota >= 7.0:
return True
else:
return False
passoumedia(9)
'''
'''
def compararComprimentos():
x = input("Salude por favor: ")
y = input("Salude de nuevo: ")
if len(x) == len(y):
return True
else:
return False
'''
def somaDigitos():
x = input("Digite un numero de tres digitos: ")
total = 0
while len(x) != 3:
x = input("Digite por favor un numero de tres digitos: ")
z = int(x) # un integer
while (z>0):
restante = z%10
total = total + restante
z = z // 10
return print(total)
def ordemCrescente():
y = int(input("Digite un numero de tres digitos: "))
primer_numero = y%10
segundo_numero = (y//10)%10
restante = y//10
tercer_numero = (restante//10)%10
if (primer_numero > segundo_numero):
primer_numero = segundo_numero
segundo_numero = primer_numero
if (primer_numero > tercer_numero):
primer_numero = tercer_numero
tercer_numero = primer_numero
if (segundo_numero > tercer_numero):
segundo_numero = tercer_numero
tercer_numero = segundo_numero
return(print(primer_numero,segundo_numero,tercer_numero))
def is_numeric(numero):
try:
int(numero)
except ValueError:
return False
return True
def tipoParametro():
x = input("Digite solo un caracter: ")
if len(x) > 1:
x = input("Por favor digite solo un caracter, osea, un caracter de tamano 1: ")
if is_numeric(x) == False:
print(0)
elif is_numeric(x) == True:
print(1)
else:
print(-1)
def quatroNumeros():
x = input("Digite un numero de tres digitos: ")
y = input("Digite otro numero de tres digitos: ")
z = input("Digite otro numero de tres digitos: ")
m = input("Digite otro numero de tres digitos: ")
if len(x) != 3:
break
if len(y) != 3:
break
if len(z) != 3:
break
if len(m) != 3:
break
if x%3 == 0 and (x ** (1/2) == round(x ** (1/2))):
if (y%3 == 0) & (y ** (1/2) == round(y ** (1/2))):
if (z%3 == 0) & (z ** (1/2) == round(z ** (1/2))):
if (m%3 == 0) & (m ** (1/2) == round(m ** (1/2))):
| false
|
b2f460c60a956866ffabcf756b76f851db3e8f1c
|
kyunghwanleethebest/inflearn_leaf
|
/code/2_property.py
| 607
| 4.15625
| 4
|
# Underscore, Getter, Setter
class Example:
def __init__(self):
self.x = 0
self.__y =0 # private
self._z = 0 # protected
@property
def y(self):
print('Get Method')
return self.__y
@y.setter
def y(self, value):
print('Set Method')
if value < 1:
raise ValueError('양수를 입력하세요')
self.__y=value
@y.deleter
def y(self):
print('Del Method')
del self.__y
test = Example()
test.x = 0
test.y = 13
print(f'x instance is {test.x}')
print(f'y instance is {test.y}')
test.y = 0
| false
|
8fb7f09891f642640d0349410a84552fdb0a6098
|
balazsbarni/pallida-basic-exam-trial
|
/namefromemail/name_from_email.py
| 717
| 4.40625
| 4
|
# Create a function that takes email address as input in the following format:
# firstName.lastName@exam.com
# and returns a string that represents the user name in the following format:
# last_name first_name
# example: "elek.viz@exam.com" for this input the output should be: "Viz Elek"
# accents does not matter
#print(name_from_email("elek.viz@exam.com"))
email_adress = str(input("Please enter ypur e-mail adress: "))
def name_from_email(entered_email_adress):
forename =entered_email_adress[entered_email_adress.index(".") :entered_email_adress.index("@")]
name =entered_email_adress[:entered_email_adress.index(".")]
return forename[1].upper() +forename[2:] + " " + name[0].upper() +name[1:]
print(name_from_email(email_adress))
| true
|
fc5e75a3fb1934afea5063e0b3462ebd51452ae5
|
sidtandon2014/Algorithms
|
/Algos/Sorting/MergeSort.py
| 1,150
| 4.125
| 4
|
def mergeSort(arr, left, right):
middle = left + (right - left) // 2
if left < middle:
mergeSort(arr, left, middle)
if (middle + 1) < right:
mergeSort(arr, middle + 1, right)
merge(arr, left, middle, right)
def merge(arr, left, middle, right):
leftArrIndex = 0
rightArrIndex = 0
arrLeft = arr[left:middle + 1]
arrRight = arr[middle + 1: right + 1]
while True:
if (leftArrIndex < len(arrLeft)) & (rightArrIndex < len(arrRight)):
if arrLeft[leftArrIndex] >= arrRight[rightArrIndex]:
arr[left] = arrRight[rightArrIndex]
rightArrIndex += 1
else:
arr[left] = arrLeft[leftArrIndex]
leftArrIndex += 1
elif leftArrIndex < len(arrLeft):
arr[left] = arrLeft[leftArrIndex]
leftArrIndex += 1
elif rightArrIndex < len(arrRight):
arr[left] = arrRight[rightArrIndex]
rightArrIndex += 1
else:
break;
left += 1
if __name__ == '__main__':
arr = [2, 1, 3,-1, 0, 10, 56]
mergeSort(arr, 0, len(arr) - 1)
print(arr)
| false
|
15469c6b9eb1e92deadda1e6330bd8e0d54452ad
|
Shwibi/python-c11-stanselm
|
/marks.py
| 434
| 4.21875
| 4
|
# Practice: 18/8/2021
# Conditional Statements with calculation
# Program 1
physics = int(input("Enter marks in physics: "))
chemistry = int(input("Enter marks in chemistry: "))
biology = int(input("Enter marks in biology: "))
total = physics + chemistry + biology
percentage = total/3
print("Total marks: ", total)
print("Total percentage: ", percentage)
if percentage >= 40:
print("You passed")
else:
print("You failed")
| true
|
412fb126e7f325e85c8d67c1aefaac11f0e86655
|
Shwibi/python-c11-stanselm
|
/vote.py
| 201
| 4.21875
| 4
|
# Practice: 18/8/2021
# Conditional Statements, boolean
# Program 2
age = int(input("Enter age: "))
if age >= 18:
print("You are eligible to vote!")
else:
print("You are not eligible to vote!")
| true
|
2c1876b25ba61af9e861f01199b49637fcaf9592
|
Elmurat01/ThinkPython
|
/Think Python - Chapter 04/ThinkPython4_flowers.py
| 754
| 4.25
| 4
|
import turtle, math
bob = turtle.Turtle()
def arc(t, r, angle):
"""Draws an arc length angle from
a circle of radius r. t is a turtle.
"""
step = (2 * math.pi * r) / 360
for i in range(angle):
t.fd(step)
t.lt(1)
def flower(t, no_petals, len_petals, angle):
"""Draws a flower-shaped pattern with
the number of petals specified in no_petals.
angle designates the width of the petal.
The length of the petal is determined by angle and
len_petals. t is a turtle.
"""
for i in range(no_petals):
for i in range(2):
arc(t, len_petals, angle)
t.lt(180 - angle)
t.lt(360/no_petals)
flower(bob, 20, 300, 45)
turtle.mainloop()
| true
|
c7d44451340d31439de7278b1e802ab76a8e23a6
|
Elmurat01/ThinkPython
|
/Think Python - Chapter 15/draw_circle.py
| 963
| 4.3125
| 4
|
import turtle, math
bob = turtle.Turtle()
class Point:
"""Represents a point in 2-D space."""
class Circle:
"""
Represents a circle.
Attributes: radius, center
"""
def draw_circle(t, circle, color = "black"):
"""
Takes a Circle object and a Turtle object
and draws a circle.
arguments:
t: Turtle object
circle: Circle object
color: optional color of the Turtle pen.
Default is black.
"""
t.penup()
t.fd(circle.center.x)
t.lt(90)
t.fd(circle.center.y + circle.radius)
t.rt(90)
t.pendown()
step = (math.pi * 2 * circle.radius)/360
for i in range(360):
t.pencolor(color)
t.fd(step)
t.rt(1)
roundy = Circle()
roundy.radius = 75
roundy.center = Point()
roundy.center.x = 150.0
roundy.center.y = 100.0
draw_circle(bob, roundy, color = "red")
turtle.mainloop()
| true
|
d289e8f42445a154370d8355a81f7171eb7a7dcd
|
alexagrchkva/for_reference
|
/theory/5th_sprint/unittest_task.py
| 1,593
| 4.15625
| 4
|
import unittest
class Calculator:
"""Производит различные арифметические действия."""
def divider(self, num1, num2):
"""Возвращает результат деления num1 / num2."""
return num1/num2
def summ(self, *args):
"""Возвращает сумму принятых аргументов."""
if len(args) <2:
return None
sum = 0
for i in args:
sum += i
return sum
class TestCalc(unittest.TestCase):
"""Тестируем Calculator."""
# Подготовьте данные для теста
@classmethod
def setUpClass(cls) -> None:
cls.calc = Calculator()
def test_divider(self):
act = TestCalc.calc.divider(8,4) # вызовите метод divider с аргументом
self.assertEqual(act, 2, 'текст, если проверка провалена')
def test_divider_zero_division(self):
with self.assertRaises(ZeroDivisionError):
TestCalc.calc.divider(8, 0)
def test_summ(self):
act = TestCalc.calc.summ(3, -3, 5)
self.assertEqual(act, 5, 'summ работает неправильно')
def test_summ_no_argument(self):
act = TestCalc.calc.summ()
self.assertIsNone(act, 'None не возращает, если аргументов нет')
def test_summ_one_argument(self):
act = TestCalc.calc.summ(5)
self.assertIsNone(act, 'None не возращает, если аргумент один')
| false
|
a84d8f35a45c7b9fe1b1c9706efc981a71b37f4e
|
annamariamistrafovic1994/SN-WD1-Lesson8
|
/mood_checker.py
| 515
| 4.1875
| 4
|
x = input("What mood are you in? ")
print(x)
operation = input("Choose one of the given solutions (happy, sad, relaxed, nervous, excited): ")
print(operation)
if operation == "happy":
print("It is great to see you happy!")
elif operation == "sad":
print("Cheer up!")
elif operation == "relaxed":
print("Stay in ZEN.")
elif operation == "nervous":
print("Take a deep breath 3 times.")
elif operation == "excited":
print("Keep the adrenaline up!")
else:
print("I don't recognize this mood.")
| true
|
3842011e556e7e0708ec652718d1daa099d7cade
|
mlr0929/FluentPython
|
/05FirstClassFunctions/any_and_all.py
| 707
| 4.21875
| 4
|
"""
all(iterable)
Return True if every element of the iterable is truthy; all([]) returns True
>>> all([0, 1, 3])
False
>>> all([1, 1, 3])
True
>>> all([])
True
# Equivalent to
>>> def all(iterable):
... for element in iterable:
... if not element:
... return False
... return True
any(iterable)
Return True if any element of the iterable is true. If the iterable is empty, return False
>>> any([0, 0, 1])
True
>>> any([0, 0, 0])
False
>>> any([])
False
# Equivalent to
>>> def any(iterable):
... for element in iterable:
... if not element:
... return True
... return False
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
| true
|
e42da9aa532f1dd148ea2f000846a3bace45eb24
|
sandyg05/cs
|
/[Course] Python for Everybody - University of Michigan/Course 2 - Python Data Structures/Chapter 6 - Strings.py
| 1,548
| 4.625
| 5
|
# Chapter 6 - Strings Quiz
# 1.
# What does the following Python Program print out?
str1 = "Hello"
str2 = 'there'
bob = str1 + str2
print(bob)
# Hellothere
# 2.
# What does the following Python program print out?
x = '40'
y = int(x) + 2
print(y)
# 42
# 3.
# How would you use the index operator [] to print out the letter q from the following string?
x = 'From marquard@uct.ac.za'
# print(x[8])
# 4.
# How would you use string slicing [:] to print out 'uct' from the following string?
x = 'From marquard@uct.ac.za'
# print(x[14:17])
# 5.
# What is the iteration variable in the following Python code?
for letter in 'banana' :
print(letter)
# letter
# 6.
# What does the following Python code print out?
print(len('banana')*7)
# 42
# 7.
# How would you print out the following variable in all upper case in Python?
greet = 'Hello Bob'
# print(greet.upper())
# 8.
# Which of the following is not a valid string method in Python?
# shout()
# 9.
# What will the following Python code print out?
data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
pos = data.find('.')
print(data[pos:pos+3])
# .ma
# 10.
# Which of the following string methods removes whitespace from both the beginning and end of a string?
# strip()
# ----------------------------------------------------------------------------------------------------------------------
# Chapter 6 - Strings Assignments
# Assignment 6.5
text = "X-DSPAM-Confidence: 0.8475"
colon_position = text.find(':')
num = text[colon_position + 1:].strip()
print(float(num))
| true
|
c19dba940010c1d12eaab21bfe06e2479fcfe3ca
|
sandyg05/cs
|
/[Course] Python for Everybody - University of Michigan/Course 1 - Programming for Everybody (Getting Started with Python)/Chapter 1 - Why We Program.py
| 1,341
| 4.34375
| 4
|
# Chapter 1 - Why We Program Quiz
# 1.
# When Python is running in the interactive mode and displaying the chevron prompt (>>>)
# what question is Python asking you?
# What would you like to do?
# 2.
# What will the following program print out:
x = 15
x = x + 5
print(x)
# 20
# 3.
# Python scripts (files) have names that end with:
# .py
# 4.
# Which of these words are reserved words in Python ?
# if
# break
# 5.
# What is the proper way to say “good-bye” to Python?
# quit()
# 6.
# Which of the parts of a computer actually executes the program instructions?
# Central Processing Unit
# 7.
# What is "code" in the context of this course?
# A sequence of instructions in a programming language
# 8.
# A USB memory stick is an example of which of the following components of computer
# architecture?
# Secondary Memory
# 9.
# What is the best way to think about a "Syntax Error" while programming?
# The computer did not understand the statement that you entered
# 10.
# Which of the following is not one of the programming patterns covered in Chapter 1?
# Random steps
# ----------------------------------------------------------------------------------------------------------------------
# Chapter 1 - Why We Program Assignments
# Assignment Write Hello World
print("Hello, World!")
| true
|
0db347081d9257b3b7fd0f8baeda34b5bf7e4b86
|
Tclack88/Scientific-Computing-Projects
|
/Basic/SineSeriesApprox.py
| 1,833
| 4.28125
| 4
|
#!/usr/bin/python3
import math
pi = 3.1415926535897932384626433832795028841971
def factorial(n):
num = 1
for i in range (1,n+1):
num *= i
return num
# we are not allowed to import functions like
# factorial or pi, so I have to define them here
# Self explanatory definition I'd say
angle= input("Give me an angle (in degrees): ")
# Couldn't figure out how to make sure this is
# either a float or integer... sorry
angle = float(angle)*pi/180
numterms = input("How many terms do you want? ")
while numterms.isdigit() is False or int(numterms)>=25:
numterms = input("Don't be ridiculous. Only integers allowed" \
" below 25, try again: ")
numterms = int(numterms)
# The first while loop ensures only integer inputs are
# accepted, the second keeps it below 25. Finally I
# turn the string input into an integer
def sind(angle,numterms):
total = 0
for i in range(1,numterms+1):
n = ((-1)**(i-1))*((angle)**(2*i-1))/factorial((2*i-1))
total += n
return total
# This is just the definition of sine as a taylor
# expansion. Since we are adding terms up to a
# specified input, the "for i in range" works perfectly
#
# Note: initially I tried doing this as an array, but
# my factorial definition only acts on single inputs
# I'm not sure how to make it operate on arrays, so I
# had to change to a range function
sind = sind(angle,numterms)
sin = math.sin(angle)
# assign these variable names to the corresponding
# functions for simplicity
print ("\nHere is sind():\n",sind)
print ("\nHere is the math module's sine:\n",sin)
print("\nTo compare:\n\n The absolute difference is:\n", \
math.sqrt((sin-sind)**2), \
"\n\nThe ratio is:(sind to sine)\n",sind/sin)
| true
|
1c34a6302c82676ed500cd9407c39c944b6a1d0d
|
Tclack88/Scientific-Computing-Projects
|
/Basic/InfoAssist.py
| 2,868
| 4.46875
| 4
|
#!/usr/bin/python3
# The purpose of this program is to take info from a .csv file (csv.csv... very creative name)
# and automate the process of finding specific information:
import csv
with open('csv.csv') as f:
readCSV = csv.reader(f, delimiter=',')
# "with open(file) as f" automatically closes after
# the operation is complete. rename to f for ease
# of typing. csv.reader returns an object in the file
# (separated by commas)
people = []
# create a blank list to while I will append dictionaries
for person in readCSV:
people.append({'last':person[0],'first':person[1],'color':person[2], \
'food':person[3],'field':person[4],'physicist':person[5]})
# Creates a dictionary for each row in the file
print("I have information here about a bunch of people:\n")
response = 'y'
while response == 'y':
print(list(people[0].keys()))
choice = input("What would you like to know about? ")
print()
# This while loop sets up the requirement to
# continue to prompt the user for keys
people_sort = []
for person in people:
item =(person['last']+", "+person['first']+": "+person[choice])
people_sort.append(item)
people_sort = sorted(people_sort)
# blank list people_sort is for the alphabetizing
# of the output. The key choice is will put the
# string "Last, first: key" for each row and store
# that into the blank list which is default sorted
# alphabetically
for i in people_sort:
print(i)
print()
# Here we print the already sorted list
response = input("Would you like to know more? <y,n> ")
if response == 'n':
break
while response != 'n' and response !='y':
print("That's not a valid response, try again")
response = input("Would you like to know more? <y,n> ")
# Here is where the user is prompted if they'd
# like to continue. I do a few short while loops
# to ensure only "y" or "n" is input
""" THE FOLLOWING DOES PART OF THE TASK, BUT DOESN'T USE
THE DICTIONARY AS REQUESTED... I'M KEEPING IT HERE
BECAUSE I'M PROUD OF IT AND MAY WANT TO REFER BACK
TO IT LATER
import csv
with open('csv.csv') as f:
readCSV = csv.reader(f, delimiter=',')
print("I have here a list of people, their first names, last names, \
favorite color, food, field of physics and physicist.\n")
choice = input ("Which would you like to know? last, first, color, \
food, field.\n (type one):")
last = []
first = []
color = []
food = []
field = []
physicist = []
for row in readCSV:
last = row[0]
first = row[1]
color = row[2]
food = row[3]
field = row[4]
physicist = row[5]
print(last+","+first+":"+choice)
"""
| true
|
3caa0f0153dbd76fd844262a24d75e3b851d28b2
|
Tclack88/Scientific-Computing-Projects
|
/Intermediate/lorenz_attractor.py
| 1,269
| 4.1875
| 4
|
#!/usr/bin/env python3
# plot of a lorentz attractor as apart of a solution to a nonlinear dynamics problem
# strogatz
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def lorenz(x,y,z,r, a=10, b=8/3):
x_dot = a*(y-x)
y_dot = r*x-y-x*z
z_dot = x*y-b*z
return x_dot, y_dot, z_dot
# Setup step size, number of iterations, and initial values. Make 3 separate
# lists for the x,y and z values. First entry is the initial values
# NOTE: with a stepsize of .01, there needs to be 5000 steps to get to t = 50
dt = 0.01
N = 5000
r = 24.5
xvals=[0]
yvals=[10]
zvals=[13]
# By derivative definition: x(t) = x(t-1) + x_dot * dt
# Use for loop to append to lists
for i in range(1,N):
x_dot, y_dot, z_dot = lorenz(xvals[i-1], yvals[i-1], zvals[i-1], r)
xvals.append(xvals[i-1] + x_dot * dt)
yvals.append(yvals[i-1] + y_dot * dt)
zvals.append(zvals[i-1] + z_dot * dt)
# Convert lists into arrays for ease of plotting
xvals = np.asarray(xvals)
yvals = np.asarray(yvals)
zvals = np.asarray(zvals)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(xvals, yvals, zvals, linewidth=0.5)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.set_title("Lorenz Equations Strogatz 9.3.4 for r = 24.5")
plt.show()
| true
|
04cdb0bfddf2670ad3f4cc7de8f4bb849bdbcdf6
|
JunWonOh/Multimodal-Calculator
|
/Multi-modal Calculator/Calculator_Module/Calculator_Presentation.py
| 2,583
| 4.15625
| 4
|
from tkinter import *
import tkinter.font as font
from Calculator_Module import Calculator_Control
# initialize the root
root = Tk()
# title of the window
root.title("CSI 407 Project")
# color of the window
root.configure(bg="#606060")
# disable resizing
root.resizable(False, False)
# the font of the buttons
myFont = font.Font(size=15, family="Ubuntu")
# The font of the text box
myFont2 = font.Font(size=25, family="Ubuntu")
# the text box
e = Entry(root, width=26, borderwidth=2, font=myFont2)
# at max, there can be 4 columns in the grid
e.grid(row=0, column=0, columnspan=4)
# asks user if they want to enter voice mode on init.
Calculator_Control.access_initial_prompt()
# behaves like EXIT_ON_CLOSE functionality on java swing, which is often included in Presentation
def close_window_click():
print('Quitting Program..')
root.quit()
root.destroy()
class Presentation:
cc = Calculator_Control.access_input_controller()
cc_fc = Calculator_Control.access_function_control()
# buttons arranged by rows and columns. get button functions are called to retrieve them
# from different modules
cc_fc.get_button_clear(e, root, myFont).grid(row=6, column=0)
cc.get_button_0(e, root, myFont).grid(row=6, column=1)
cc_fc.get_button_equals(e, root, myFont).grid(row=6, column=2, columnspan=2)
cc.get_button_1(e, root, myFont).grid(row=5, column=0)
cc.get_button_2(e, root, myFont).grid(row=5, column=1)
cc.get_button_3(e, root, myFont).grid(row=5, column=2)
cc.get_button_plus(e, root, myFont).grid(row=5, column=3)
cc.get_button_4(e, root, myFont).grid(row=4, column=0)
cc.get_button_5(e, root, myFont).grid(row=4, column=1)
cc.get_button_6(e, root, myFont).grid(row=4, column=2)
cc.get_button_minus(e, root, myFont).grid(row=4, column=3)
cc.get_button_7(e, root, myFont).grid(row=3, column=0)
cc.get_button_8(e, root, myFont).grid(row=3, column=1)
cc.get_button_9(e, root, myFont).grid(row=3, column=2)
cc.get_button_mult(e, root, myFont).grid(row=3, column=3)
cc.get_button_open_br(e, root, myFont).grid(row=2, column=0)
cc.get_button_close_br(e, root, myFont).grid(row=2, column=1)
cc.get_button_expo(e, root, myFont).grid(row=2, column=2)
cc_fc.get_button_delete(e, root, myFont).grid(row=2, column=3)
# formats voice button
Calculator_Control.access_voice_button(e, root, myFont).grid(row=1, column=0, columnspan=2)
# gives additional functionality to close button
root.wm_protocol("WM_DELETE_WINDOW", close_window_click)
root.mainloop()
| true
|
b77691eea281865c3cc1aaeea025a4ed1a3cb07f
|
koolhussain/Python-Basics
|
/19.Dictionary.py
| 379
| 4.125
| 4
|
exDict = {'Jack':[75,'White'],'Bob':[22,'brown'],'Ahmad':[23,'Blue'],'Kevin':[17,'Black']}
print(exDict)
print(exDict['Jack'])
#Adding New Key-value pair
exDict['Tim'] = 54
print(exDict)
#Modifiy Old Key-Value pair
exDict['Tim'] = 15
print(exDict)
#Deleteing a Key-Value Pair
del exDict['Tim']
print(exDict)
#REfernceing values of a key with a list
print(exDict['Jack'][1])
| false
|
d8a1213f4366ecd4985389b1e81d60bba23e893c
|
SMGuellord/Algorithms-and-data-structures-using-Python
|
/queue/QueueWithSinglyLinkedList.py
| 1,751
| 4.21875
| 4
|
class Node(object):
def __init__(self, data):
self.data = data
self.next_node = None
class Queue(object):
def __init__(self):
self.head = None
self.size = 0
def enqueue(self, data):
self.size += 1
new_node = Node(data)
if not self.head:
self.head = new_node
else:
new_node.next_node = self.head
self.head = new_node
def dequeue(self):
if not self.head:
return
else:
current = self.head
previous = None
while current.next_node is not None:
previous = current
current = current.next_node
self.size -= 1
data = current.data
previous.next_node = None
return data
def peek(self):
if not self.head:
return
else:
current = self.head
while current.next_node is not None:
current = current.next_node
return current.data
def traverse_list(self):
if not self.head:
return
else:
current_node = self.head
while current_node is not None:
print(" %d" % current_node.data)
current_node = current_node.next_node
def queue_size(self):
return self.size
queue = Queue()
queue.enqueue(20)
queue.enqueue(30)
queue.enqueue(40)
print("Queue size", queue.queue_size())
queue.traverse_list()
print("Peeked: ", queue.peek())
print("Queue size", queue.queue_size())
queue.traverse_list()
print("Dequeued:", queue.dequeue())
print("Dequeued:", queue.dequeue())
print("Queue size", queue.queue_size())
queue.traverse_list()
| true
|
1831235ebe9dee4c75bccff6f62ad2afd8b3e8c4
|
Tanyaregan/daily_coding
|
/daily_1_13.py
| 1,093
| 4.40625
| 4
|
# Given an array of integers, find the first missing positive integer
# in linear time and constant space.
# In other words, find the lowest positive integer that does not exist in the array.
# The array can contain duplicates and negative numbers as well.
# For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
# You can modify the input array in-place.
def missing_int(array):
"""Given an array of integers, find the lowest positive int that
does not exist in the array.
>>> missing_int([3, 4, -1, 1])
2
>>> missing_int([1, 2, 0])
3
"""
positive_nums = [num for num in array if num > 0]
positive_nums.sort()
pos_num = 1
for num in positive_nums:
if num != pos_num:
return pos_num
else:
pos_num += 1
return pos_num
#######################################################
if __name__ == "__main__":
import doctest
print
result = doctest.testmod()
if not result.failed:
print "All tests passed, you super-genius, you."
print
| true
|
851c2de55b7ddbc0166c6a4c374a8cb1f7c72e9c
|
azizamukhamedova/Python-Thunder
|
/ArrangementOfLetters.py
| 588
| 4.21875
| 4
|
'''
Backtracking is a form of recursion. But it involves choosing only option out of any possiblities.
######################## Arrangemt Of Letter Problem ##########################
###### Python ######
'''
def arrangement(num,s):
if num == 1:
return s
else:
return [
y + x
for y in arrangement(1,s)
for x in arrangement(num-1,s)
]
letter = ['1','2', '3']
print(arrangement(2,letter))
| true
|
19e65fde298f1f827b77865f5c49af233991cbe6
|
acneuromancer/algorithms-datastructures
|
/Python/most_frequent.py
| 421
| 4.15625
| 4
|
"""
Given an array find out what the most frequent element is.
"""
def most_frequent(a_list):
count = {}
max_val = 0
max_key = None
for key in a_list:
count[key] = 1 if key not in count else count[key] + 1
if count[key] > max_val:
max_key = key
max_val = count[key]
return max_key
print(most_frequent([5, 0, 5, 1, 1, 5, -1, 5, 2, 3, 4]));
| true
|
efc4ced43468dfe6429a96611e65d57437690c31
|
Eastwu5788/LeetCode
|
/48.py
| 1,361
| 4.21875
| 4
|
# !/usr/local/python/bin/python
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <wudong@eastwu.cn>'
# @Time: '2020-06-19 13:36'
"""
给定一个 n × n 的二维矩阵表示一个图像。
将图像顺时针旋转 90 度。
说明:
你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
示例 1:
给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
"""
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for row in range(0, n // 2 + n % 2):
for col in range(0, n // 2):
tmp = list()
i, j = row, col
for _ in range(0, 4):
tmp.append(matrix[i][j])
i, j = j, n - i - 1 # 核心技术
for k in range(0, 4):
matrix[i][j] = tmp[(k - 1) % 4]
i, j = j, n - i - 1
return
if __name__ == "__main__":
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Solution().rotate(matrix)
print(matrix)
| false
|
f251c542e7dd581c3223c2718352287820910ce5
|
mauriciosierrac/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/3-say_my_name.py
| 458
| 4.4375
| 4
|
#!/usr/bin/python3
''' That Function print the first and last name'''
def say_my_name(first_name, last_name=""):
'''
funcion say my name
Return: print the first and last name
'''
if type(first_name) is not str:
raise TypeError ('first_name must be a string')
if type(last_name) is not str:
raise TypeError ('last_name must be a string')
print('My name is {} {}'.format(first_name, last_name))
| true
|
06b4012fc2db5a8d35e1a4b48bfe5354ea26401f
|
carolinegbowski/exercises_day_1
|
/05_iteration_4.py
| 1,080
| 4.125
| 4
|
this_list = [1, 2, ['jeff', 'tom'], [42, ['billy', 'jason']]]
def crack_this_list(any_list):
for i in any_list:
if type(i) is list:
for j in i:
if type(j) is list:
for k in j:
if type(k) is list:
for l in k:
print(l)
else:
print(k)
else:
print(j)
else:
print(i)
crack_this_list(this_list)
# while True: ???????
# if i in any_list is list:
# for j in i:
# print(j)
# else:
# print(i)
# can't you do a while loop to see while NOT list, print i, but if list, print each item of list?
# can do recursively or with a stack
# recursive -- function that calls itslef (breaks into smaller units and calls on itself)
def unspool_list(item):
if type(item) != list:
return str(item)
return "\n".join(unspool_list(element) for element in item)
# call join here
| false
|
5987f01590742617c2aaa36c27ad7def84d98967
|
ashokjain001/Coding_Practice
|
/problem-Solving/capitalization.py
| 332
| 4.3125
| 4
|
#write a function that accepts a string. The function should
#capitalize the first letter of each word in the string then
#return the capitalized string.
def capitalization(string):
array=string.split()
newstr=''
for i in array:
newstr=newstr+' '+i[0].upper()+i[1:]
return newstr
print capitalization('a short sentence')
| true
|
59af5c806732b7c23220593ad053287590f012b2
|
johnerick-py/microsoft-python
|
/microsoftExercicios/python-lists/challenge1.py
| 1,208
| 4.125
| 4
|
import random
suits = ["Hearts", "Spades", "Clubs", "Diamonds"]
ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]
cards = []
baralho = []
count = 0
for suit in suits:
for rank in ranks:
cards = rank + ' of ' + suit
baralho.append(cards)
random.shuffle(baralho)
print(f'There are {len(baralho)} cards in the deck.')
print('Dealing...')
hand = random.choices(baralho, k=6)
while count < 5:
count = count + 1
del baralho[0]
print(f'There are {len(baralho)} cards in the deck.')
print('Player has the following cards in their hand:')
print(hand)
# Gabarito
# import random
#
# suits = ["Hearts", "Spades", "Clubs", "Diamonds"]
# ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]
# deck = []
#
# for suit in suits:
# for rank in ranks:
# deck.append(f'{rank} of {suit}')
#
# print(f'There are {len(deck)} cards in the deck.')
#
# print('Dealing ...')
#
# hand = []
#
# while len(hand) < 5:
# card = random.choice(deck)
# deck.remove(card)
# hand.append(card)
#
# print(f'There are {len(deck)} cards in the deck.')
# print('Player has the following cards in their hand:')
# print(hand)
| false
|
19d20dff0e99e6c54e024fbee301b8dc95ae8dbd
|
karakose77/udacity-cs101-intro-to-computer-science-exercises-and-projects
|
/mk005-is_symmetric.py
| 510
| 4.46875
| 4
|
# A list is symmetric if the first row is the same as the first column,
# the second row is the same as the second column and so on. Write a
# procedure, symmetric, which takes a list as input, and returns the
# boolean True if the list is symmetric and False if it is not.
def is_symmetric(L):
"""
Returns True if given list is symmetric.
"""
result = len(L) == len(L[0])
for i in range(len(L)):
for j in range(len(L)):
result *= L[i][j] == L[j][i]
return result
| true
|
296530e3cb3d06b42ff811d9c10ed8c82e6f6723
|
karakose77/udacity-cs101-intro-to-computer-science-exercises-and-projects
|
/mk009-is_palindrome_recursive.py
| 343
| 4.34375
| 4
|
# Define a procedure, that takes as input a string, and returns a
# Boolean indicating if the input string is a palindrome.
def is_palindrome_recursive(s):
"""
Returns true if input string is a palindrome.
"""
if len(s) == 0 or len(s) == 1:
return True
return (s[0] == s[-1]) and is_palindrome_recursive(s[1:-1])
| true
|
6e8dd58f96b1748825260c3a3d8cedf1f62b2637
|
jzarazua505/the_matrix
|
/property.py
| 794
| 4.125
| 4
|
width = 5
height = 2
# This is where we calculate perimeter
perimeter = 2 * (width + height)
# This is where we calculate area
area = width * height
print("Perimeter is " + str(perimeter) + " and Area is " + str(area) + "!")
print(f"Perimeter is {perimeter} and Area is {area}!")
print(f"Area: {area}")
# f(x) = y = 2x + 4
# f(input) = 2 * (input) + 4 = output
def f(x):
return 2 * x + 4
y = f(6)
print(y)
def get_area(width, height):
return width * height
print()
area1 = get_area(5, 2)
print(f"Area 1: {area1}")
area2 = get_area(7, 8)
print(f"Area 2: {area2}")
print()
test = "julian"
def print_words():
print("words")
print("stuff")
print("thing")
return "test"
test = print_words()
print(test)
other = print_words()
print_words()
print_words()
print_words()
| true
|
94dd05b8a2370ab85db2412e2be93872d0fbce05
|
2281/unittest
|
/unittest/radius.py
| 494
| 4.15625
| 4
|
from math import pi
def circle_area(radius):
if radius < 0:
raise ValueError("Radius can't be negative")
if type(radius) not in [int, float]:
raise TypeError("Type is not int or float")
return pi*radius**2
#print(circle_area(-5))
# r_list = [1,0,-1,2+3j, True, [2], "seven"]
# message = "Площадь окружности с радиусом {radius} --> {area}"
#
# for r in r_list:
# s = circle_area(r)
# print(message.format(radius = r, area = s))
| true
|
75bafe1ecce74af6b790cc77007c9e184ae912be
|
Annapooraniqxf2/read-write-python-program
|
/finish-the-program/p008_finish.py
| 447
| 4.15625
| 4
|
# Python program to find the
# sum of all digits of a number
# function definition
def sumDigits(<Finish the line>):
if num == 0:
return 0
else:
return num % 10 + sumDigits(int(num / 10))
# main code
x = 0
print("Number: ", x)
print("Sum of digits: ", sumDigits(x))
print()
x = 12345
print("Number: ", x)
print("Sum of digits: ", sumDigits(x))
print()
x = 5678379
print("Number: ", x)
print("Sum of digits: ", sumDigits(x))
print()
| true
|
2882485852aa333e90ae5a1677a967305918dceb
|
Annapooraniqxf2/read-write-python-program
|
/finish-the-program/p001_finish.py
| 305
| 4.21875
| 4
|
"""
Input age of the person and check whether a person is eligible for voting or not in Python.
"""
# input age
age = int(input("Enter Age : "))
# condition to check voting eligibility
<Fill the line>
status="Eligible"
<Fill the line>
status="Not Eligible"
print("You are ",status," for Vote.")
| true
|
e59f0cb7158c7181f7b6a538e1f3386b3dd52767
|
KhauTu/KhauTu-Think_Python
|
/Chap15_5.py
| 880
| 4.1875
| 4
|
from math import sqrt
class Point:
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
class Circle:
def __init__(self, a, b, c):
# line between a and b: s1 + k * d1
s1 = Point((a.x + b.x)/2.0, (a.y + b.y)/2.0)
d1 = Point(b.y - a.y, a.x - b.x)
# line between a and c: s2 + k * d2
s2 = Point((a.x + c.x)/2.0, (a.y + c.y)/2.0)
d2 = Point(c.y - a.y, a.x - c.x)
# intersection of both lines:
# s1 + k * d1 == s2 + l * d2
l = d1.x * (s2.y - s1.y) - d1.y * (s2.x - s1.x)
l = l / (d2.x * d1.y - d2.y * d1.x)
self.center = Point(s2.x + l * d2.x, s2.y + l * d2.y)
dx = self.center.x - a.x
dy = self.center.y - a.y
self.radius = sqrt(dx * dx + dy * dy)
def __repr__(self):
return "Center: (%.2f, %.2f), Radius: %.2f" % (self.center.x, self.center.y, self.radius)
a = Point(9, 3)
b = Point(8, 6)
c = Point(0, 0)
print(Circle(a, b, c))
| false
|
f31ac167f2e8d70f19e58355b919395abaf878ea
|
Allegheny-Computer-Science-102-F2020/cs102-F2020-challenge2-starter
|
/iterator/iterator/iterate.py
| 1,166
| 4.53125
| 5
|
"""Calculate the powers of two, with iteration, from minimum to maximum values."""
# TODO: Add the required import statements for List and Tuple
def calculate_powers_of_two_for_loop(
minimum: int, maximum: int
) -> List[Tuple[int, int]]:
"""Calculate and return the powers of 2 from an inclusive minimum to an exclusive maximum."""
powers_list = []
# iterate through a sequence of numbers that range from
# the minimum (inclusive) to the maximum (exclusive)
for i in range(minimum, maximum):
# TODO: save a two-tuple of the form (i, 2**i)
# return the list of the tuples of the powers
return powers_list
def calculate_powers_of_two_while_loop(
minimum: int, maximum: int
) -> List[Tuple[int, int]]:
"""Calculate and return the powers of 2 from an inclusive minimum to an exclusive maximum."""
powers_list = []
i = minimum
# iterate through a sequence of numbers that range from
# the minimum (inclusive) to the maximum (exclusive)
while i < maximum:
# TODO: save a two-tuple of the form (i, 2**i)
i += 1
# return the list of the tuples of the powers
return powers_list
| true
|
2ca165947c741d4c65a75f3df950a38fa39a04bd
|
JosiahMc/python_stack
|
/python_fundamentals/coin_tosses.py
| 1,630
| 4.375
| 4
|
# Assignment: Coin Tosses
# Write a function that simulates tossing a coin 5,000 times. Your function should
# print how many times the head/tail appears.
# # Sample output should be like the following:
# # Starting the program...
# Attempt #1: Thro1 head(s) so far and 0 tail(s) so far
# Attempt #2: Throwing a coin... It's a head! ... Got 2 head(s) so far and 0 tail(s) so far
# Attempt #3: Throwing a coin... It's a tail! ... Got 2 head(s) so far and 1 tail(s) so far
# Attempt #4: Throwing a coin... It's a head! ... Got 3 head(s) so far and 1 tail(s) so far
# ...
# Attempt #5000: Throwing a coin... It's a head! ... Got 2412 head(s) so far and 2588 tail(s) so far
# Ending the program, thank you!
# Hint: Use the python built-in round function to convert that floating point number into an integer
import random
def heads_tails ():
heads_so_far = 0
tails_so_far = 0
attempts_so_far = 0
print "Starting the program..."
for i in range (0,5000):
attempts_so_far = attempts_so_far + 1
coin_toss = random.randint (1,2)
if coin_toss % 2 == 0:
heads_so_far = heads_so_far + 1
print "Attempt #" + str(attempts_so_far) + " Throwing a coin... It's a head!... Got " + str(heads_so_far) + "head(s) so far and " + str(tails_so_far) + " tails so far"
elif coin_toss % 2 == 1:
tails_so_far = tails_so_far + 1
print "Attempt #" + str(attempts_so_far) + " Throwing a coin... It's a tail!... Got " + str(heads_so_far) + "head(s) so far and " + str(tails_so_far) + " tails so far"
print "Ending the program, thank you!"
heads_tails()
| true
|
a3d18cc43f4ca22670598e60ba5b883f11c867b5
|
dexterka/coursera_files
|
/2_Python_data_structures/week4_lists/lists_testing.py
| 1,019
| 4.125
| 4
|
# Define list
friends = ['Bob', 'Harry', 'Anne', 'Peter', 'Helen', 'Mary']
print(friends[2:4])
print(type(friends))
friends[1] = 'Susan'
print(friends)
print('Length of list:', len(friends))
# A counted loop with range
for i in range(len(friends)):
friend = friends[i]
print('Index:', i)
print('Happy New Year:', friend)
# Manipulating lists
lists = list()
print(lists)
lists.append(300)
lists.append('red')
lists.append(0.875)
print(lists)
print(type(lists))
friends.sort() # throws an error due to integers, string value and floating number = a mismatch
print(friends) # sorts alphabetically
numerals = [1,2,3,4,5,6]
print(sum(numerals))
print(max(numerals))
print(min(numerals))
text = 'I have some breaking news!'
splitted = text.split() # default is splitting by whitespaces
print(splitted)
print(len(splitted))
for word in splitted:
print(word)
sentence = 'first;second;third'
splitted_delim = sentence.split(';')
print(splitted_delim)
| true
|
cca42ca6cfd18d29c6681cd7a84e813e204e6008
|
MHKNKURT/python_temelleri
|
/5-Pythonda Koşul İfadeleri/if-else-demo.py
| 2,283
| 4.125
| 4
|
#1
# name = input("İsim: ")
# age = int(input("Yaş: "))
# edu = input("Eğitim Durumu: ")
# if (age >= 18) and (edu == "lise" or edu == "üniversite"):
# print("Ehliyet alabilirsiniz.")
# else:
# print("Ehliyet alamazsınız.")
#2
sozlu1 = int(input("Sözlü1: "))
sozlu2 = int(input("Sözlü2: "))
yazili = int(input("Yazılı: "))
ort = ((sozlu1 + sozlu2)/2)*0.50 + (yazili*0.50)
if 85<= ort < 100:
print("Notunuz 5")
elif 70<= ort < 84:
print("Notunuz 4")
elif 55<=ort <69:
print("Notunuz 3")
elif 45<= ort < 54:
print("Notunuz 2")
elif 25<= ort<44:
print("Notunuz 1")
else:
print("Notunuz 0")
#3
# if days <= 365:
# print("1.servis aralığı")
# elif (days>365) and (days<= 730):
# print("2.servis aralığı")
# elif (days>730) and (days<= 1095):
# print("3.servis aralığı")
# else:
# print("Aracınızın garanti süresi dolmuş.")
#4
# x = int(input("Sayı: "))
# if x>0 and x%2==0:
# print("Sayınız pozitif çift sayıdır.")
# else:
# print("Sayınız pozitif çift sayı değildir.")
#5
# username = input("Kullanıcı adı: ")
# password = input("Şifre: ")
# if username == "semainal" and password== "1234":
# print("Giriş Başarılı")
# else:
# print("Kullanıcı bilgileriniz yanlış.")
#6
# a = int(input("a: "))
# b = int(input("b: "))
# c = int(input("c: "))
# if a>b and a>c:
# print("a en büyüktür.")
# elif b>a and b>c:
# print("b en büyüktür.")
# elif c>a and c>b:
# print("c en büyüktür.")
#7
# vize1 = int(input("vize1: "))
# vize2 = int(input("vize2: "))
# final = int(input("final: "))
# ort = ((vize1+vize2)/2) * 0.60 + final * 0.40
# if ort >= 50:
# print("Dersten başarıyla geçtiniz.")
# elif final >= 70:
# print("Dersten başarıyla geçtiniz.")
# elif final<=50:
# print("Final notunuz 50'nin altında olduğu için kaldınız.")
#8
# name = input("İsim: ")
# kg = float(input("Kilo: "))
# hg =float(input("Boy: "))
# formul = (kg)/ (hg**2)
# if (formul>=30.0) and (formul<=34.9):
# print("Şişman (obez)")
# elif (formul>=25.0) and (formul >=29.9):
# print("Fazla Kilolu")
# elif (formul>=18.5) and (formul >= 24.9):
# print("Normal")
# elif (0 <= formul) and (formul >= 18.4):
# print("Zayıf")
# else:
# print("Bilgileriniz yanlış.")
| false
|
15119d609e7855b9330937e8d96e235dd900361e
|
vkmb/py101
|
/classes/classes and objects.py
| 853
| 4.125
| 4
|
# classes.py
# - classes and objects
class Employee:
'Common base class for all employees'
empCount = 0 # This is a class variable
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
# Adding some members
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
# Check and display
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employees %d" % Employee.empCount
# Adding new attributes
emp1.location="California"
print emp1.location
class Manager(Employee): # Manager is an employee
| true
|
954070ef0bbdfc02dd030e2f7ab9a2abdf26d190
|
mjaw10/assignment
|
/Spot check pool.py
| 521
| 4.21875
| 4
|
print("This program will calculate the volume of a pool")
width = float(input("Please enter the width of the pool: "))
length = float(input("Please enter te length of the pool: "))
depth = float(input("Please enter the depth of your pool: "))
main_section_volume = length * width * depth
circle_radius = width/2
circle_area = 3.14 * (circle_radius ** 2)
half_circle_volume = (circle_area / 2) * depth
pool_volume = main_section_volume + half_circle_volume
print("The pool volume is {0}m³".format(pool_volume))
| true
|
5f111a2967558285ab96d83966b029eebe29a3d2
|
saisrikar8/C1-Dictionary
|
/main.py
| 1,797
| 4.125
| 4
|
'''
03/08/2021
Review
List:
mutable, []
List functions
LIST.insert(INDEX, ELEMENT)
LIST.append(ELEMENT)
LIST.remove(ELEMENT)
LIST.pop(INDEX)
LIST[INDEX] = ELEMENT
Tuple
immutable, ()
___________________________________________________
Dictionary
Another type of list, stores data/values inside the curly brackets, {}.
Similar to a list, it is mutable, however the index is a key, which is liked to data/values.
Ex.
student = {}
student["name"] = "John"
student["age"] = 12
student["weight"] = "120lbs"
student["school"] = "Evergreen"
student["Python"] = True
print(student["age"])
print(student["weight"])
print(student["Python"])
Time
Handles time-related tasks
Formula
import time # Importing the time library
Useful Time functions
1. time.time()
- returns floating-point numbers in seconds passed since epoch(Jan. 1st 1970, 00:00 UTC)
- Use it for Date arthmetic (etc. duration)
import time
print (time.time())
2. time.sleep(NUMBER)
- Suspends(delays) execution of the current thread for the given number of seconds
import time
for x in range(10):
print(str(x) + " seconds has passed")
time.sleep(60)
'''
# Exercise 1
'''
Expected output:
*
* *
* * *
* * * *
* * * * *
'''
print("Exercise 1")
for x in range(5):
print("* " * (x + 1))
# Exercise 2
'''
Expected output:
* * * * *
* * * *
* * *
* *
*
'''
print("\nExercise 2")
for i in range(5):
print("* " * (5 - i))
#Exercise 3
'''
*
* *
* * *
* * * *
* * * * *
'''
print("\nExercise 3")
for y in range(5):
print(" " * 3 * (4 - y) + "* " * (y+1))
#Exercise 4
print("\nExercise 4")
'''
* * * * *
* * * *
* * *
* *
*
'''
for z in range(5):
print(" " * 3 * z + "* " * (5 - z))
| true
|
a010b033f58c902cfcf9979e4ab456c78795f2d7
|
chernish2/py-ml
|
/01_linear_regression_straight_line.py
| 2,976
| 4.3125
| 4
|
# This is my Python effort on studying the Machine Learning course by Andrew Ng at Coursera
# https://www.coursera.org/learn/machine-learning
#
# Part 1. Linear regression for the straight line y = ax + b
import pandas as pd
import numpy as np
from plotly import express as px
import plotly.graph_objects as go
# Hypothesis function, or prediction function
def hypothesis(x, θ):
return x[0] * θ[0] + x[1] * θ[1]
# Cost function aka J(θ) is MSE (Mean Squared Error)
def cost_function(x, y, θ):
m = len(x) # number of rows
sqr_sum = 0
for i in range(m):
sqr_sum += pow(hypothesis(x[i], θ) - y[i], 2)
return sqr_sum / (2 * m)
# Gradient descent algorithm
def gradient_descent(x, y, α, normalize=True):
steps_l = [] # list for visualizing data
n_iter = 500 # number of descent iterations
visualize_step = round(n_iter / 20) # we want to have 20 frames in visualization because it looks good
m = len(x) # number of rows
θ = np.array([0, 0])
# normalizing feature x_1
x_norm = x.copy()
if normalize:
max_x1 = max(np.abs(x[:, 1]))
x_norm[:, 1] = x_norm[:, 1] / max_x1
# gradient descent
for iter in range(n_iter):
sum_0 = 0
sum_1 = 0
for i in range(m):
y_hypothesis = hypothesis(x_norm[i], θ)
sum_0 += (y_hypothesis - y[i]) * x_norm[i][0]
sum_1 += (y_hypothesis - y[i]) * x_norm[i][1]
if iter % visualize_step == 0: # add visualization data
steps_l.append([x[i][1], y_hypothesis, iter])
new_θ_0 = θ[0] - α * sum_0 / m
new_θ_1 = θ[1] - α * sum_1 / m
θ = [new_θ_0, new_θ_1]
cost = cost_function(x, y, θ)
if iter % visualize_step == 0: # debug output to see what's going on
print(f'iter={iter}, cost={cost}, θ={θ}')
print(f'Gradient descent is done with θ_0={θ[0]} and θ_1={θ[1]}')
# visualizing gradient descent
df = pd.DataFrame(np.array(steps_l), columns=['x', 'y', 'step'])
fig = px.scatter(df, x='x', y='y', animation_frame='step')
fig.add_trace(go.Scatter(x=x[:, 1], y=y, mode='markers'))
global figure_n
fig.update_layout(title={'text': f'Figure {figure_n}. α={α}, normalize={normalize}', 'x': 0.5, 'y': 0.9}, font={'size': 18})
fig.show()
figure_n += 1
# Generating dataset for our function y = ax + b
# In this case y = 36.78 * x - 150
def generate_dataset():
a = 36.78
b = -150
x = np.arange(-10, 10, step=0.1)
y_dataset = a * x + b
noise_ar = np.random.random(y_dataset.shape) * 100 # add some noise to the data
x_dataset = np.array([[1, x] for x in x]) # adding feature x_0 = 1
y_dataset = y_dataset + noise_ar
return x_dataset, y_dataset
x, y = generate_dataset()
α_l = [0.0605, 0.06, 0.05975, 0.05]
figure_n = 1
for α in α_l:
gradient_descent(x, y, α, False)
α_l = [0.3, 0.03]
for α in α_l:
gradient_descent(x, y, α)
| true
|
21f96178fa5517739532612710192bcb8edb93c4
|
akankshashetty/python_ws
|
/Q5.py
| 341
| 4.34375
| 4
|
"""5. Write a program to print the Fibonacci series up to the number 34.
(Example: 0,1,1,2,3,5,8,13,… The Fibonacci Series always starts with 0 and 1, the numbers that follow are arrived at by
adding the 2 previous numbers.)"""
a = 0
b = 1
c = 0
print(a,b,end=" ")
while not c==34:
c=a+b
print(c,end=" ")
a,b=b,c
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.