blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c8a1104eaafbc5d6d5684d863470643a57da0b25 | cattiza/thinkpython2 | /Optional_Parameter.py | 1,045 | 4.125 | 4 | class Dog():
"""A simple attempt to model a dog."""
def __init__(self, name, age):
"""Initialize name and age attributes. """
self.name = name
self.age = age
def sit(self):
print(self.name.title()+ " is now sitting")
def roll_over(self):
print(self.name.title()+ " rolled over!")
mydog = Dog("wiliam", 8)
print("my dog name is: " + mydog.name.title())
print("My dog is: " + str(mydog.age) + " . ")
mydog.sit()
mydog.roll_over()
class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.name = restaurant_name
self.type = cuisine_type
def describle_restaurant(self):
print(self.name.title())
print(self.type.title())
def open_restaurant(self):
print(self.name.title()+ " is open")
my = Restaurant("bac","Viet nam")
my.describle_restaurant()
| false |
6d0c94be6a853bb27bc1fa316a1248294bfa5599 | ArturRejment/snake | /scoreboard.py | 725 | 4.15625 | 4 | from turtle import Turtle
""" A class to display current score and game over message """
class ScoreBoard(Turtle):
def __init__(self):
super().__init__()
self.score = -1
self.color("white")
self.hideturtle()
self.goto(0, 250)
self.write_score()
# Update and write the score
def write_score(self):
self.score += 1
self.clear()
self.write(f"Score = {self.score}", False,
align="center", font=("Arial", 25, "normal"))
# Print the message after the game is over
def game_over(self):
self.goto(0, 0)
self.write("GAME OVER.", False, align="center",
font=("Arial", 25, "normal"))
| true |
e0ee6cd8443b7cb52ad85246fccc8c5a4420f4f4 | Axaxaxas-Mlo/Python101 | /Lists.py | 1,332 | 4.375 | 4 | Lista1 = ['Elemento 1',2]
print(Lista1)
print(type(Lista1[0]))
cuadrados = [1,4,9,16,25]
print(cuadrados)
slice = cuadrados[:-1] # No entiendo bien como funciona, si es una clase porque se define asi?
print(slice) # Slice realmente es una lista, que onda con esto?
cuadrados[2] = 'dos'
print(cuadrados)
animales = ['elefante', 'leon', 'tigre', 'jirafa']
print(animales)
animales += ['mono', 'perro'] # similar a B = B + [Elem1,Elem2]
print(animales)
animales.append('dino') # anades solo un elemento al final de la lista
print(animales)
animales[6] = 'Dinosaurio' # solo modificas un solo elemento [6]
print(animales)
animales = animales + ['gato', 'pajaro'] # parecido al append pero puedes agregar mas de un elemento
print(animales)
plantas = ['arbustos','flores']
animales += [plantas,2]
print(animales)
Ultimo = animales.pop()
print(Ultimo)
animales[2:3] = ['gato pequeno', 'gato grande'] # puedes remplazarlo por un mismo elemento 'gato' en ambos elementos
print(animales)
animales[3:5] = []
print(animales)
#animales[:] = [] # igual sirve para borrar la lista
#print(animales)
animales.clear() # metodo para borrar una lista
print(animales)
grocery_list = ['pescado', 'tomate', 'manzana']
print('tomate' in grocery_list) # la funcion in sirve para buscar un elemento en una lista, en que mas sirve? | false |
c75efc7afdbd281bd93863f9f9d67194db9a1046 | Axaxaxas-Mlo/Python101 | /elseifLoop.py | 1,200 | 4.3125 | 4 | x = -2
if x < 0:
print ('x < 0') # checa si es menor a cero
elif x == 0:
print ('x is zero') # si no es verdadero que x < 0, checa si x = 0
elif x == 1:
print ('x is one') # si no es igual a cero, checa si es uno
else:
print ('Ninguno de los anteriores es verdadero') # cuando ningun valor es correcto
name = 'ana'
if name in 'panama':
print ('Si esta')
else:
print ('No esta')
a = 2
b = 3
if a < b:
print ('a es menor que b')
elif a == b:
print ('a es igual a b')
else:
print ('a es mayor que b')
c = 4
"""
if a < b and a < c:
if b < c:
print ('a < b < c')
else:
print ('a < c < b')
elif a < b and a > c:
print ('b < a < c')
elif a > b and a < c:
if b < c:
print
"""
temp = 31
if temp > 22 and temp < 30:
print ('temperatura esta bien (%d)' %temp)
else:
print ('temperatura esta mal (%d)' %temp)
temp = 31
if 22 <= temp <= 30:
print ('temperatura esta bien (%d)' %temp)
else:
print ('temperatura esta mal (%d)' %temp)
temp = int(input('Introduzca la temperatura actual'))
if 22 <= temp <= 30:
print ('temperatura esta bien (%d)' %temp)
else:
print ('temperatura esta mal (%d)' %temp)
| false |
61ebe352704ce9bbbf643534cacb3287214725e7 | dnieafeeq/mysejahtera_clone | /Day2/chapter32.py | 705 | 4.46875 | 4 | theCount = [1, 2, 3, 4, 5]
fruits = ['banana', 'grape', 'mango', 'durian']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in theCount:
print(f"This is count {number}")
# same as above
for fruit in fruits:
print(f"A fruit of type: {fruit}")
# amixed list
# use {} since we don't know what's in it
for i in change:
print(f"I got {i}")
# build lists with an empty one
elements = []
# use the range function to do 0 to 5 counts
for i in range(0, 6):
print(f"Adding {i} to the list.")
# append is a function that lists understand
elements.append(i)
# print them out
for i in elements:
print(f"Element was: {i}") | true |
2580f8a9daee003faf559e5e880ecc12c7170e83 | Rantpel/Batch-Four | /leap year.py | 272 | 4.375 | 4 | #Purpose of the program
print("Program to Determine is a given year is a leap year")
year=int(input("Enter yearto be Checked."))
if(year%4==0 and year%100!=0 or year%400==0):
print("The year is a leap year")
else:
print("The year isn't a leap year!")
| true |
5cb76103b8e0c3142b9530c0d8f4c3498ba3f439 | Rantpel/Batch-Four | /simple int.py | 573 | 4.3125 | 4 | #The purpose of the Program
print("this is a program to find Simple Interest")
#Ask the user to input the principal amount
print("Input the principal amount")
principal=int(input("the value of principal:"))
#Ask the user to input the rate
print("Input the principal amount")
rate=float(input("the value of rate:"))
#Ask the user to input the time period
print("Input the time period")
time=int(input("the value of time:"))
#Calculate the simple interest
interest=(principal*rate*time/100
#Print out the simple interest
print("round(interest,2"))
| true |
bdf46483e177e6e935750d552f5448f10a7d5bf2 | YXMforfun/_checkio-solution | /home/median.py | 1,251 | 4.15625 | 4 | """
A median is a numerical value separating the upper half of a sorted array of numbers from the lower half.
In a list where there are an odd number of entities, the median is the number found in the middle of the array.
If the array contains an even number of entities, then there is no single middle value, instead the median becomes
the average of the two numbers found in the middle.
For this mission, you are given a non-empty array of natural numbers (X).
With it, you must separate the upper half of the numbers from the lower half and find the median.
"""
def median(data):
result = sorted(data)
length = len(data)
if length == 1:
return data[0]
elif length %2 == 0:
fin = (result[(length//2) -1] + result[length//2]) / 2
else :
fin = result[length//2]
return fin
if __name__ == '__main__':
assert median([1, 2, 3, 4, 5]) == 3, "Sorted list"
assert median([3, 1, 2, 5, 3]) == 3, "Not sorted list"
assert median([1, 300, 2, 200, 1]) == 2, "It's not an average"
assert median([3, 6, 20, 99, 10, 15]) == 12.5, "Even length"
print("Start the long test")
assert median(list(range(1000000))) == 499999.5, "Long."
print("The local tests are done.")
| true |
a109be86b2888df9b07f5a4a8b3cd254f7f99626 | sek550c/leetcode | /py/121BestTimeBuyAndSell.py | 901 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
'''
import time
# record min price and max profit
def maxProfit(prices):
minPrice = prices[0]
maxProfit = 0
for p in prices:
minPrice = min(minPrice, p)
maxProfit = max(maxProfit, p - minPrice)
return maxProfit
prices = [1, 6, 4, 3, 1]
time0 = time.clock()
print maxProfit(prices)
time1 = time.clock()
print 'cost %f s' % (time1-time0)
| true |
1805e80b2a72b2bec016f4a3180cdd649c3ecde6 | sek550c/leetcode | /py/27RemoveElement.py | 772 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
'''
import time
def removeElement(nums, val):
m = 0
for i in xrange(len(nums)):
if nums[i] != val:
nums[m] = nums[i]
m += 1
return m
nums = [3, 2, 2, 3]
val = 3
time0 = time.clock()
print nums[:removeElement(nums, val)]
time1 = time.clock()
print 'cost: %f s' % (time1-time0)
| true |
70979eb5db49ade6b309de53f1ca5eba96bca979 | sek550c/leetcode | /py/118PascalTriangle.py | 954 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
'''
import time
def getNum(row, col):
if row == col or col == 1: return 1
else: return getNum(row-1, col-1) + getNum(row-1, col)
def generate(numRows):
tri = []
for row in xrange(1, numRows+1):
for col in xrange(1, row+1):
#print row, col
tri.append(getNum(row, col))
tri += tri
return tri
#Any row can be constructed using the offset sum of the previous row. Example:
# 1 3 3 1 0 (previous row)
# + 0 1 3 3 1
# = 1 4 6 4 1 (next row)
def generate2(numRows):
res = [[1]]
for i in range(1, numRows):
res += [map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1])] # map compute (see map and lambda)
return res[:numRows] # in case numRows = 0
Row = 5
print generate2(Row)
| true |
b0d56744efd572d799a2a3d43924166ce2de0af0 | sek550c/leetcode | /py/283MoveZeros.py | 1,024 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
'''
import time
# two pointer
def moveZeroes(nums):
cur, zero = 0, 0
while cur < len(nums):
if nums[cur] != 0: # not zero
if cur != zero:
nums[cur], nums[zero] = nums[zero], nums[cur] # swap with zero
zero += 1 # and zero plus 1
cur += 1
return nums
# pop and append
def moveZeroes2(nums):
for x in nums:
if x == 0:
nums.pop(nums.index(x))
nums.append(x)
return nums
nums = [0, 1, 0, 0, 3, 2]
time0 = time.clock()
print moveZeroes(nums)
time1 = time.clock()
print 'cost: %f s' % (time1 - time0)
print moveZeroes2(nums)
time2 = time.clock()
print 'cost: %f s' % (time2 - time1)
| true |
cebbe4aaacb3da2130490bb808a877c9272f2eee | sek550c/leetcode | /py/350IntersectionOfTwoArray.py | 2,526 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
'''
'''
Q1:
If arrays are sorted, then use method 2, i.e. pointer method.
Q2:
Q3:
If only nums2 cannot fit in memory, put all elements of nums1 into a HashMap, read chunks of array that fit into the memory, and record the intersections.
If both nums1 and nums2 are so huge that neither fit into the memory, sort them individually (external sort), then read 2 elements from each array at a time in memory, record intersections.
'''
import time
'''
this func not work for case [1, 2, 3][2, 1, 1]
def intersect(nums1, nums2):
res = []
i, j = 0, 0
if len(nums1) < len(nums2): # make sure nums2 is smaller
nums1, nums2 = nums2, nums1
nums1 = sorted(nums1) # for test case [1, 2][2, 1]
nums2 = sorted(nums2)
print nums1
print nums2
while j < len(nums2) and i < len(nums1):
if nums1[i] == nums2[j]:
res.append(nums2[j])
j += 1
i += 1
return res
'''
# assume nums1 size: m, nums2 size: n
# hash time:O(m+n), space: O(m) or O(n)
def intersect(nums1, nums2):
res = []
# store nums2 in hash table
hashtable = {}
for num in nums2:
hashtable[num] = hashtable.get(num, 0) + 1
# process through nums1
for num in nums1:
if num in hashtable and hashtable[num] != 0:
res.append(num)
hashtable[num] -= 1
return res
# sort and pointer
def intersect2(nums1, nums2):
nums1, nums2, i, j, res = sorted(nums1), sorted(nums2), 0, 0, []
while i < len(nums1) and j < len(nums2):
if nums1[i] == nums2[j]:
res.append(nums1[i])
i += 1
j += 1
elif nums1[i] < nums2[j]:
i += 1
else:
j += 1
return res
#nums1 = [-2147483647,1,2,3]
#nums2 = [1,-2147483647,-2147483647]
#nums2 = [1, 2]
#nums1 = [2, 1]
nums1 = [1, 2]
nums2 = [2, 1]
time0 = time.clock()
print intersect(nums1, nums2)
time1 = time.clock()
print "cost: %f s" % (time1 - time0)
print intersect2(nums1, nums2)
time2 = time.clock()
print "cost: %f s" % (time2 - time1)
| true |
9a17391792811cb4a9ec80bb949315b09340b224 | Sharmaraunak/python | /wk215.py | 363 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 8 14:24:17 2018
@author: raunak
"""
##print("enter the base: ")
#base = eval(input())
#print("enter the exponential power: ")
#exp = int(input())
def iterPower(base,exp):
result =1
while exp > 0:
result = result*base
print(result)
exp-=1
return result
| true |
08a24f5866f3f3b9c14edfcdf459134bc530df3b | deepanshurana/Python-Codes | /ErrorsAndExceptions.py | 987 | 4.1875 | 4 | """
There are two kinds of errors: SyntaxError and Exceptions.
Even if the statement or expression is syntactically correct,it may cause
an error when an attempt is made to execute it.
It is possible to handle selected exceptions. (using try and except)
firstly, the try clause is executed. If no exceptions, then except clause
is skipped and try statement is finished.
The finally clause runs whether or not the try statement produces an exception.
Following are the two examples.
"""
def divide(x, y):
try:
res = x / y
except ZeroDivisionError:
print("Divisible By Zero. Exception handled.", end='\n')
else:
print("RESULT: ", res)
finally:
print("FINALLY... I ALWAYS WORK, NO MATTER WHAT.")
def main():
divide(2, 1)
divide(2, 0)
# divide("2", "1")
# for this program with string I/P to work, use bare except clause,
# this will handle any kind of exception occurance.
if __name__ == "__main__":
main()
| true |
07323696d37d37669753cca7eea3a943bf1adf78 | deepanshurana/Python-Codes | /max difference in an array.py | 500 | 4.125 | 4 | print('--'* 50)
list = [] #initialising list
size_of_array = int(input('ENTER THE TOTAL ELEMENTS IN AN ARRAY: ')) #for the total size of an array
for i in range(0,size_of_array):
value = int(input('Enter the %d element: ' % (i+1)))
list.append(value) #appending the list
print('The list is :' , list)
list.sort(reverse=True) #sorting the list in descending order
difference = list[0]-list[-1]
print ('the max difference in the list is :' , difference)
print('--'* 50)
| true |
3f62423a1233a8009f15e13e29e05c8c9fa5453f | wrilka/python-beginner-projects | /A simple calculator/final calculator.py | 866 | 4.3125 | 4 | def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
def exponent(n1, n2):
return n1 ** n2
operation = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide,
"**": exponent,
}
def calculator():
n1 = int(input("Input the first number?:\n"))
for symbols in operation:
print(symbols)
again = True
while again:
operation_symbol = input("Input the operation: \n")
n2 = int(input("Input another Number\n"))
calculation = operation[operation_symbol]
answer = calculation(n1,n2)
print(f"{n1} {operation_symbol} {n2} is = {answer}")
another = input(f"Type 'y' to continue calculating {answer} and 'n' to stop").lower()
if another == "y":
n1 = answer
else:
again = False
print(f"Your Final answer is {answer}")
calculator()
calculator() | false |
13a4a85fe117384d118cd3fe2f3a56d88d5747b0 | nikgun1984/Data-Structures-in-Python | /Queues and Stacks/Stack.py | 1,159 | 4.15625 | 4 | # Stack implementation using LinkedList
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.top = None
self.bottom = None
self.length = 0
def push(self, value):
new_node = Node(value)
if self.length == 0:
self.top = new_node
self.bottom = new_node
else:
new_node.next = self.top
self.top = new_node
self.length += 1
def pop(self):
if self.top is None:
return "None"
if self.top == self.bottom:
self.bottom = None
self.top = self.top.next
self.length -= 1
def peek(self):
return self.top.value
def is_empty(self):
return self.length == 0
def print_list(self):
node = self.top
while node:
print(node.value, end=',')
node = node.next;
print("\b")
stack = Stack()
stack.push(3)
stack.push(5)
stack.push(7)
stack.push(9)
stack.print_list()
print()
stack.pop();
stack.print_list()
print(stack.peek())
print(stack.is_empty())
| true |
15369703773202192231181b1c5940dfb8488fca | patrick-du/Notes | /Courses & Books/Grokking Algorithms/breadth_first_search.py | 2,680 | 4.25 | 4 | # Breadth-first search (BFS): a graph algorithm to find the shortest path b/w 2 nodes
# Breath-first search answers 2 questions:
# - Is there a path from node A to node B?
# - What is the shortest path from node A to node B?
# Example Use Case
# - Checkers AI to calculate fewest moves to victory
# - Spell chcker (fewest misspelling to real world)
# - Find closest doctor in network
# Graph
# - Models a set of connections
# - Comprised of nodes and edge
# - A node directly connected to another node is called its neighbor
# BFS Example: mango seller in network
# - You are looking for a mango seller
# - Make a list of friends and iterate through each friend checking if they sell mangos
# - If they do, you have found a mango seller
# - If they do not, search through your friend's friends
# - Repeat cycle until entire network is visited
# - Implemented with a queue (people must be searched in the order they're added)
# Queues
# - Similar to stacks, no random access
# - Operations
# - Enqueue: add item to end of queue
# - Dequeue: take off item at front of queue
# - Considered a FIFO data structure (first in, first out)\
# Graph Implementation (represent nodes as hash tables)
from collections import deque
graph = {}
graph["you"] = ["alice", "bob", "claire"] # Array of your neighbors
graph["bob"] = ["anuj", "peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom", "jonny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["jonny"] = []
# Directed graph: has arrows, one way relationship
# Undirect graph: no arrows, two way relationship
# BFS Implementation
# 1. Keep queue containing people to check
# 2. Pop person off queue
# 3. Check if person is a mango seller
# - a. Yes, you're done
# - b. No, add all their neighbors to the queue
# 4. Loop
# 5. If queue is empty, no manager sellers in network
def search(name):
search_queue = deque()
search_queue += graph["you"]
searched = []
while search_queue:
person = search_queue.popleft()
if not person in searched:
if person_is_seller(person):
print(person + " is a mango seller!")
return True
else:
search_queue += graph[person]
searched.append(person)
return False
def person_is_seller(name):
return name[-1] == 'm'
search("you")
# BFS Runtime
# - Enqueue takes constant time, O(1)
# - Doing this for every person takes O(n)
# - BFS takes O(V+E) where
# - V = # of people
# - O = # of edges
# Tree: special type of graph where no edges ever point back | true |
df90b293ace1bab8e500c6ab24d6a008170b2666 | mlama007/4RockPaperScissors | /4ROCK_PAPER_SCISSORS.py | 1,193 | 4.15625 | 4 | """This is a simple game of rock, paper, scissors"""
from random import randint
from time import sleep
options = ["R", "P", "S"]
LOSE = "You lost!"
WIN = "You won!"
def decide_winner(user_choice, computer_choice):
print "Your choice: %s" % user_choice
print "Computer selecting..."
sleep(1)
print "Computer choice: %s" % computer_choice
user_choice_index = options.index(user_choice)
computer_choice_index = options.index(computer_choice)
if user_choice_index == computer_choice_index:
print "This is a tie!"
elif user_choice_index == 0 and computer_choice_index == 2:
print WIN
elif user_choice_index == 1 and computer_choice_index == 0:
print WIN
elif user_choice_index == 2 and computer_choice_index == 1:
print WIN
elif user_choice_index > 2:
print "Invalid Choice!"
return
else:
print "You lose!"
def play_RPS():
print "Let's play rock, paper, scissors!"
user_choice = raw_input("Select R for Rock, P for Paper, or S for Scissors: ").upper()
sleep(1)
computer_choice = options[randint(0,len(options)-1)]
decide_winner(user_choice, computer_choice)
play_RPS() | true |
a960c05cf9b1f541bc638170cf8ecb616c00cf6d | Sandhya788/Basics | /python/password5.py | 394 | 4.15625 | 4 | incorrectPassword= True
while incorrectPassword:
password = input("type in your password")
if len(password < 8):
print("your password must be 8 characters long")
elif noNum(password == False):
print("you need a number in your password")
elif noCap(password == False):
print("you need a capital letter in your password")
elif NoLow(password == False): | true |
3563aad76f85735b0d143c2fa6d3319e47e179bf | wurainren/leaningPython | /com/wurainren/base/dataType.py | 1,274 | 4.46875 | 4 | # -*- coding:utf-8 -*-
#Python内置的一种数据类型是列表:list。
# list是一种有序的集合,可以随时添加和删除其中的元素。
classmates = ['Michael', 'Bob', 'Tracy']
# query 通过下标;切片
print(classmates[0])
print(classmates[-1])
print(classmates[:1]) #===》这里切出来的结果,还是一个list
# count 通过len()函数 获取list元素的个数
print(len(classmates))
# add 通过append()函数,追加元素到末尾;insert()函数 将元素插入指定的位置
classmates.append('Adem')
print(classmates)
classmates.insert(1,'Good')
print(classmates)
classmates[1]='Jack'
print(classmates)
# delete 通过pop()函数,删除list末尾;也可用指定位置删除元素
classmates.pop()
print(classmates)
classmates.pop(1)
print(classmates)
L =[
['Apple','Google','Microsoft'],
['Java','Python','Ruby','PHP'],
['Adam','Bart','Lisa']
]
print(L[0][0])
print(L[1][1])
print(L[2][2])
#有序列表元组:tuple。
# tuple和list非常类似,但是tuple一旦初始化就不能修改
myClassName = ('Michael', 'Bob', 'Tracy')
t=(1,2)
print(t)
print(t[0])
print(t[1])
print(t[-1])
#list和tuple是Python内置的有序集合,一个可变,一个不可变。根据需要来选择使用它们 | false |
0ba02a9253e23eb402cbb15f8b317256283bc025 | xen0bia/college | /csce160/book_source_code/Chapter 10/exercise1/exercise1.py | 1,785 | 4.65625 | 5 | # 1. Pet Class
# Write a class named Pet , which should have the following data attributes:
# • _ _ name (for the name of a pet)
# • _ _ animal_type (for the type of animal that a pet is. Example values are ‘Dog’, ‘Cat’,
# and ‘Bird’)
# • _ _ age (for the pet’s age)
# The Pet class should have an _ _ init _ _ method that creates these
# attributes. It should also have the following methods:
# • set_name
# This method assigns a value to the _ _ name field.
# • set_animal_type
# This method assigns a value to the _ _ animal_type field.
# • set_age
# This method assigns a value to the _ _ age field.
# • get_name
# This method returns the value of the _ _ name field.
# • get_animal_type
# This method returns the value of the _ _ animal_type field.
# • get_age
# This method returns the value of the _ _ age field.
#Once you have written the class, write a program that creates an object of the class and
#prompts the user to enter the name, type, and age of his or her pet. This data should be
#stored as the object’s attributes. Use the object’s accessor methods to retrieve the pet’s
#name, type, and age and display this data on the screen.
class Pet:
def __init__(self,name,animal_type,age):
self.__name = name
self.__animal_type = animal_type
self.__age = age
def set_name(self,name):
self.__name = name
def set_age(self,age):
self.__age = age
def set_animal_type(self,animal_type):
self.__animal_type = animal_type
def get_name(self):
return self.__name
def get_animal_type(self):
return self.__animal_type
def get_age(self):
return self.__age | true |
bbb14262a5f93148882b0a0c0b91cb224e769682 | xen0bia/college | /csce160/lab5/payroll.py | 876 | 4.15625 | 4 | '''
Zynab Ali
'''
REG_HRS = 40.0 # Hours at regular pay before overtime starts
OVERTIME_RATE = 1.5 # Overtime payrate multiplier
def main():
hours_worked = float(input('\nEnter the number of hours worked this week: '))
hourly_rate = float(input('Enter the hourly pay rate: '))
if hours_worked > REG_HRS:
print('This individual worked overtime.')
gross_pay = (hourly_rate*REG_HRS) + (hourly_rate*OVERTIME_RATE*(hours_worked - REG_HRS))
print(f'The gross pay is ${gross_pay: .2f}')
else:
print('This individual did not work overtime.')
gross_pay = hourly_rate * hours_worked
print(f'The gross pay is ${gross_pay: .2f}')
if gross_pay > 5000.0:
print('Congratulations!')
print('You earned more than $5,000 this week!')
if __name__ == '__main__':
main()
| true |
989d12e0d08597a26cb87d17c91b37671a213a2f | githubcj79/nisum_test | /answers.py | 1,755 | 4.40625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Ejercicio 1
# Write a Python program to square and cube every number in a given list of integers using Lambda.
# Original list of integers:
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Square every number of the said list:
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# Cube every number of the said list:
# [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
def exercise_1(input_list=[]):
squared_list = list(map(lambda x: x * x, input_list))
print(squared_list) # [2, 4, 6, 8, 10]
cubed_list = list(map(lambda x: x * x * x, input_list))
print(cubed_list) # [2, 4, 6, 8, 10]
# Ejercicio 2
# Write a Python class to implement pow(x, n)
class Pow(object):
"""docstring for Pow"""
def __init__(self, x, n):
super(Pow, self).__init__()
self.x = x
self.n = n
def pow_(self):
return pow(self.x, self.n)
# Ejercicio 3
# Un número natural es un palíndromo si se lee igual de izquierda a derecha y de derecha a izquierda.
# Por ejemplo, 14941 es un palíndromo, mientras que 81924 no lo es.
# Escriba un programa que indique si el número ingresado es o no palíndromo
def is_palindrome( s ):
if len(s) < 1:
return True
else:
if s[0] == s[-1]:
return is_palindrome( s[1:-1] )
else:
return False
def main():
exercise_1(input_list=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(f"Pow(2, 3) = {Pow(2, 3).pow_()}")
print(f"Pow(5, 2) = {Pow(5, 2).pow_()}")
num = 123
print(f" Is palindrome {num} ? {'yes' if is_palindrome(str(num)) else 'no'}")
num = 323
print(f" Is palindrome {num} ? {'yes' if is_palindrome(str(num)) else 'no'}")
if __name__ == "__main__":
main()
| true |
909de2fb5af980a531f87002206b5b0a8972b2a7 | Zuiveraar/Proyectos-y-trabajos-Codecademy- | /Standalones/fibonacci.py | 1,340 | 4.21875 | 4 | def fibonacci(n):
if n is 1:
return 1
if n is 0:
return 0
fibValue = fibonacci(n-1) + fibonacci(n-2)
if fibValue not in alreadySeen:
alreadySeen.append(fibValue)
return fibValue
while True:
alreadySeen = []
choice = input("Do you want to generate fibonacci numbers, search them or exit? G/S/E ")
if choice is "G":
lowerLimit = int(input("From which number would you like to see? "))
upperLimit = int(input("Until which number would you like to see? "))
fibonacci(upperLimit)
for i in alreadySeen:
if i > lowerLimit and i < upperLimit:
print(i)
w = input("Do you want to save this sequence? Y/N ")
if w is "Y":
f = open("fib.txt", "w+")
for i in alreadySeen[ lowerLimit : upperLimit]:
f.write(str(i) + ",")
f.close()
elif choice is "S":
f = open("fibUntil40.txt", "r")
contents = f.read()
contentsList = contents.split(",")
f.close()
search = input("Which number do you want to search? ")
try:
print("Number found at index " + contentsList.index(search))
except ValueError:
print("Number not found in fibonacci sequence")
else:
break
print("bye bye") | false |
729b4259757b68b51fd036229495ec6b9108d7e1 | tal21-meet/meet2019y1lab2 | /MEETinTurtle.py | 1,412 | 4.15625 | 4 | import turtle
# Everything that comes after the # is a
# comment.
# It is a note to the person reading the code.
# The computer ignores it.
# Write your code below here...
turtle.penup() #Pick up the pen so it doesn’t
#draw
turtle.goto(-200,-100) #Move the turtle to the
#position (-200, -100)
#on the screen
turtle.pendown() #Put the pen down to start
#drawing
#Draw the M:
turtle.goto(-200,-100+200)
turtle.goto(-200+50,-100)
turtle.goto(-200+100,-100+200)
turtle.goto(-200+100,-100)
turtle.penup()
turtle.goto(-150+100,-100)
turtle.pendown()
turtle.goto(-50+100,-100)
turtle.penup()
turtle.goto(-50+100,-100+200)
turtle.pendown()
turtle.goto(-150+100,-100+200)
turtle.goto(-150+100,-100+100)
turtle.goto(-50+100,-100+100)
turtle.goto(-150+100,-100+100)
turtle.goto(-150+100,-100)
turtle.penup()
turtle.goto(-150+250,-100)
turtle.pendown()
turtle.goto(-50+250,-100)
turtle.penup()
turtle.goto(-50+250,-100+200)
turtle.pendown()
turtle.goto(-150+250,-100+200)
turtle.goto(-150+250,-100+100)
turtle.goto(-50+250,-100+100)
turtle.goto(-150+250,-100+100)
turtle.goto(-150+250,-100)
turtle.penup()
turtle.goto(-150+400,100)
turtle.pendown()
turtle.goto(-150+500,100)
turtle.goto(-150+450,100)
turtle.goto(-150+450,-100)
# turtle.mainloop() tells the turtle to do all
# the turtle commands above it and paint it on the screen.
# It always has to be the last line of code!
| false |
7c68b401fcd371aae138cbf0e3ebd2472985e591 | im-swapnilb/python | /app3-part11.py | 2,935 | 4.34375 | 4 | """
Problem statement :
Ask the user how many floating point numbers with 5 integer digits and two decimal digits the program should accept.
That means you need to check if the number entered by the user has 5 digits and two decimal digits to be accepted.
Your program should accept five of them. Add the numbers and display a subtotal.
@Authors
Urmi Parekh, id : 500186977
Ashish Sharma, id : 500188494
Swapnil Bandgar, id : 500186962
Karthik Thallam, id : 500188370
"""
import re
# Defining the regular expression to check for float value
regex = '[+-]?[0-9]+\.[0-9]+'
# Function for asking user for how many numbers he want to consider
def total_numbers_accept():
total_numbers = int(input("Please enter how many floating point numbers would you like to consider : "))
# Calling function to enter numbers
enter_numbers(total_numbers)
# Function for accepting numbers for user
def enter_numbers(total_number):
floating_numbers_list = [] # Defining list to store floating numbers from user
i = 1
while i <= total_number:
val = input("Please enter floating point number " + str(i) + ": ")
# Calling check function to check whether the entered value is of type float
check_response = check_float(val)
if check_response == 1:
splitting_number = val.split(".") # Splitting the integer digits and decimal digits
integer_part = splitting_number[0]
decimal_part = splitting_number[1]
if len(integer_part) == 5 and len(
decimal_part) == 2: # Checking if integer part has 5 digits and decimal part has 2 digits
floating_numbers_list.append(val) # Appending number into the list
i += 1
else:
print("Please enter a floating point number which has 5 integer digits and 2 decimal places")
# Calling this function to perform summation of all these values
addition_operation(floating_numbers_list)
# A function for checking if values entered by user are of type float
def check_float(float_num):
if re.search(regex, float_num):
return 1
else:
print("Not a Floating point number. Please enter valid floating point number.")
return 0
# Function for Addition operation
def addition_operation(floating_numbers_list):
total = 0.0
i = 0
# We only need to accept 5 numbers as per the problem statement so the value of total_elements should be 5 or
# less than that
if (len(floating_numbers_list)) < 6:
total_elements = len(floating_numbers_list)
else:
total_elements = 5
while i < total_elements:
total = total + float(floating_numbers_list[i])
i = i + 1
print("Total for floating point numbers is:", total)
if __name__ == '__main__':
print("The floating operation begins now")
# Calling the function for accepting numbers
total_numbers_accept()
| true |
799b0d3dfc32ffbf001cda74455b22230e7ae94b | im-swapnilb/python | /pythonTest1/create_dictionary.py | 1,046 | 4.3125 | 4 | """
Create dictionary with different key-values and print it
@Author Swapnil_Bandgar, Student_id : 500186962
"""
# creating dictionary with different approach and datatype
def create_dict():
# creating empty dictionary
dict4 = {}
# dictionary with multiple data types
dict1 = {"Name": "Swapnil", "Course": "AI & DS", "Intake": "Jan21", "SId": 123,
"Subjects": ["Python", "Optimization", "Stats", "AI", "ML"]}
print("Student dictionary: ", dict1)
key_search = "Subjects"
print("All subjects: ", dict1.get(key_search, "Check key once"))
tuple1 = ((1, "Swapnil"), (2, "Bandgar"))
print("dictionary created from tuple ", dict(tuple1))
# dictionary with tuple, list and string, number
dict2 = {"Movies": ["Toy Story 1", "Toy Story 2", "Toy Story 3"], "Rating": [4.0, 5.0, 4.7],
"Released year": (2009, 2011, 2015)}
print("Movie dictionary: ", dict2)
if __name__ == '__main__':
print("lets create dictionary with different data types and methods :")
create_dict()
| true |
5dc54c2f2a1a94ef286021646bb4639060b17356 | im-swapnilb/python | /pythonTest1/operations.py | 420 | 4.3125 | 4 | # Python program for practical application of sqrt() function
# import math module
import testMathFunc
# function to check if prime or not
def check(n):
if n == 1:
return False
# from 1 to sqrt(n)
for x in range(2, (int)(testMathFunc.sqrt(n)) + 1):
if n % x == 0:
return False
return True
# driver code
n = 6
if check(n):
print("prime")
else:
print("not prime")
| true |
9188e2bac20ff5ffc20a18924629faac35eccd6b | Nethermaker/school-projects | /intro/dictionary_assignment.py | 2,734 | 4.28125 | 4 | # 1. Create a dictionary that connects the numbers 1-12 with each
# number's corresponding month. 1 --> January, for example.
months = {1:'January',
2:'February',
3:'March',
4:'April',
5:'May',
6:'June',
7:'July',
8:'August',
9:'September',
10:'October',
11:'November',
12:'December'}
# 2. Write a function called write_date() that takes a date written in
# the format "6/28/1983" and prints it out in the format "28 of June, 1983".
# Hint: The split function can work with more than just spaces!
def write_date(date):
month_day_year = date.split('/')
return '{} of {}, {}'.format(month_day_year[1],
months[int(month_day_year[0])],
month_day_year[2])
# 3. Write a dictionary that contains at least five words as keys,
# and choose a value for each that will replace the word. For example,
# you may have the word "Handelman" as a key and "Batman" as its value.
# Shhh...don't tell anyone.
words_dict = {'Handelman':'Batman',
'is':'isn\'t',
'I':'you',
'will':'won\'t',
'can':'can\'t'}
# 4. Write a function called replace_words() that takes a sentence and
# returns the same sentence, but with any of the keys in your dictionary
# from problem 3 replaced with their respective values. Note: if more
# than one of the words appears in the sentence, then all words should
# be correctly replaced!
# Ex: replace_words('Mr. Handelman is my programming teacher')
# 'Mr. Batman is my programming teacher.'
#This is pretty finnicky and sensitive to punctuation, but it works
def replace_words(sentence):
word_list = sentence.split()
new_string = []
for word in word_list:
if word in words_dict:
new_string.append(words_dict[word])
else:
new_string.append(word)
return ' '.join(new_string).capitalize()
# 4. Write a function called count_words() that takes a string (possibly
# a long string!) as input and counts the number of time each word
# appears in the string. It then returns the count of all words as a
# dictionary.
# Ex: count_words('So patient a doctor to doctor a patient so')
# {'so':2, 'patient': 2, 'a': 2, 'doctor': 2, 'to': 1}
def count_words(string):
count_words = {}
for word in string.lower().split():
if word in count_words:
count_words[word] += 1
else:
count_words[word] = 1
return count_words
| true |
63f9d76cd6887ae1e04bb01c9c1e7f5ad2d91270 | Nethermaker/school-projects | /adv/crash_course.py | 1,904 | 4.125 | 4 | print 'Welcome to Advanced Programming'
#Math
print 3 + 4
print 3 - 4
print 3 * 4
print 3 / 4
name = 'Handelman'
number = 27
number2 = 15
print 'My name is {}.'.format(name)
#your_name = raw_input('What is your name? ')
#print 'Hello there, {}!'.format(your_name)
def average_of_three(x,y,z):
return (x + y + z) / 3.0
print average_of_three(58, 72, 91)
#String methods
word = 'programming'
print word[3]#print a 'g'
print word[-1]#print the last thing 'g'
print word[2:6]#prints 'o' through 'a'
print word[:5]
print word[5:]
word += ' class'
print word
print len(word) #length = 17
print name.lower()
print name.upper()
print name.count('a') #counts the 'a's in name
print name.index('d') #finds the 'd' (3)
#Conditional statements
def is_even(number):
if number % 2 == 0:
return True
else:
return False
#You need elif if there are three or more possibilities
#Loops
def print_to_n(n):
x = 1
while x < n:
print x
x += 1
def keep_printing():
while True:
print 'This goes forever!'
x = raw_input()
if x != '':
break
my_list = [1,2,3,4,5,6,7,8,9,10]
def add_one(lst):
new_list = []
for thing in lst:
new_list.append(thing+1)
return new_list
def add_to_n(n):
return sum(range(1,n+1))
#Dictionaries
#A dictionary pairs off two values with each other.
capitals = {'Spain':'Madrid',
'Norway':'Oslo',
'Djibouti':'Djibouti'}
print capitals['Norway']
#File I/O
with open('demofile.txt', 'w') as my_file:
my_file.write('This is a test.\n')
my_file.write('I am Mr. {}.'.format(name))
with open('demofile.txt', 'rb') as my_file:
string = my_file.read()
print string
| true |
2822851327677da64c8304bc70604beb3f2c46eb | Nethermaker/school-projects | /intro/warmup_day4.py | 870 | 4.3125 | 4 | # The following program is supposed to ask a user how much the meal
# cost, how many people ate, and what percentage they are tipping, and
# should return the amount each person should pay.
# Unfortunately, there are several errors in the program. Can you find
# them all? Here is what the program should look like if it works.
#
# >>> How much was your meal (in dollars)? 82.50
# What percent tip are you leaving? 20
# How many people are contributing to the tip? 4
# You should each leave $______
meal_cost = raw_input ("How much was your meal (in dollars)? ")
percent = raw_input("What percent tip are you leaving? ")
people = raw_input("How many people are contributing to the tip? ")
total_tip = float(meal_cost) * (1 + float(percent)/100)
tip_per_person = float(total_tip) / float(people)
print "You should each leave $" + str(tip_per_person)
| true |
05babfc47f24daf65034ad088d157e909125f077 | acalzadaa/python_bootcamp | /week03 input and coditionals/friday.py | 1,316 | 4.34375 | 4 | # end of week project
# making a calculator!
# 1. Ask the user for the calculation they would like to perform.
# 2. Ask the user for the numbers they would like to run the operation on.
# 3. Set up try/except clause for mathematical operation.
# a. Convert numbers input to floats.
# b. Perform operation and print result.
# c. If an exception is hit, print error.
# Step 1
operation = input("select an operation [a]dd, [s]ubstract, [m]ultiply, [d]ivide: ")
print(f"you selected: {operation}")
try:
first = float(input("first number: "))
second = float(input("second number: "))
if len(operation) == 1:
print("listo!")
if operation.lower() == "a":
print("seleccionaste Add")
print(f"{first} + {second} = {(first+second)}")
elif operation.lower() == "s":
print("Seleccionaste Substract")
print(f"{first} - {second} = {(first-second)}")
elif operation.lower() == "m":
print("Seleccionaste Multiply")
print(f"{first} x {second} = {(first*second)}")
elif operation.lower() == "d":
print("Seleccionaste Divide")
print(f"{first} / {second} = {(first/second)}")
else:
print(f"invalid input! {operation}")
except:
print("Error!")
| true |
e7c0d6a1deed8429577c1ecf9100226f75445668 | acalzadaa/python_bootcamp | /week08 Efficiency/tuesday.py | 1,575 | 4.71875 | 5 | # Lambda functions, otherwise known as anonymous functions,
# are one-line functions within
# >>> lambda arguments : expression
# >>> lambda arguments : value_to_return if condition else value_to_return
# Using a Lambda
# using a lambda to square a number
print( ( lambda x : x**2) (4) )
# Passing Multiple Arguments
# passing multiple arguments into a lambda
print( (lambda x, y : x * y) (2,3))
# Saving Lambda Functions
# saving a lambda function into a variable
square = lambda x,y : x*y
print(square)
result = square(4,6)
print(result)
#Conditional Statements
# using if/else statements within a lambda to return the greater number
greater = lambda x, y : x if x > y else y
result = greater(2,7)
print(result)
# Returning a Lambda
# returning a lambda function from another function
def my_func(n):
return lambda x : x * n
doubler = my_func(2)
print(doubler(3))
tripler = my_func(3)
print(tripler(3))
# Fill in the Blanks: Fill in the blanks for the following code so that it takes in a
# parameter of “x” and returns “True” if it is greater than 50; otherwise, it should
# return “False”:
# >>> ____ x _ True if x _ 50 ____ False
print("Exercise 1")
def greater_than_50(n):
return (lambda x : "True" if x > 50 else "False")(n)
print(greater_than_50(51))
# Degree Conversion: Write a lambda function that takes in a degree value in
# Celsius and returns the degree converted into Fahrenheit.
print("Exercise 2")
def celsius_to_fahrenheit(degrees):
return (lambda x : (x*(9/5)+32))(degrees)
print(celsius_to_fahrenheit(40)) | true |
909c816c70dc94e74ad37588623cca19493a0a46 | acalzadaa/python_bootcamp | /week06 data collections and files/tuesday.py | 1,912 | 4.46875 | 4 | # Tuesday: Working with Dictionaries
#Adding New Information
# adding new key/value pairs to a dictionary
car = {"year" : 2018}
car["color"] = "Blue"
print(f'year {car["year"]} , color {car["color"]}')
#Changing Information
# updating a value for a key/value pair that already exists
car["color"] = "Red"
print(f'year {car["year"]} , color {car["color"]}')
#Deleting Information
# deleting a key/value pair from a dictionary
try:
del car["year"]
print(car)
except KeyError:
print("That key doesnt exist")
#Looping a Dictionary
for key in car.keys():
print(key)
print(car[key])
#Looping Only Values
for value in car.values():
print(value)
#Looping Key-Value Pairs
for key, value in car.items():
print(f"{key} : {value}")
#TUESDAY EXERCISES
# User Input: Declare an empty dictionary. Ask the user for their name, address,
# and number. Add that information to the dictionary and iterate over it to show
# the user.
root = dict()
exit_code = False
index = 0
while not exit_code:
index += 1
name = input("What's your name?: ")
address = input("what's your address?: ")
phone = input("what's your number?: ")
element = dict()
element["name"] = name
element["address"] = address
element["phone"] = int(phone)
element_name = "element" + str(index)
root[element_name] = element
ans = input("Exit (y/n)?: ").lower()
if ans == "y":
exit_code = True
print("Show the Dictionary!")
for elem in root.keys():
print(elem)
print(root[elem])
print(root[elem]["name"])
print(root[elem]["address"])
print(root[elem]["phone"])
# Problem-Solving: What is wrong with the following code:
# >>> person = { 'name', 'John Smith' }
# >>> print(person['name'])
person = { 'name' : 'John Smith' }
print(person['name'])
# Remember that adding and altering key-value pairs are the same syntax.
| true |
4b5e34a4a0f10ff3034e4d82e7c61811636bfdfe | acalzadaa/python_bootcamp | /week08 Efficiency/week_challenge.py | 704 | 4.25 | 4 | # For this week’s challenge, I’d like you to create a program that asks a user to input a number
# and tells that user if the number they entered is a prime number or not.
# Remember that prime numbers are only divisible by one and itself and must be above the number 2.
# Create a function called “isPrime” that you pass the input into, and return a True or False value. Be
# sure to keep efficiency in mind when programming the function
from week08.primenumber import PrimeNumber
def main():
ans = input("Tell me a number: ")
prime_number = PrimeNumber(int(ans))
if prime_number.is_prime():
print("is a prime!")
else:
print("is not a prime!")
main() | true |
a2e299f33ca165eb421f24d80ef8b9996348fc54 | acalzadaa/python_bootcamp | /week04 lists and loops/tuesday.py | 1,551 | 4.28125 | 4 | # writing your first for loop using range,
# COUNTS UP TO... BUT NOT INCLUDING
print("1st Exercise ---------------------")
for num in range(5):
print(f"Value: {num}")
# providing the start, stop, and step for the range function
print("2nd Exercise ---------------------")
for num in range(2, 10, 2):
print(f"Value: {num}")
# printing all characters in a name using the 'in' keyword
print("3rd Exercise ---------------------")
name = "John Smith"
for letter in name:
print(f"Value: {letter}")
# using the continue statement within a foor loop
print("4th Exercise ---------------------")
for num in range(5):
if num == 3:
continue
print(num)
# breaking out of a loop using the 'break' keyword
print("5th Exercise ---------------------")
for num in range(5):
if num == 3:
break
print(num)
# setting a placeholder using the 'pass' keyword
print("6th Exercise ---------------------")
for i in range(5):
# TODO: add code to print number
pass
# Divisible by Three:
# Write a for loop that prints out all numbers from 1 to 100
# that are divisible by three.
print("Test 1 Exercise ---------------------")
for num in range(100):
if num % 3 == 0:
print(num)
# Only Vowels: Ask for user input, and write a for loop
# that will output all the vowels within it.
# For example:
# >>> "Hello" ➔ "eo"
print("Test 2 Exercise ---------------------")
vowels = ["a", "e", "i", "o", "u"]
word = input("Dime una palabra: ")
for letter in word:
if letter in vowels:
print(letter)
| true |
d802058971fb6d6805caf1bf4a08f9ddd8c31dcb | ksambaiah/Programming | /python/lists/listsComp.py | 434 | 4.375 | 4 | #!/usr/bin/env python3
# List comprehension is fun
if __name__ == "__main__":
# populate list with some values
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
# Get all even elements
even = [i for i in a if i % 2 == 0]
print(a)
print("Even numbers in the above list")
print(even)
mod3 = [i for i in a if i % 3 == 0]
print("Divisible by three numbers in the above list")
print(mod3)
| true |
024d2adce8e739fb8aaaedd3da198a789efc7e70 | usamayazdani/Python | /Practice/Important/codes/Q1(proper_index_in_list).py | 1,081 | 4.34375 | 4 | """function that inserts a value in
the list at its proper position (index) such that after inserting the value the list is still sorted. The list can
either be in ascending or descending order, your function should work for both types. You can write a
separate function to which would tell you in which order the list is sorted (Hint: You only have to check
the first two numbers to determine in which order the list is sorted)."""
# it must have two parameters: first the value you want to insert and second the list in
# which you want to insert the value. (You are not allowed to use the sort function of lists)
def proper_index(num,lst):
lst.append(num)
if lst[0]<lst[1]:
for i in range(0,len(lst)+1):
for j in range(i,len(lst)):
if lst[i]>lst[j]:
lst[i],lst[j] = lst[j],lst[i]
elif lst[0]>lst[1]:
for i in range(0,len(lst)+1):
for j in range(i,len(lst)):
if lst[i]<lst[j]:
lst[i],lst[j] = lst[j],lst[i]
return lst
| true |
069f6ae77c525f691cc557fe3b2ba713017e6de9 | usamayazdani/Python | /Assignments/Assignment 005/Code/code_get_comany_names.py | 1,461 | 4.25 | 4 | """function you need to write is called “get_companies”. It takes the list of
dictionaries representing companies along with a dictionary representing
location. This dictionary will have “City” and “Country” as its keys. The values of
these keys can be any strings. Your function should return a list of companies
which are located in the location provided as a dictionary to the function."""
def get_companies(company,location):
listt = []
for keyy in location: # this will take key of location that is provided
for dic in company: # this will take dictionaries from list .
for key,value in list(dic.items()): # this will make a list in which first element is key and second is value of # dictionaries and assign into variables the key to key variable and # value to value variable
if value == location[keyy]: # if value of dictionary is equal to the value of location .
listt.append(dic["Company Name"]) # than the company name of that location is assign to listt
break # if one time it is assign than this will break(stop) the loop .
if len(listt)==0: # if the length of listt is 0 than this means the location is invalid so it will return None
return 'None'
return listt # if the location is in dictionaries than this will return the list of company names .
| true |
2ebde5681e35e4dbb7233320f4bb721fa1c01685 | usamayazdani/Python | /Practice/reverse_given_number.py | 638 | 4.375 | 4 |
# This function take input from the user and than pass into the function .
# the output is the reverse of the number .
# This will run for both positive and negative integers
num = int(input("Enter any positive or negative number : "))
def reverse_a_given_integer_num(num):
if num < 0:
num = -1*num
y = str(num)
k = ""
for i in range(len(y)-1,-1,-1):
k = k+y[i]
out_num = int(k)
return out_num*-1
else:
y = str(num)
k = ""
for i in range(len(y)-1,-1,-1):
k = k+y[i]
return int(k)
reverse_a_given_integer_num(num)
| true |
a601e1cd64b8b1e77d02d22bddc50ff57b6c12ed | ZahraFarhadi19/Leetcode-practices | /Unique Email Addresses/Unique-Email-Addresses.py | 1,469 | 4.15625 | 4 | '''
Every email consists of a local name and a domain name,
separated by the @ sign.
For example, in alice@leetcode.com,
alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain '.'s or '+'s.
If you add periods ('.') between some characters in the local name
part of an email address, mail sent there will be forwarded to the
same address without dots in the local name.
For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address.
(Note that this rule does not apply for domain names.)
If you add a plus ('+') in the local name,
everything after the first plus sign will be ignored.
This allows certain emails to be filtered,
for example m.y+name@email.com will be forwarded to my@email.com.
(Again, this rule does not apply for domain names.)
It is possible to use both of these rules at the same time.
Given a list of emails, we send one email to each address in the list.
How many different addresses actually receive mails?
aA", S = "aAAbbbb"
#Output: 3
'''
class Solution:
def numUniqueEmails(self, emails):
"""
:type emails: List[str]
:rtype: int
"""
res = set()
for e in emails:
local, domain = e.split('@')[0], e.split('@')[1]
local = local.split('+')[0]
new_email = ''.join([c for c in local if c != '.']) + '@' + domain
res.add(new_email)
return len(res)
| true |
000c5f4b6aebd1b321becfaf011f4fdd70433a84 | jjnorris31/metodosNumericos | /flip_boolean.py | 497 | 4.40625 | 4 | """
Create a function that reverses a boolean value and returns the string "boolean expected" if another variable type is given.
Examples
True ➞ False
False ➞ True
0 ➞ "boolean expected"
None ➞ "boolean expected"
"""
def reverse(arg):
if type(arg) == type(0) or arg == {}:
result = "boolean expected"
else:
answersDict = {
True: False,
False: True
}
result = answersDict.get(arg, "boolean expected")
return result
| true |
b45a147939f5983102fe08ac10871675f5a99c88 | jjnorris31/metodosNumericos | /even_generator.py | 241 | 4.1875 | 4 | """
Using list comprehensions, create a function that finds all even numbers from 1 to the given number.
Examples
8 ➞ [2, 4, 6, 8]
4 ➞ [2, 4]
2 ➞ [2]
"""
def find_even_nums(num):
return [i for i in range(1, num + 1) if i % 2 == 0]
| true |
bbc409b2e9d9212d4c40e738aca76d4767ccce81 | jjnorris31/metodosNumericos | /array_of_arrays.py | 607 | 4.4375 | 4 | """
Create a function that takes three arguments (x, y, z) and returns a list containing sublists (e.g. [[], [], []]), each of a certain number of items, all set to either a string or an integer.
x argument: Number of sublists contained within the main list.
y argument Number of items contained within each sublist(s).
z argument: Item contained within each sublist(s).
Examples
3, 2, 3 ➞ [[3, 3], [3, 3], [3, 3]]
2, 1, "edabit" ➞ [["edabit"], ["edabit"]]
3, 2, 0 ➞ [[0, 0], [0, 0], [0, 0]]
""
def matrix(x, y, z):
result = []
for i in range(0, x):
result.append([z] * y)
return result
| true |
72d30654274571f5fad472c4090b8d2fd414682a | jjnorris31/metodosNumericos | /is_anagram.py | 281 | 4.15625 | 4 | """
Write a function that takes two strings and returns (True or False) whether they're anagrams or not.
Examples
'cristian', 'Cristina' ➞ True
'Dave Barry', 'Ray Adverb' ➞ True
'Nope', 'Note' ➞ False
"""
def is_anagram(s1, s2):
return sorted(s1.lower()) == sorted(s2.lower())
| true |
5fdda35bdd889857a3dfb20bf12707f03b9b6ab3 | abhigyan709/dsalgo | /OOPS_CONCEPT/OOP Principles/class_progrm_21.py | 656 | 4.28125 | 4 | # Prinitig an object
class Shoe:
def __init__(self, price, material):
self.price = price
self.material = material
s1 = Shoe(1000, "Canvas")
print(s1)
# the above print of s1 object is not in more readable format, it gives hexagonal form
# to implement the more readable format for prining the object we will use __str__ method
# let's get started to see how it works
class Shoe2:
def __init__(self, price, material):
self.price = price
self.material = material
def __str__(self):
return "Shoe with price " + str(self.price) + " and material: " + self.material
s1 = Shoe2(2000, "leather")
print(s1) | true |
feed600182879d3f19c072e7275306cc97010d4a | abhigyan709/dsalgo | /Python_basics/while_loops.py | 323 | 4.28125 | 4 | # while loop repeats a block of code as long as a particular condition remains true
# a simple value
current_value = 1
while current_value <= 5:
print(current_value)
current_value += 1
# letting the user to choose when to quit
msg = ''
while msg != 'quit':
msg = input("What's your message? ")
print(msg)
| true |
44590fe7a33d99a7a8e21a5200b78602502753ab | abhigyan709/dsalgo | /OOPS_CONCEPT/OOP Principles/class_program_20.py | 464 | 4.125 | 4 | # just like the ballons and ribbons, we can make one reference variable refer to another object.
# now any change made through this refernce varible will not affect the old object.
class Mobile:
def __init__(self, price, brand):
self.price = price
self.brand = brand
mob1 = Mobile(1000, "Apple")
mob2 = mob1
mob2 = Mobile(2000, "Samsung")
print("Mobile", "Id", "Price")
print("mob1", id(mob1), mob1.price)
print("mob2", id(mob2), mob2.price) | true |
dfca9ad207774c458ad78c9b0477d2c31cadb154 | AnoopPS02/Launchpad | /P5.py | 257 | 4.34375 | 4 | *program that asks the user for a phrase/sentence & Print back to the user the same string, except with the words in backwards order*
String="My name is Anoop"
String1=String.split()
String2=String1[::-1]
Ans=""
for i in String2:
Ans=Ans+" "+i
print(Ans)
| true |
7ce893d37b6c60644004bf0c01bbbb09d5fe194c | informramiz/Unscramble-Computer-Science-Problems | /Task1.py | 1,583 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
#A helper function to count numbers for each type of recod
def count_distinct_numbers_each(records, dictionary = {}):
distinct_numbers_count = 0
for record in records:
#first 2 recorders of either calls or texts are numbers so check each
for number in list(record[0:2]):
#only count a number if it does not exist already in the dictionary
if number not in dictionary:
distinct_numbers_count += 1
dictionary[number] = True
return distinct_numbers_count
# write a function that count the distinct numbers, to avoid code duplication
def count_distinct_numbers(calls, texts):
#a dictionary to mark numbers as counted
dictionary = {}
#count distinct numbers in calls
distinct_numbers_count = count_distinct_numbers_each(calls, dictionary)
#count distinct numbers in texts records
distinct_numbers_count += count_distinct_numbers_each(texts, dictionary)
return distinct_numbers_count
distinct_numbers_count = count_distinct_numbers(calls, texts)
print("There are %s different telephone numbers in the records." % distinct_numbers_count)
| true |
3497a9d3abc8ec8d38e813b741749ce120525950 | apugithub/MITx-6.00.1x-Programming-Using-Python | /Week-3/Hangman_Is The Word Guessed.py | 735 | 4.125 | 4 | ##### 1st Approach:
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
# FILL IN YOUR CODE HERE...
return set(secretWord) <= set(lettersGuessed)
##### 2nd Approach:
def isWordGuessed(secretWord, lettersGuessed):
if secretWord=='':
return True
for c in secretWord:
if c in lettersGuessed:
return isWordGuessed(secretWord[1:], lettersGuessed)
elif c not in lettersGuessed:
return False
| true |
e2309c0e661dd89b00106cc6d4e7131a3e342826 | JAYARAJ2014/python | /inheritance.py | 814 | 4.34375 | 4 | class Animal:
def __init__(self):
print("Animal Constructor")
self.age = 1
def eat(self):
print("Eat")
class Mammal(Animal):
def __init__(self): # THis will override the parent class constructor.
# invoke constructor of the superclass / parent class.
super().__init__()
print("Mammal Constructor")
self.weight = 3
def walk(self):
print("Walk")
class Fish(Animal):
def swim(self):
print("Swim")
m = Mammal()
m.eat()
m.walk()
print(m.age)
print(m.weight)
f = Fish()
f.eat()
f.swim()
print(m.age)
print(isinstance(f, Mammal)) # False
print(isinstance(f, Fish)) # True
print(isinstance(f, Animal)) # True
print(isinstance(f, object)) # True
issubclass(Mammal, Animal) # True
issubclass(Mammal, object) # True
| false |
db97ad39dc4c39620b3285751f375d4c75fd167a | himu999/Python_oop | /H.inheritance/c.inheritance.py | 1,092 | 4.15625 | 4 | class Vehicle:
"""Base class for all vehicles"""
def __init__(self, name, manufacturer, color):
self.name = name
self.color = color
self.manufacturer = manufacturer
def drive(self):
print("Driving", self.manufacturer, self.name)
def turn(self, direction):
print("Turning", self.name, direction)
def brake(self):
print(self.name, "is stopping!")
class Car(Vehicle):
"""Car class"""
def __init__(self, name, manufacturer, color, year):
super().__init__(name, manufacturer, color)
self.name = name
self.manufacturer = manufacturer
self.color = color
self.year = year
self.wheels = 4
print("A new car has been created. Name:", self.name)
print("It has", self.wheels, "wheels")
print("The car was built in", self.year)
def change_gear(gear_name):
"""Method of changing gear"""
print(self.name, "is changing gear to", gear_name)
if __name__ == "__main__":
c = Car("Afnan GT 5.0 ", "N&R CC", "RED", 2015)
| true |
e730a2f4f5e0e752cb6304b604366dbce9d6ac12 | Jbranson85/Python | /drawface.py | 1,142 | 4.15625 | 4 | '''
drawface.py
Jonathan Branson, 3/27/17
This program will draw a face that has 2 eyes, nose and a mouth, by using the
tkinter mondule to draw the shapes on a canvas
'''
from tkinter import *
##Builds Frame
root = Tk()
##Creates the Canvas, for shapes to be drawn on
background = Canvas(root, width = 525, height = 525, bg = "yellow")
##Draws the Head using a circle
head = background.create_oval(25,25,500,500, fill="purple")
##Draws the left eye using 2 circles
eye_1 = background.create_oval(125,105,220,200, fill = "white")
innereye_1 = background.create_oval(160,140,180,160, fill = "green")
##Draws the right eye using 2 circles
eye_2 = background.create_oval(285,105,385,200, fill = "white")
innereye_2 = background.create_oval(325,140,345,160, fill = "green")
##Draws the mouth using a arc
mouth = background.create_arc(125,300,385,450, start = 0, extent = -180, fill = "black")
##Draws the nose with 2 lines
nose_1 = background.create_line(250,200,185,325)
nose_2 = background.create_line(185,325,260,325)
##Packs the Canvas
background.pack()
##Loops main program
root.mainloop()
| true |
45f38da8b7407cfb94885ddfc4f843e945167bf8 | 666sempron999/Abramyan-tasks- | /Series(40)/18.py | 717 | 4.15625 | 4 | """
Series18. Дано целое число N и набор из N целых чисел, упорядоченный
по возрастанию. Данный набор может содержать одинаковые элементы.
Вывести в том же порядке все различные элементы данного набора.
"""
import random
resultList = list()
N = int(input("Введите число элементов - "))
for x in range(0,N):
resultList.append(random.randint(0, 10))
print(resultList)
resultList.sort()
print("_______________________________")
print(resultList)
print("_______________________________")
print(set(resultList))
| false |
721ac2a3f410a889ab412752fd7db8b26456f6e1 | 666sempron999/Abramyan-tasks- | /Begin(40)/21.py | 1,115 | 4.125 | 4 | '''
Даны координаты трех вершин треугольника: (x 1 , y 1 ), (x 2 , y 2 ), (x 3 , y 3 ).
Найти его периметр и площадь, используя формулу для расстояния меж-
ду двумя точками на плоскости (см. задание Begin20). Для нахождения
площади треугольника со сторонами a, b, c использовать формулу Герона:
S =
√ p·(p − a)·(p − b)·(p − c),
где p = (a + b + c)/2 — полупериметр.
'''
x1 = int(input("Введите x1: "))
y1 = int(input("Введите y1: "))
x2 = int(input("Введите x2: "))
y2 = int(input("Введите y2: "))
x3 = int(input("Введите x3: "))
y3 = int(input("Введите y3: "))
a = pow((pow((x2-x1),2) + pow((y2-y1),2)),(1/2))
b = pow((pow((x3-x2),2) + pow((y3-y2),2)),(1/2))
c = pow((pow((x3-x1),2) + pow((y3-y1),2)),(1/2))
p = (a+b+c)/2
S = pow(
p*(p-a)*(p-b)*(p-c)
,(1/2))
print(a)
print(b)
print(c)
print("S = ", S)
| false |
97db6409c609d5f3c1aa4955fdd6c1face2762b1 | 666sempron999/Abramyan-tasks- | /Boolean(40)/29.py | 913 | 4.34375 | 4 | '''
Boolean29 ◦ . Даны числа x, y, x 1 , y 1 , x 2 , y 2 . Проверить истинность высказыва-
ния: «Точка с координатами (x, y) лежит внутри прямоугольника, левая
верхняя вершина которого имеет координаты (x 1 , y 1 ), правая нижняя —
(x 2 , y 2 ), а стороны параллельны координатным осям».
'''
x = int(input("Введите x: "))
y = int(input("Введите y: "))
print('Вершина 1')
x1 = int(input("Введите x1: "))
y1 = int(input("Введите y1: "))
print('Вершина 2')
x2 = int(input("Введите x2: "))
y2 = int(input("Введите y2: "))
flag = True
if x2 > x1 and y2 < y1:
if (x >= x1 and x <= x2) and (y >= y1 and y <= y2):
pass
else:
flag = False
print(flag) | false |
d59cba0dd4e09ea0217dbabeea96034229437e00 | 666sempron999/Abramyan-tasks- | /For(40)/39.py | 680 | 4.125 | 4 | '''
For39. Даны целые положительные числа A и B (A < B). Вывести все целые
числа от A до B включительно; при этом каждое число должно выводиться
столько раз, каково его значение (например, число 3 выводится 3 раза).
'''
A = int(input("Введите A "))
B = int(input("Введите B "))
while A > B:
A = int(input("Введите A "))
B = int(input("Введите B "))
counter = A
for i in range(1,(B - A)+2):
for j in range(1,counter+1):
print(counter)
print('---------')
counter += 1
| false |
9e47d26e85a5071ba3860247c5f69e0ab27bafa7 | binnllii/classprojects | /cis122 HW/P4_while1.py | 267 | 4.3125 | 4 | hint = "Enter name of country or 'Quit':"
country_list = [ ]
nation = input(hint)
while nation != 'Quit':
country_list.append(nation)
nation = input(hint)
print()
print('Countries')
for country in country_list:
print(country)
print()
print('Finished')
| false |
3d3a23a1023bc4abee851a683211f05730818597 | binnllii/classprojects | /cis122 HW/P2_list.py | 283 | 4.125 | 4 | majors_list = ["Computer Science", "Biology", "Journalist", "Business", "Chemistry"]
n_majors = len(majors_list)
print('There are', n_majors, 'majors in my list.')
print(" ")
print("Majors")
for n_majors in majors_list:
print(" ", n_majors)
print("--------")
print("Finished")
| false |
ac7d3d379427f91dc20dc11731723ec3ecce0d36 | DaveRichmond-/sabine_learn_to_code | /pfk_exercises/review_chpt1_8.py | 1,913 | 4.21875 | 4 | # Chapter 2: Variables --------------->
# how much money would you have in your piggy bank, if you had 7 one dollar bills, 34 quarters, 71 dimes, 112 nickels and 42 pennies?
# create an equation below to calculate the result and store it in a variable called TOTAL.
# you can use the variables that I created for you:
value_penny = 0.01
value_nickel = 0.05
value_dime = 0.10
value_quarter = 0.25
value_dollar = 1.0
# TOTAL =
# Chapter 3: Strings, Lists, Tuples and Dictionaries --------------->
# create a string in a variable called STRING_1
# STRING_1 =
# create another string that contains an apostrophe
# STRING_2 =
# create a string that contains the number stored in the variable MY_NUMBER (hint: you need to convert the number to a string as well)
MY_NUMBER = 3.1415
# STRING_3 =
# create a list containing both strings and numbers
# LIST_1 =
# create a list containing another list
# LIST_2 =
# create a list, and then assign the variable MY_VARIABLE to the first position in the list
MY_VARIABLE = 'testing, 123'
# LIST_3
# create two lists and the "append" them and assign the result to a new list
# LIST_4 =
# LIST_5 =
# LIST_6 =
# create a tuple
# TUPLE_1 =
# create a dictionary containing at least three key:value pairs
# DICT_1 =
# Chapter 4+6: If / Else statements + Functions --------------->
# write a function called FIGHT_OR_FLIGHT that takes a single input variable called INPUT_1. If INPUT_1 is "monster" then it returns "FIGHT". If INPUT_1 is "dragon" then it returns "FLIGHT". And if INPUT_1 = "pbj" then it returns "EAT".
# Chapter 5+6: Loops + Functions --------------->
# write a function called LIST_COUNTER that takes a single input variable called INPUT_LIST and adds up all of the numbers contained in the list (using a for loop).
# write a function called SUM_TO_1000 that returns the sum of every number from 1 to 1000 (using a while loop).
| true |
ecbef1dd6f3e8539940512a81a88dfdeeb130c7d | zeeshan13026/PythonRefresher | /14_destructuring_variables/code3.py | 280 | 4.125 | 4 | people = [('Bob', 42, 'Mechanic'), ('James', 24, 'Artist'),('Harry', 32, 'Lecturer')]
for name, age, job in people:
print(f"{name} is {age} year old and working as a {job}")
for person in people:
print(f"Name : {person[0]}, Age : {person[1]}, Profession : {person[2]} ") | false |
6cb8ca0e88370851e98b55c3778747352feb172e | ectrimble20/PythonExerciseCode | /PracticePython/ElementSearch.py | 2,609 | 4.1875 | 4 | # ElementSearch.py
import random
"""
Write a function that takes an ordered list of numbers (a list where the elements are in order from smallest to
largest) and another number. The function decides whether or not the given number is inside the list and
returns (then prints) an appropriate boolean.
Extras:
Use binary search.
"""
elements = random.randint(40, 100)
e_list = list(set([random.randint(0, 100) for n in range(0, elements)]))
"""
e_list = []
for _ in range(0, elements):
n = random.randint(0, 100)
e_list.append(n)
e_list = list(set(e_list)) # convert and sort
"""
e_list.sort() # make sure it's sorted
s_element = random.randint(0, len(e_list))
# print("Random List:", e_list)
print("Random List: {}".format(e_list))
# print("Random element:", s_element, "Value: ", e_list[s_element])
print("Random element: {} => Value: {}".format(s_element, e_list[s_element]))
def binary_search(search_for: int, search_in: list) -> object:
"""
This is a binary search function for a list of sorted integer values. It follows the following steps to quickly
search the list in a half-interval search pattern.
Step 1: Set Left-Index to 0, Set Right-Index to search_in length minus 1 (n-1)
Step 2: Check if Left-Index is greater than Right-Index, if so, return -1, not found in the list
Step 3: Set Middle-Index to the floor of Left-Index + Right-Index divided by 2 ((L+R)//2)
Step 4: If Value At Middle-Index is less than search Value, set Left-Index to Middle-Index + 1, Go to Step 2
Step 5: If Value at Middle-Index is greater than search Value, set Right-Index to Middle-Index - 1, Go to Step 2
Step 6: If Value at Middle-Index equals search Value, return Middle-Index
:param search_for: int we're searching for
:param search_in: list of sorted ints to search
:return: int index (-1 if not found)
"""
step = 0
l = 0
r = len(search_in) - 1
while True:
# print("Debug:step:L:R:", step, l, r)
step += 1
if l > r:
print("l > r, no result")
return -1
m = (l + r) // 2
# print("M::", m)
# Start binary search
if search_in[m] == search_for:
return m
if search_in[m] < search_for:
l = m + 1
else:
r = m - 1
res = binary_search(s_element, e_list)
if res is not -1:
print("Found {} at index {}".format(s_element, res))
# print("Found", s_element, "at index", res)
else:
print("Did not find {} in the list".format(s_element))
# print("Did not find", s_element, "in the list")
| true |
502405c48c8a71d517817d1074c1ad766a99ead8 | ectrimble20/PythonExerciseCode | /PracticePython/Divisors.py | 689 | 4.34375 | 4 | # Divisors.py
"""
Create a program that asks the user for a number then prints out a list of all the divisors of that number
...divisor is a number that divides evenly into another number, ex 13 is a divisor of 26 because 26 % 13 == 0
"""
num = int(input("Enter a number to get it's divisors: "))
l = []
# for n in range(1, num): -- we need to add 1 to the range in order to ensure we check itself
for n in range(1, num+1):
if num % n == 0:
l.append(n)
# print("Divisors of", num, "are", l)
print("Divisors of {} are {}".format(num, l))
print("One liner attempt:")
print("[n for n in range(1, num+1) if num % n == 0]")
print([n for n in range(1, num+1) if num % n == 0])
| true |
176f1237183f9733598b42ef847ce809c188da52 | samarla/LearningPython | /fibonacci.py | 385 | 4.40625 | 4 | user_input = int(input('enter how many fibonacci numbers to be printed (not less than 3): \n'))
fibonacci = [1, 1]
def append_fibonacci(n):
"""this function appends the next fibonacci element into the list """
next_number = fibonacci[n-1]+fibonacci[n-2]
fibonacci.append(next_number)
for i in range(2, user_input):
append_fibonacci(len(fibonacci))
print(fibonacci) | true |
c7a67c23b2aae88e039c045f3dae89fe6b372e5e | samarla/LearningPython | /factorial using function.py | 289 | 4.25 | 4 | number = int(input('enter any number: '))
def factorial(n):
if n == 1: # The termination condition
return 1 # The base case
else:
res = n * factorial(n-1) # The recursive call
return res
print('the factorial of given number is: ',factorial(number))
| true |
e7847ad5d3351a90a5728fa84f6657f830663cec | mokpolar/FluentPython | /ch12_MixedIn.py | 1,451 | 4.1875 | 4 | """
Python MixedIn 클래스에만 다중 상속을 사용
http://brownbears.tistory.com/149
"""
class ToDictMixin:
def to_dict(self):
""" __dict__ 은 상속받은 value에 대해 dict타입으로 보여줌"""
print("to_dict", self.__dict__)
return self._traverse_dict(self.__dict__)
def _traverse_dict(self, instance_dict):
output = {}
for key, value in instance_dict.items():
output[key] = self._traverse(key, value)
return output
def _traverse(self, key, value):
""" isinstance를 사용한 동적 타입 검사, 인스턴스 딕셔너리 __dict__를 이용한 클래스"""
if isinstance(value, ToDictMixin):
print("case 1")
return value.to_dict()
elif isinstance(value, dict):
print("case 2")
return self._traverse_dict(value)
elif isinstance(value, list):
print("case 3")
return [self._traverse(key, i) for i in value]
elif hasattr(value, '__dict__'):
print("case 4")
return self._traverse_dict(value.__dict__)
else:
print("case 5")
return value
class BinaryTree(ToDictMixin):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
tree = BinaryTree(10, left=BinaryTree(7, right=BinaryTree(9)))
print(tree.to_dict())
| false |
3b4b7774719a9a625ac876df22fa0c8240f4b543 | SonoDavid/python-ericsteegmans | /CH7_lists/indexSmallest.py | 1,080 | 4.40625 | 4 | def index_smallest_of(sequence, start=0):
"""
Return the position of the smallest element in the
given sequence starting from the given position.
- If several smallest elements can be found, the
function return the position of te leftmost
smallest element.
- None is return if no such smallest element can be
found.
"""
if (start < 0) or (start >= len(sequence)):
return None
ind_smallest = start
ind_current = start+1
while ind_current < len(sequence):
if sequence[ind_current] < sequence[ind_smallest]:
ind_smallest = ind_current
ind_current += 1
return ind_smallest
assert index_smallest_of((77, -20, -4, 100), 0) == 1
assert index_smallest_of((-9, 4, -20, -20, 1, -20, -1), 1) == 2
assert index_smallest_of((-300, -20, -4, 100), 0) == 0
assert index_smallest_of((-80, -20, -4, -100), 2) == 3
assert index_smallest_of("cbabc", 0) == 2
assert index_smallest_of((), 0) == None
assert index_smallest_of((1, 2, 3), 3) == None
assert index_smallest_of((1, 2, 3), -1) == None | true |
999b4c25b114ca8354eac7a2d3f4ea6ad6c18512 | SonoDavid/python-ericsteegmans | /CH4_strings/calc_num_digits.py | 504 | 4.34375 | 4 | # Calculate the sum of the digits in an integer number
# in decimal format
# - The program keeps on prompting for a non-negative
# integer number until it finally gets one
number = ""
while not str.isdigit(number):
number = input\
("Enter a non-negative number: ")
digit_sum = 0
current_pos = 0
while current_pos < len(number):
digit_sum += ord(number[current_pos]) - ord("0")
current_pos += 1
print("The sum of the digits of the number",\
number,"amounts to",digit_sum) | true |
3d390d7d50f009bf9aaa30677332ed3d637a44d5 | SonoDavid/python-ericsteegmans | /CH1_integer_arithmetic/leapyear.py | 411 | 4.28125 | 4 | # Check whether a given year is a leap year.
# A year is a leap year if it is a multiple of 4 and
# not a multiple of 100, or it is a multiple of 400.
#
# Author: Joachim David
# Date: June 2019
year = int(input("Enter the year to examine: "))
if ((year % 4 == 0) and not (year % 100 == 0)) or (year % 400 == 0):
print(f'The year {year} is a leap year!')
else:
print(f'The year {year} is not a leap year!') | true |
31f9ea558320ac9863922444f2782c760d4e9369 | mpreddy960/pythonPROJECTnew | /padma/os_module.py | 2,570 | 4.125 | 4 | #chage current path using : chdir()
import os
# Functio to Get the current
# working directory
def current_path():
#print("Current working directory before")
print(os.getcwd())
print()
# Driver's code
# Printing CWD before
print("current working directory before")
current_path()
# Changing the CWD
os.chdir('../')
# Printing CWD after
print("current working directory after")
current_path()
#create a path using : mkdir()
import os
cwd = os.getcwd()
print("print cwd:",cwd)
#using : makedirs()
directory_new_path = "venkataravana"
bn = os.getcwd()
print("print now path :",bn)
d = bn+ "/reddy/lugs/klm/"
concatenate = os.path.join(d,directory_new_path)
print("print concatenate new path :",concatenate)
#os.makedirs(concatenate)
print("created new path venkataravana :",directory_new_path)
## Python program to explain os.mkdir() method
# importing os module
# import os
#
# Directory
try:
directory = "GeeksforGeeks34"
parent_dir = os.getcwd()
print("print getcwd:",parent_dir)
# Parent Directory path
#parent_dir = "D:/Pycharm projects/"
# Path
path = os.path.join(parent_dir, directory)
print("print path :",path)
os.mkdir(path)
# print("Directory '% s' created" % directory)
print("created directory:",directory)
except FileExistsError:
pass
#mkdir(created new path
import os
try:
directory = "reddymalapati"
vc = os.getcwd()
print(vc)
n = os.path.join(vc,directory)
print("print join vc path :",n)
os.mkdir(n)
print(print("created directory :",directory))
except FileExistsError:
print("file already exist")
#second directory
# # Directory
# directory = "Geeks"
#
# # Parent Directory path
# parent_dir = "D:/Pycharm projects"
#
# # mode
# mode = 0o666
#
# # Path
# path = os.path.join(parent_dir, directory)
#
# # Create the directory
# # 'GeeksForGeeks' in
# # '/home / User / Documents'
# # with mode 0o666
# os.mkdir(path, mode)
# print("Directory '% s' created" % directory)
#using listdir
import os
cx = "/"
cv = os.listdir(cx)
print("print listdir :",cx," :")
print("print cv :",cv)
import os
# Get the list of all files and directories
# in the root directory
path = "/"
dir_list = os.listdir(path)
print("Files and directories in '", path, "' :")
# print the list
print(dir_list)
#using remove
file = "a.txt"
nm = os.getcwd()
print("file location :",nm)
xc = os.path.join(nm,file)
#os.remove(xc)
# exmple
# file = 'file1.txt'
# # File location
# location = "D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/"
# # Path
# path = os.path.join(location, file)
# # Remove the file
# # 'file.txt'
# os.remove(path) | false |
ae60d94e8142658451e6f87f8d7f0c72d485eb2c | mpreddy960/pythonPROJECTnew | /list_functions.py | 1,036 | 4.375 | 4 | # Python program to print positive numbers in a list
fig = [6,5,5,4,3,-7,-8,-9,4]
print(fig)
f = []
def get_ele(fig):
"""teddyjjjj"""
for ty in fig:
if ty >=0:
f.append(ty)
print(ty, end=',')
return f
# first to last element
g = get_ele(fig)
print(get_ele.__doc__)
print(g)
f = [2,4,3,2,4,2,3,4]
print(f)
k = f[::-1]
print(k)
# Python program to print all positive numbers in a range
start,end = -2,20
for doll in range(start,end):
if doll >= 0:
print(doll,end=',')
# Python program to print all negative numbers in a range
python,pythonjob = -10,28
for jobsettle in range(python,pythonjob):
if jobsettle < 0:
print(jobsettle,end=',')
# Remove multiple elements from a list in Python
# list1 = [11, 5, 17, 18, 23, 50]
#
# for ele in list1:
# if ele % 2 == 0:
# list1.remove(ele)
# print("New list after removing all even numbers: ", list1)
# Output:
# Python – Remove empty List from List
testlist = [1,2,3,[],[],5,6,7]
print(testlist)
| false |
0f42460db3ed7c9ea2ae8c7f5d79f781d787c936 | 1141938529/ClassExercises | /week01/day02/OrdChr.py | 566 | 4.1875 | 4 | # 使用ord函数找出1,A,B,a,b的ascII码
print("1的ASCII码为:",ord('1'))
print("A的ASCII码为:",ord('A'))
print("B的ASCII码为:",ord('B'))
print("a的ASCII码为:",ord('a'))
print("b的ASCII码为:",ord('b'))
# 使用chr函数找出40,59,79,85 90 所对应的字母
print("----------------")
c = 40
print("40的ASCII码为:",chr(40))
print(str(c)+"的ASCII码为:",chr(c))
def Ascll(c):
print(str(c) + "的ASCII码为:", chr(c))
def main():
Ascll(40)
Ascll(59)
Ascll(79)
Ascll(85)
Ascll(90)
main()
| false |
6ed5fe4e0dfce4016edc2301039318c74e91f344 | 1141938529/ClassExercises | /week01/day03/03hk2.12.py | 866 | 4.125 | 4 | # 打印表格
import math
print(format("a", "<8s"), end=(""))
print(format("b", "<8s"), end=(""))
print("a ** b")
for i in range(5):
print(format(i+1,"<8d"),end=(""))
print(format(i + 2, "<8d"),end=(""))
print(format((i+1)**(i+2), "<8d"))
# 2.13 分割数字
value = eval(input("enter an integer:"))
qian = value//1000
bai = (value-qian*1000)//100
shi = (value-qian*1000-bai*100)//10
ge = (value-qian*1000-bai*100-shi*10)
print(ge)
print(shi)
print(bai)
print(qian)
# 三角形的面积
x1,y1,x2,y2,x3,y3 = eval(input("enter three points for a"
" triangle:") )
def Sidess(x1,y1,x2,y2):
sides = math.sqrt((x2-x1)**2+(y2-y1)**2)
return sides
s1 = Sidess(x1,y1,x2,y2)
s2 = Sidess(x3,y3,x2,y2)
s3= Sidess(x1,y1,x3,y3)
s=(s1+s2+s3)/2
area =math.sqrt(s*(s-s1)*(s-s2)*(s-s3))
print("the area is ",format(area,".1f"))
| false |
801faa729dc97d01fc50f8bf3a112f56777a6689 | EmpowerSecurityAcademy/daily_exercises | /lambda_operator/lambda_operator.py | 610 | 4.3125 | 4 | # list comprehensions follow the format
# [dosomething(num) for num in array if some_condition_is_true]
# use a list comprehension to return only even numbers
def even_numbers(array_numbers):
return [num for num in array_numbers if num % 2 == 0]
# use list comprehension to return words starting with the letter "a"
def start_with_a(array_strings):
return [s_str for s_str in array_strings if s_str[0] == 'a']
# use list comprehension to multiply by 11 numbers that are divisable by 3
def multiply_by_11_numbers_divisable_by_three(array_numbers):
return [num*11 for num in array_numbers if num % 3 == 0] | true |
720f47b5f02345025baf6102fa5b1550003e35fd | tainenko/gliacloud | /part1/Counting.py | 1,631 | 4.15625 | 4 | '''
Counting
Given a list of urls, print out the top 3 frequent filenames.
ex.
Given
urls = [
"http://www.google.com/a.txt",
"http://www.google.com.tw/a.txt",
"http://www.google.com/download/c.jpg",
"http://www.google.co.jp/a.txt",
"http://www.google.com/b.txt",
"https://facebook.com/movie/b.txt",
"http://yahoo.com/123/000/c.jpg",
"http://gliacloud.com/haha.png",
]
The program should print out
a.txt 3
b.txt 2
c.jpg 2
'''
import operator
def get_file_name(str):
'''
輸入str,回傳檔案string
:param str:
:return filename:
'''
return str.split('/')[-1]
def count_the_files(urls):
'''
統計url list中file出現次數,回傳dict
:param urls:
:return dict:
'''
dct={}
for url in urls:
file=get_file_name(url)
dct[file]=dct.get(file,0)+1
return dct
def get_top_3_file(dct,n=3):
'''
從統計的dct中取得出現次數前三筆的檔案字串
:param dct:
:return list:
'''
lst=[]
for i in range(n):
key=max(dct.items(), key=operator.itemgetter(1))[0]
lst.append('{} {}'.format(key,dct[key]))
del dct[key]
return lst
if __name__=='__main__':
urls = [
"http://www.google.com/a.txt",
"http://www.google.com.tw/a.txt",
"http://www.google.com/download/c.jpg",
"http://www.google.co.jp/a.txt",
"http://www.google.com/b.txt",
"https://facebook.com/movie/b.txt",
"http://yahoo.com/123/000/c.jpg",
"http://gliacloud.com/haha.png",
]
dct=count_the_files(urls)
lst=get_top_3_file(dct)
for l in lst:
print(l)
| false |
d78278d86a8e2b522e1845cb876fb9f9c85132f9 | flavienfr/bootcamp_ml | /day00/ex00/sum.py | 547 | 4.1875 | 4 | def sum_(x, f):
"""Computes the sum of a non-empty numpy.ndarray onto wich a function is
applied element-wise, using a for-loop.
Args:
x: has to be an numpy.ndarray, a vector.
f: has to be a function, a function to apply element-wise to the
vector.
Returns:
The sum as a float.
None if x is an empty numpy.ndarray or if f is not a valid function.
Raises:
This function should not raise any Exception.
"""
if x.size == 0 or not f:
return None
total = 0.0
for value in x:
total += f(value)
return total | true |
8e4a98d01dafe2d5845a965a2f2e4ba3456bbbcb | sanyamb22/python-101 | /insertionSortAlgo.py | 1,132 | 4.34375 | 4 | # INSERTION SORT ALGORITHM
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key <= arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
# driver code
arr = [12, 11, 13, 8, 10]
print("array before sorting :",arr)
insertionSort(arr)
print("sorted array is :", arr)
# for i in range(len(arr)):
# print(arr[i])
# OTHER IMPLEMENTATION
# def insertion_sort(list_a):
# indexing_length = range(1, len(list_a))
# for i in indexing_length:
# value_to_sort = list_a[i]
# while list_a[i-1] > value_to_sort and i > 0:
# list_a[i], list_a[i-1] = list_a[i-1], list_a[i]
# i = i -1
# return list_a
# print(insertion_sort([7,8,9,8,7,6,5,6,7,8,9,8,7,6,5,6,7,8]))
# def insSort(arr):
# for i in range(1, len(arr)):
# key = arr[i]
# j = i - 1
# while arr[j] >= key and j >= 0:
# arr[j], arr[i] = arr[i], arr[j]
# j = j - 1
# arr[j+1] = key
# arr = [4, 8, 6, 7, 10, 44, 15]
# print(arr)
# insSort(arr)
# print(arr)
| false |
d48bd9fab26d6876b882c9cb209a102e83d00a4a | Ciwonie/python_cs150 | /cs150/week_6/project_2.py | 1,472 | 4.34375 | 4 | # This project works with while loops and inputs . Your program will generate a random value, and ask for your guess.
# Upon submitting your guess, the program will return back if your guess is too high or too low.
# This will continue until you guess the correct number in which the program will output:
# "Correct congratulations you answered in xx number of guess" . The program will then print out all of your guesses."
# Author: Jonathan E. Cirone @ 24 Feb 19
import random
print('Welcome to GuessTen')
def guessChecker(myGuess):
numbersGuessed = []
attempts = 0
while True:
try:
randomNumber = random.randint(1, 10)
userGuess = int(input(myGuess))
if userGuess < 1 or userGuess > 10:
print('Invalid Range\n')
continue
except ValueError:
print('Invalid \n')
continue
else:
if userGuess != randomNumber:
numbersGuessed.append(userGuess)
attempts += 1
continue
else:
numbersGuessed.append(userGuess)
attempts += 1
print("***You guessed correctly!***")
print("Congratulations, here are your attempts: {} ".format(attempts))
print('These were your guessed numbers: {}'.format(numbersGuessed))
break
myGuess = guessChecker('Please guess a number [1-10]: \n')
# edited: JEC @ 2342
| true |
9f25a9044a4f76db8a928a63f48864c62a383bfb | yangroro/gitpractice2 | /예제1.py | 250 | 4.125 | 4 | def is_odd(number):
if number % 2 == 1: # 2로 나누었을떄 나머지가 1이면 홀수이다.
return True
else:
return False
is_odd(3)
True
is_odd(4)
False
is_odd = lambda x: True if x % 2 == 1 else False
is_odd(3)
True
| false |
233a31e57427b5f4b0566215076380cd209a0365 | jatinsumai1104/Essence | /ml_model/text-module/readCsv.py | 1,501 | 4.125 | 4 | # importing csv module
import csv
# csv file name
filename = "aapl.csv"
# initializing the titles and rows list
fields = []
rows = []
# reading csv file
with open(filename, 'r') as csvfile:
# creating a csv reader object
csvreader = csv.reader(csvfile)
# extracting field names through first row
fields = next(csvreader)
# extracting each data row one by one
for row in csvreader:
rows.append(row)
# printing the field names
print('Field names are:' + ', '.join(field for field in fields))
# printing first 5 rows
diseases = []
Dict1 = {}
Dict2 = {}
for row in rows[:11]:
# parsing each column of a row
i=0
symptoms = []
for col in row:
if(i==0):
diseases.append(col)
i=i+1
else:
if(col!=''):
symptoms.append(col.lower())
Dict1[diseases[-1]] = symptoms
Dict2[diseases[-1]] = 0
print('Diseases and Symptoms:')
print(Dict1)
print('\n')
print('Enter all symptoms:')
print('Press q to quit')
while True:
x=input()
if(x=='q'):
break
else:
for disease in Dict1:
if(x.lower() in Dict1[disease]):
Dict2[disease] = Dict2[disease] + 1
print('Count of all symptoms in each disease:')
print(Dict2)
for x in Dict2:
Dict2[x] = Dict2[x]/11
print('Probability')
print(Dict2)
| true |
62542722f9abba4f0eb97acce6c5a3b32bc95637 | erdemgokmuharrem/basic-python-projects | /celToFahrenheit.py | 686 | 4.34375 | 4 | print("-" * 30)
print("1- Celsius to fahrenheit")
print("2- Fahrenheit to celsius")
print("-" * 30)
choice = input("Your choice (1/2): ")
if choice == "1":
print("\n# Celsius to Fahrenheit")
celsius = float(input("Degree to convert: "))
fahrenheit = (celsius * 1.8) + 32
print("{} degree celsius is equal to {} degree fahrenheit.".format(celsius, fahrenheit))
elif choice == "2":
print("\n# Fahrenheit to Celsius")
fahrenheit = float(input("Degree to convert: "))
celsius = (fahrenheit - 32) / 1.8
print("{} degree fahrenheit is equal to {} degree celsius.".format(fahrenheit, celsius))
else:
print("Congratulations! You hacked the super-program.") | false |
408c8ed4a32e24c280f71baeb9a42c613a4269cc | rogermanzo99/Python-Ejercicios | /Calculadora/calculadora.py | 1,375 | 4.375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
while True:
print("Presione '1' para realizar una suma")
print("Presione '2' para realizar una resta")
print("Presione '3' para realizar una multiplicacion")
print("Presione '4' para realizar una division")
print("Presione '5' para salir de la calculadora ")
user = input("")
user = int(user)
if user == 1:
print ("Ingrese el primer digito: \n")
a = input("")
print ("Ingrese el segundo digito: \n")
b = input("")
operacion = float(a + b)
resultado = (operacion)
print ("El resultado de la suma es %s" %(resultado))
elif user == 2:
print("Ingrese el primer digito:")
a = input("")
print("Ingrese el segundo digito:")
b = input("")
operacion = float(a - b)
resultado = (operacion)
print ("El resultado de la resta es %s" %(resultado))
elif user == 3:
print("Ingrese el primer digito:")
a = input("")
print("Ingrese el segundo digito:")
b = input("")
operacion = float(a * b)
resultado = (operacion)
print ("El resultado de la multiplicación es %s" %(resultado))
elif user == 4:
print("Ingrese el primer digito:")
a = input("")
print("Ingrese el segundo digito:")
b = input("")
operacion = float(b / a)
resultado = (operacion)
print ("El resultado de la división es %s" %(resultado))
elif user == 5:
print("Gracias por usar nuestra calculadora")
break | false |
d0dfb47058916c53ec30d41696a076a2d7430773 | devichandanpati/python | /conditionals_13.py | 669 | 4.28125 | 4 | week = [(0,"Sunday"), (1,"Monday"), (2,"Tuesday"), (3,"Wednesday"), (4,"Thursday"), (5,"Friday"), (6,"Saturday")]
x = int(input("Enter number for a week day between 0-6"))
for number,day in week :
if x == 0 :
print("Day is Sunday")
break
elif x == 1 :
print ("Day is Monday")
break
elif x == 2 :
print("Day is Tuesday")
break
elif x == 3 :
print("Day is Wednesday")
break
elif x == 4 :
print("Day is Thursday")
break
elif x == 5 :
print("Day is Friday")
break
elif x == 6 :
print("Day is Saturday")
break
| true |
463f670913fdbbe42ac74b8478e3e4ed2aafbf40 | devichandanpati/python | /functions_20.py | 624 | 4.25 | 4 | def turn_clockwise(direction) :
direction = str(input("Enter direction"))
if direction == "N" :
print("Direction is E")
direction == "E"
return direction
elif direction == "E" :
print("Direction is S")
direction == "S"
return direction
elif direction == "S" :
print("Direction is W")
direction == "W"
return direction
elif direction == "W" :
print("Direction is N")
direction == "N"
return direction
print(turn_clockwise("E"))
| true |
200221ac7d1f59d0a140b1fe4ac8e9f7e9df6f28 | devichandanpati/python | /functions_30.py | 270 | 4.21875 | 4 | def slope(x1,y1,x2,y2) :
value = (y1-y2) / (x1 - x2)
return value
x1 = int(input("Enter value for x1 :"))
y1 = int(input("Enter value for y1 :"))
x2 = int(input("Enter value for x2 :"))
y2 = int(input("Enter value for y2 :"))
print(slope(x1,y1,x2,y2))
| false |
151d2bfe1877203953f52be0bfb297baf40a1697 | IIKovalenko/Python_Study | /Input&Output.py | 2,948 | 4.28125 | 4 | #I/O
#python中两种输出值的方式:表达式语句 和 print()函数, 第三种是使用文件对象的write()
#函数,标准输出文件可以使用sys.stdout引用
s = "Hello, World";
print(str(s));
print(repr(s));#打印出来有单引号 'Hello, World'
#repr()可以不转义特殊字符,原样输出
hello = "Hello\n";
print(hello);
print(r"Hello\n");
print(repr(hello));
#repr()参数可以使任何对象
print(repr(('1', "2", (1, 2))));
#两种方式打印出平方立方表
#第一种方式
for x in range(1, 11):
print(repr(x).rjust(2), repr(x*x).rjust(3), end=" ");
print(repr(x*x*x).rjust(4));
#第二种方式
for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x));
#rjust() ljust() zfill()用法
print("abcdef".rjust(10));
print("abcdef".ljust(10));
print("abcdef".center(10));
print("abcdef".zfill(10));
print(str(5).zfill(10));
#format格式化输出
print("{0:03d}".format(2));
print("{0:03d}".format(20));
print("{0:03d}".format(123));
print("{0:0f}".format(2.2));
formatStr = "{0:2d} {1:2f} {2:2s}";
print(formatStr.format(10, 20, "200"));
print("{} and {}".format("I", "you"));
#format指定关键字参数
print("This is {food} and {fruit}".format(food = "milk", fruit = "apple"));
print("Hello, Welcome {1}, {middle}, {0}".format("Tom", "Georg", middle="Tony"));
import math
print("PI is {0:.3f}".format(math.pi));
#在 ':' 后传入一个整数, 可以保证该域至少有这么多的宽度
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
print("{0:10} ===> {1:10d}".format(name, phone));
#旧式格式化字符串
print("PI is %.3f"%math.pi);
#文件
#读写文件
#opne()将返回一个file对象 open(filename, mode)
f = open("f.txt", 'r+');
str = f.read();#read all content, read(size)
print("The content of the file is :", str);
#move file pointer to start
f.seek(0);
str = f.read(2);
print("The first 2 byte is :", str);
f.seek(0);
str = f.readline();
print("The first line is :", str);
#wirte
count = f.write("\n3.Hello, DUT!\n");
print("The count of char wrote is ", count);
f.close();
#seek(offset, from_what) from_what 0开头位置 1当前位置 2结尾位置
#-----------------------pickle模块----------------------------
#python的pickle模块实现了基本的数据序列和反序列化
#通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中,永久存储
#反之亦然
#基本接口 pickle.dump(obj, file, [, protocol])
#使用pickle模块将数据对象保存到文件
import pickle
obj = {'a':[1, 2.0, 3, 4+6j],
'b':("string", u"Unicode string"),
'c':None
};
print(type(obj));
output = open('obj.pkl', 'wb');
pickle.dump(obj, output);
output.close();
#反序列化
pkl_file = open("obj.pkl", "rb");
aobj = pickle.load(pkl_file);
print("The type of loading obj is :", type(aobj));
print(aobj);
| false |
6b9ad3ee684ec53b2ea5e69445656e5de6d51b46 | srunas/he-aesar-cipher | /main.py | 2,083 | 4.125 | 4 | print("Программа для шифрования и расшифровки методом Цезаря")
while True:
alphabet = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
# Тут я написал алфавит 2 раза подряд для того чтобы может было производить поиск до 25 символов.
x = int(input("Encrypt/Decrypt(Зашифровать/Расшифровать)1/2: "))
if x == 1:# Зашифровка.
word = input("Enter e clear massage(Введите слово на английском): ")
key = int(input("Please enter key (number from 1-25)(Введите ключ шифрования диапазоном 1-25): "))
word = word.lower() #Сделано для того чтобы программа не ломалась при вводе заглавных букв.
wordX = ""
# Все основные переменные.
for i in word:
position = alphabet.find(i)
newPosition = position + key
if i in alphabet:
wordX = wordX + alphabet[newPosition]
else:
wordX = wordX + i
print("Your cipher is(Ваш шифр):", wordX)
elif x == 2:# Расшифровка.
word = input("Enter e cipher massage(Введите шифр на английском): ")
key = int(input("Please enter key (number from 1-25)(Введите ключ шифрования диапазоном 1-25): "))
word = word.lower()
wordX = ""
for i in word:
position = alphabet.find(i)
newPosition = position - key
if i in alphabet:
wordX = wordX + alphabet[newPosition]
else:
wordX = wordX + i
print("Your word is(Ваше слово):", wordX)
else:
print("You entered the wrong command, try again(Вы ввели не верную команду, попробуйте еще раз)")
| false |
a67bc9cd1e949c13bae120b9dc1e035427a6c5d9 | tutunak/hackerrank | /python/Python If-Else.py | 357 | 4.5 | 4 | #!/bin/python3
# If is odd, print Weird
# If is even and in the inclusive range of to , print Not Weird
# If is even and in the inclusive range of to , print Weird
# If is even and greater than , print Not Weird
n = int(input())
if n % 2:
print('Weird')
elif 6 <= n <= 20:
print('Weird')
elif (2 <= n <= 5) or n > 20:
print("Not Weird")
| false |
98a722a91f143889d8b88442a2430d0d52c4606d | ulises28/PHW | /ClassCompositionExample.py | 1,182 | 4.5 | 4 | from typing import List #List, tuple, set... etc
import sys
class BookShelf:
def __init__(self, *books): #When calling a function, the * operator can be used to unpack an iterable into the arguments in the function call
self.books = books
#Type hinting -> the value that must be returned or ": str" after an argument to mention the type of variable is expected.
def __str__(self) -> str:
return f"Bookshelf with {len(self.books)} books."
class Book:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Book {self.name}."
book = Book("HArry Potter")
book2 = Book ("Python 101")
shelf = BookShelf(book, book2)
print(shelf)
print(shelf.books)
print(sys.path)
#-----------Note--------------
#Visit this URL to know more about https://treyhunner.com/2018/10/asterisks-in-python-what-they-are-and-how-to-use-them/
#Using * and ** to pass arguments to a function
#Using * and ** to capture arguments passed into a function
#Using * to accept keyword-only arguments
#Using * to capture items during tuple unpacking
#Using * to unpack iterables into a list/tuple
#Using ** to unpack dictionaries into other dictionaries | true |
89f7be3862af86fdf222b2b3268795ed908983fd | rybli/Python-Class-Practice | /Vehicle/Exercise 4.py | 746 | 4.34375 | 4 | # Exercise Question 4: Class Inheritance
# Create a Bus class that inherits from the Vehicle class.
# Give the capacity argument of Bus.seating_capacity() a default value of 50.
# Use the following code for your parent Vehicle class. You need to use method overriding.
class Vehicle:
def __init__(self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage
def seating_capacity(self, capacity):
return f"The seating capacity of a {self.name} is {capacity} passengers"
class Bus(Vehicle):
def seating_capacity(self, capacity=50):
return super(Bus, self).seating_capacity(capacity=50)
b1 = Bus("School Volvo", 180, 12)
print(b1.seating_capacity()) | true |
063094016c88e3f76a69e919b11adf39ff762f31 | rybli/Python-Class-Practice | /Random/dice_rolling.py | 1,842 | 4.40625 | 4 | # Dice Rolling Program
# Original Problem Statement
# Write a program that will roll a 6-sided dice and display it with ascii art.
from random import randint
class Dice:
# Die face count that are allowed.
allowed_sides = [3, 4, 6, 8, 12, 20]
def __init__(self, sides: int):
"""
Create a die with a custom number of sides.
:param sides: Number of sides for the die.
"""
# Check if sides is valid.
# Using most common face counts. (3, 4, 6, 8 , 12, 20)
if sides not in self.allowed_sides:
raise Exception("Please select a face value that is allowed.", self.allowed_sides)
self.sides = sides
def __repr__(self):
return repr("A(n) %d-sided die" % self.sides)
def roll(self, num_of_dice: int):
"""
Roll a custom amount of dice.
:param num_of_dice: Number of dice to roll.
:return: List of values of dice rolled and sum of all rolls.
"""
if num_of_dice <= 0:
raise Exception("num_of_dice must be a positive int, got: ", num_of_dice)
rolls = []
for x in range(num_of_dice):
rolls.append(randint(1, self.sides))
return "Rolls: ", rolls,\
"Total: ", sum(rolls)
def start():
"""
Start the program and gather user input.
Prints out list of rolls and total.
Asks user if they want to re-roll.
"""
dice_sides = int(input("What size die? "))
number_of_dice = int(input("How many dice? "))
d1 = Dice(dice_sides)
print(d1.roll(number_of_dice), sep="\n")
answer = input("Do you want to roll again? ")
while answer == "y":
print(d1.roll(number_of_dice))
answer = input("Do you want to roll again? ")
if __name__ == "__main__":
start()
d2 = Dice(8)
print(d2)
| true |
44a1a3e66f8f029f67166a15733973e366d6d85a | ricardofqueiroz/Python | /exMenus.py | 2,781 | 4.46875 | 4 |
#Menu de opções
print("""
[1] - DadosPessoa
[2] - Calculos
[3] - cestaFrutas
[4] - HoraAtual
[5] - sair
""")
#=========================================================#
#Criando um contador para a estrutura de repetição while caso o usuário escolha opção não existente
contar=0
#=========================================================#
#Funções
#1º Função
def DadosPessoa():
# SeuNome = input("Digite seu nome: ")
# print('Nome da pessoa é', SeuNome)
# idade=int(input("Digite sua idade: "))
# print(SeuNome, 'tem', idade, 'anos.', 'Nasceu no ano de', 2020 - idade)
#Exemplo com formatação
SeuNome=input("Digite seu nome: ")
print(f'Nome da pessoa é {SeuNome}')
idade=int(input("Digite sua idade: "))
print(f'{SeuNome} tem {idade} anos. Nasceu no ano de {2020 - idade}.')
#2º Função
def Calculos():
print("Calculando uma multiplicação")
n1=int(input(": "))
n2=int(input(": "))
multiplicar=n1*n2
print("O resultado da multiplicação é:", multiplicar, "e seu tipo de dado é", type(multiplicar))
"""
No tipo de dado 'type(multiplicar)' que mostra qual o tipo de dado da multiplicação também poderia
ser 'print(type(multiplicar))'
"""
#3º Função
def cestaFrutas(frutas):
return frutas
cesta=[]
#4º Função
def HoraAtual():
from datetime import datetime
horas=datetime.now()
horas12=horas.strftime("%I:%M") #%I - Significa formato 12 horas
periodo=horas.strftime("%p") #%p - Siginifica periodo se é AM/PM
print("Agora são:", horas12, periodo)
#=========================================================#
#Escolhendo as opções para chamar as funções
opcao=int(input("Escolha uma opção: "))
while opcao != 1 and opcao != 2 and opcao != 3 and opcao != 4 and opcao != 5:
opcao=int(input("Esta opção não existe. Escolha outra: "))
contar=contar+1
if opcao == 1:
DadosPessoa()
elif opcao == 2:
Calculos()
elif opcao == 3:
#O loop while ira permitir que preencha a cesta com até 5 frutas
contar=0
while len(cesta)<5: #'len' irá retornar o comprimento da lista cesta, ou seja o nº de frutas na cesta
fruta=input("Digite uma fruta:")
contar=contar+1
#Condição que irá identificar se ha fruta repetida na cesta
if fruta in cesta:
print("Essa fruta ja foi colocada na cesta, digite outra")
else:
#Continuando preencher a cesta com o uso da função 'append' que irá sempre adicionar uma fruta na cesta
cesta.append(fruta)
print(cesta)
#Condição que informa se a lista 'cesta' foi preenhida com a função 'len' que retorna o comprimeto da lista cesta
if len(cesta)==5:
print("A cesta de frutas esta cheia")
elif opcao == 4:
HoraAtual()
elif opcao == 5:
print("Sair do programa")
| false |
e4ae5a3bf98ba5568d6f961b249ccec857f738eb | Csaba79-coder/SETI-python-practice | /seti.py | 1,814 | 4.375 | 4 | def decimal_to_binary(decimal_number):
"""Returns the array of digits in binary representation of a decimal number"""
list = []
while decimal_number > 0:
elem = decimal_number % 2
list.insert(0, elem)
decimal_number //= 2
return list
print(decimal_to_binary(24))
def binary_to_decimal(binary_digits):
"""Returns the decimal (number) representation of a binary number represented by an array of 0/1 digits"""
decimal, i, n = 0, 0, 0
binary_digits = int("".join(str(x) for x in binary_digits))
while (binary_digits != 0):
dec = binary_digits % 10
decimal = decimal + dec * pow(2, i) # (2 ** i)
binary_digits = binary_digits // 10
i += 1
print(decimal)
# nem működik úgy, ahogy a feladatban volt az input, azaz ilyen formátumú inputnál
binary_to_decimal([1, 0, 1, 0, 0])
def dec_to_base(num,base): #Maximum base - 36
"""Returns the digits in destination_base representation of the decimal number"""
base_num = []
base_num = [int(i) for i in base_num]
while num>0:
dig = int(num%base)
if dig<10:
base_num += [int(i) for i in str(dig)]
else:
base_num += chr(ord('A')+dig-10) #Using uppercase letters
num //= base
base_num = base_num [::-1] #To reverse the string
return base_num
print(dec_to_base(20, 8))
def base_to_decimal(digits, original_base):
"""Returns the decimal (number) representation of an array of digits given in original_base"""
pass
def digits_as_string(digits, base):
"""Returns the string representation of an array of digits given in base"""
pass
def convert_base(original_digits, original_base, destination_base):
"""Conversion from any base to any other base"""
pass
| false |
ba9615892470400493ff92ff97c59eb76b6e5a8b | cla473/PythonTest | /Genfuncs.py | 1,503 | 4.25 | 4 | """
A set of generic functions:
reverse_string(string) --> string
split_string(orig_str, no_chars) --> list
strip_leading_digits(orig_str) --> string
transcribe_DNA(orig_DNA) --> string
@author: cla473
"""
#Signature: string --> string
def reverse_string(orig_str):
""" return a reversed string
>>> reverse_string("abc")
'cba'
>>> reverse_string("a")
'a'
"""
#using extended slice [begin:end:step]
rev_str = orig_str[::-1]
return rev_str
def split_string(orig_str, no_chars):
""" returns splits the orig_str into lenghts of no_chars and returns as a list
>>> split_string("AUGGCCAUG", 3)
["AUG", "GCC", "AUG"]
"""
chars_list = [orig_str[i:i+3] for i in range(0, len(orig_str), 3)]
#Alternative method
#pip install more-itertools
#from more_itertools import sliced
#list(sliced(dna_str, 3))
return chars_list
def strip_leading_digits(orig_str):
""" Strips leading digits from a string
>>> strip_leading_digits("123ABCDEF")
ABCDEF
>>> strip_leading_digits("12AB3456CD")
AB3456CD
>>> strip_leading_digits("ABCDEF")
ABCDEF
"""
import re
new_str = re.sub('^\d+', '', orig_str)
return new_str
def transcribe_DNA(orig_DNA):
""" returns a complementing DNA string
>>> transcribe_DNA("GATGGAACTTGACTACGTAAATT")
'GAUGGAACUUGACUACGUAAAUU'
"""
if len(orig_DNA) <= 1000:
new_DNA = orig_DNA.replace('T', 'U')
return new_DNA | true |
3ca72ae79bcd3c5128f9391287fc32b75bee38ee | laminsawo/python-365-days | /python-fundamentals/day-6-Dictionaries/dictionary-labs-decisions.py | 2,000 | 4.53125 | 5 | dict1 = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'key': 54}
print(dict1)
print(dict1['one'])
print(dict1['two'])
print(dict1['three'])
# modify a dictionary key value
dict1['key'] = 22
print(dict1, '\n')
# add new a dictionary key and a value
dict1['newKey'] = 66
print(dict1, '\n')
# create a new dictionary without assigning any value
dict2 = {}
dict2['first'] = 1
dict2['second'] = 2
dict2['third'] = 3
print(dict2)
print(dict2['second'], '\n')
# clear all data and keys in a dictionaries
dict3 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'key': 54}
dict3.clear()
print(dict3, ' <-- the contents of the list has been cleared \n')
# print the keys in dictionary
dict3 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'key': 54}
print(dict3.keys(), '\n')
dict3 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'key': 54}
print(dict3.items(),'\n')
# look for item with using key 'four', delete and print the rest of the
dict3 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'key': 54}
dict3.pop('four')
print(dict3, '\n')
#print the values of keys in a dictionary
dict3 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'key': 54}
print(dict3.values(), '\n')
# update multiple dictionaries to provide a unique key entry as the final result
# example, this removes duplicated kye pair and keep one unique key pair
dict3 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'ten': 10}
dict4 = {'one': 1, 'six': 6, 'seven': 7, 'four': 4, 'eight': 8, 'nine': 9}
dict3.update(dict4)
print(dict3, '\n')
# remove a dictionary key
del dict2['first']
print(dict2,'\n')
# delete the entire dictionary
# printing the dict2 with result in an error
# del dict2
print(dict2)
dict3 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'ten': 10}
if 'hundred' in dict3:
print('1')
else:
print('no match')
while 'eleven' in dict3:
print(dict3)
break
| true |
a8bf71ee2acb3edf2a8cca85e819dba665f99465 | laminsawo/python-365-days | /python-fundamentals/day-1-Operators/advanced-operators.py | 1,185 | 4.8125 | 5 | # This Python file exhibits Advanced Python Maths operators
"""
Operators and usage:
// = Floor division - This rounds down the answer to the nearest whole number when two numbers are divided
% = Modulus - This gives the remainder when two numbers are divided e.g. 5 % 2 = 1
** = Exponent - gives the result of powers e.g. 2**2 = 4 and 2**8 = 256
"""
x = 25
y = 10
line = '--------------------------------------------------------------------------'
# Floor division in action - expected result is 2
a = x//y
print("A floor division of %d by %d is equal to %d" %(x,y,a))
print("25 / 10 = 2.5. Floor division rounded down 2.5 to the nearest whole number\n \t", line)
# Modulus operator in action
# Expected result is 5
a = x%y
print("A modulus of %d by %d is equal to %a" %(x,y,a))
print("The above example gives the result of the remainder of 5 when 25 is divided by 10 \n \t", line)
# Exponential operator in action
# Example, let's find out what is 2 ** 8?
# This should return 256
x = 2
y = 8
a = x**y
print("%d ** %d is equal to %d" %(x,y,a))
print("The above example calculates the 2 to the power of 8 and return 256 as the result \n \t", line)
| true |
115f7fb591125aca6b3b8a132aa3528b0cc169c9 | brandonmorren/python | /C7 text Files/oefTextFiles/extraOEF1.py | 1,241 | 4.25 | 4 | def read_month(input_month):
if input_month == 8:
file = open("./Files/weather_2018 08.csv")
elif input_month == 10:
file = open("./Files/weather_2018 10.csv")
file.readline() #titel lezen
line = file.readline().rstrip()
highest_temperature = 0
first_period = line.split(";")[0]
last_period = ""
period = ""
while line:
if line != "\n":
last_period = line.split(";")[0]
record = line.split(";")
temperature = float(record[1])
if temperature > highest_temperature:
highest_temperature = temperature
period = line.split(";")[0]
line = file.readline().rstrip()
file.close()
return [first_period, last_period, highest_temperature, period]
month = int(input("Choose a month: "))
while month > 1 and month > 12:
month = int(input("Choose a month: "))
if month not in [8, 10]:
print("no data available")
else:
values = read_month(month)
print()
print("period:", "\t", values[0], "-", values[1])
print(6*"-")
print("the highest temperature in this period =", values[2], "°C")
print("this temperature was measured at", values[3][-5:], "on", values[3][:9]) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.