blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b45f6f5b4e111381fb85240154fb1943f8db0133 | shenbagasundar/Python | /Dateformatconversion.py | 253 | 4.5625 | 5 | # function to convert user provided date format
from datetime import datetime
# get input from user
date_input = input('Enter a date(MM/DD/YYYY): ')
obj = datetime.strptime(date_input, '%m/%d/%Y')
print(obj)
print(obj.strftime('%m%d%y')) | true |
2774b74bc10040f8549191ccda5b82bfa73b3840 | Indi44137/Selection | /Selection revision 3.py | 258 | 4.1875 | 4 | #Indi Knighton
#02/10/2014
#A program which checks whether a number is in the range of 21-29
number = int(input("Please enter a number here: "))
if number >= 21 and number <= 29:
print("You have selected a number inside of this number range")
| true |
ded7c74ed151460a3d802a9893748a16634e19a4 | tchitchikov/Python_Test | /Statistics/StandardDeviation.py | 1,395 | 4.34375 | 4 | """
__author__ john
The goal of this application is to calculate Standard Deviation.
1) get a total count (n)
2) find the mean (x bar)
3) subtract each instance (x sub i) from the mean (x bar)
4) square each result of instance minus mean
5) sum the total of squares
6) divide by the total count minus 1 (n-1)
7) take the square root of the result
sqrt(sum((x sub i - x bar)^2)/(n-1))
"""
listOfNumbers = [1, 3, 4, 5, 5, 5, 8, 15, 16, 19, 21]
print("The given set is: {0}".format(listOfNumbers))
# get the total count
n = len(listOfNumbers)
print("The list is length {0}".format(n))
# find the mean
sum = 0.0
for number in listOfNumbers:
sum = sum + number
xBar = sum/n
print("The mean of the list is {0}".format(xBar))
# subtract each instance of xSubI from the mean xBar
listDistanceFromMean = []
for number in listOfNumbers:
distanceFromMean = number - xBar
distanceFromMean = distanceFromMean**2
listDistanceFromMean.append(distanceFromMean)
# sum the total of squares and divide by n-1
sumDistanceFromMean = 0.0
for number in listDistanceFromMean:
sumDistanceFromMean = sumDistanceFromMean + number
variance = sumDistanceFromMean/(n-1)
# finally take the square root to get the Standard Deviation
standardDeviation = variance**0.5
print("The standard deviation for the given set is {0}".format(standardDeviation))
print("The variance for the given set is {0}".format(variance)) | true |
2b9130b8d32be383646e570041fd7017a4ffdbc8 | kre-men/Microsoft-DEV236x- | /Module 4 Nesting and Loops/Practicas/Part3__Escape Sequence (Task 2 and 5).py | 540 | 4.125 | 4 | print("It's" + "Python Time!")
print("It's\nPython Time!")
print("It's" + "\nPython Time!")
print("It\'s\nPython Time!")
#Task 2
# [ ] create and test pre_word()
def pre_word(word):
if word.isalpha()==word.startswith("pre"):
return True
else:
return False
palabra=input("enter a word that starts with \"pre\": ")
if pre_word(palabra)==False:
print("not a \"pre\" word")
else:
print("is a valid \"pre\" word")
print("\n")
#Task 5
#Fix the Errors
# [ ] review, run, fix
print("Hello" + "\n" + "World!")
| true |
d52847e9f4507027cdfab0c54b4072dfaa8ee68d | sneh-goel/Python-Practice-Codes | /11_primality_func.py | 750 | 4.25 | 4 | #Exercise 11 (and Solution)
#Ask the user for a number and determine whether the number is prime or not.
# (For those who have forgotten, a prime number is a number that has no divisors.).
# You can (and should!) use your answer to Exercise 4 to help you. Take this opportunity to practice using functions, described below.
def divisors(x):
a = 2
list = []
while a < x:
if x%a == 0:
list.append(a)
a += 1
return len(list)
num = int(input("Enter an integer - "))
no_of_divisors = divisors(num)
if num == 1:
print ("Entered num is not prime.")
else:
if no_of_divisors == 0:
print ("Entered num " + str(num) + " is prime.")
else:
print ("Entered num is not prime.")
# END # | true |
3398d7d804fec8c49c6980f34f3e2475a07f64eb | sneh-goel/Python-Practice-Codes | /6_string_lists.py | 484 | 4.1875 | 4 | #Exercise 6
#Ask the user for a string and print out whether this string is a palindrome or not.
# (A palindrome is a string that reads the same forwards and backwards.)
s = input('Enter any word - ')
p = []
q = []
x = 0
while x < len(s):
p.append(s[x])
x = x + 1
y = len(s) - 1
while y >= 0:
q.append(s[y])
y = y - 1
print (q)
print (p)
if p == q:
print ("Entered string is a Palindrome.")
else:
print ("Entered string is not a Palindrome.")
# END # | true |
37a84d991bae874a70168fbd4c0d68c89315b0b2 | habibor144369/python_program | /12th program.py | 1,062 | 4.28125 | 4 | terminate_program = False
while not terminate_program:
number1 = input("please enter a first number: ")
number1 = int(number1)
number2 = input("please enter a second number: ")
number2 = int(number2)
while True:
operator = input("please press any one operator [+ - * / % ] or [quit] press exit to program: ")
if operator == "quit":
terminate_program = True
break
if operator not in['+', '-', '*', '/', '%']:
print("unknown operator! please press the correct operator.")
continue
if operator == "+":
print("Result is: ", number1 + number2)
break
if operator == "-":
print("Result is: ", number1 - number2)
break
if operator == "*":
print("Result is: ", number1 * number2)
break
if operator == "/":
print("Result is: ", number1 / number2)
break
if operator == "%":
print("Result is: ", number1 % number2)
break
| true |
f40e4296333f9559e7c24e503b7f6b935e4149ee | 1633376/NUR-Assigment-2 | /Code/mathlib/integrate.py | 2,143 | 4.125 | 4 | import numpy as np
def trapezoid(function, a, b, num_trap):
"""
Perform trapezoid integration
In:
param: function -- The function to integrate.
param: a -- The value to start the integration at.
param: b -- The value to integrate the function to.
param: num_trap -- The number of trapezoids to use.
Out:
return: An approximation of the integral from a to b of
the function 'function'
"""
# The step size for the integration range.
dx = (b-a)/num_trap
# Find trapezoid points.
x_i = np.arange(a,b+dx,dx)
# Determine the area of all trapezoids.
area = dx*(function(a) + function(b))/2
area += np.sum(function(x_i[1:num_trap])) *dx
return area
def romberg(function, a, b, num_trap):
"""
Perform romberg integration
In:
param: function -- The function to integrate.
param: a -- The value to start the integration at.
param: b -- The value to stop the integrate at.
param: num_trap -- The maximum number of initial trapezoid
to use to approximate the area.
Out:
return: An approximation of the integral from a to b of
the function 'function'
"""
# The array to store the combined results in.
results = np.zeros(num_trap)
# The current combination:
# 0 = combine trapezoids, 1 = combine combined trapezoids,
# 2 = combine the combined combined trapezoids etc.
for combination in range(0, num_trap-1):
# Iterate and combine.
for j in range(1, num_trap-combination):
# Create the initial trapezoids to combine.
if combination == 0:
# We need two trapezoids to combine the very first time.
if j == 1:
results[j-1] = trapezoid(function, a, b, 1)
results[j] = trapezoid(function,a,b,2**j)
# Combine.
power = 4**(combination+1)
results[j-1] = (power*results[j] - results[j-1])/(power-1)
return results[0]
| true |
c29e6d51ea5e0f620509b0d0890d31e70c116595 | Bansi-Parmar/Python_Basic_Programs | /python_program-109.py | 799 | 4.28125 | 4 | ## 109. Write a program to do the following tasks:
## [a] Read any two positive numbers say n1 & n2. Assume n1>n2.
## [b] Print all even numbers that lies between n1 & n2.
## [c] Print the total number of an even numbers between n1 and n2.
print('\n\t even numbers count')
print('\t......................\n')
n1 = int(input("Enter maximum value N1 :- "))
n2 = int(input("Enter minimum value N2 :- "))
c=0
if(n1 > n2):
print('All even numbers between {} and {} are :- '.format(n1,n2))
for i in range(n2,n1+1):
if(i%2 == 0):
c+=1
print(i,end=' ')
print()
print('Total even numbers between {} and {} are :- '.format(n1,n2),c)
else:
print('NOT a VALID Number')
| true |
f6e286640af89577d6da44cdd01926c38d52bf9a | Bansi-Parmar/Python_Basic_Programs | /python_program-035.py | 471 | 4.15625 | 4 | ## 35. To find sum of all prime digits from a given number.
print('\n\t sum of all prime digits from a given number.')
print('\t...............................................\n')
n = int(input("Enter number :- "))
tno = n
psum = npsum = 0
while(tno > 0):
dig = tno % 10
tno = tno//10
if((dig==1) or (dig==2) or (dig==3) or (dig==5) or (dig==7) or (dig==9)):
psum = psum + dig
print("sum of {} prime number is : ".format(n),psum)
| true |
3218d99aeb62c4abf6f1ae03bb98c3a7f3f8dd95 | Bansi-Parmar/Python_Basic_Programs | /python_program-029.py | 343 | 4.21875 | 4 | ## 29. To find factorial of a given number. N! = 1*2*3*โฆ. *N.
print('\n\t factorial of a given number')
print('\t..............................\n')
no = int(input("Enter Number :- "))
def fact(n):
if(n == 0):
return 1
return n * fact(n-1)
print("factorial of a given number is :- ".format(no),int(fact(no)))
| true |
71940b412cbdc264053abc2f00b37e44a5aeec30 | Bansi-Parmar/Python_Basic_Programs | /python_program-117.py | 329 | 4.34375 | 4 | ## 117. To check whether the given number is a binary number or not.
print('\n\t Number is Octal or NOT')
print('\t..........................\n')
try:
n = int(input("Enter Octal Number :- "),2)
print('{} is Binary Number'.format(bin(n).replace("0b", "")))
except ValueError:
print('Not Binary Number...')
| true |
00eebf36a86de03b55aee5476a4605b4b96c108d | djecklund/My-Python-Programs | /BasicCalculator/BasicCalculator.py | 1,175 | 4.34375 | 4 | from MathEquations import MathEquations
import sys
userInput = input("Do you want to do some math? Type yes or no: ")
while(userInput != 'no' and userInput != 'No'):
if userInput == "yes" or userInput == "Yes":
try:
num1 = int(input("Please enter your first number: "))
operation = input("Please enter an operation Examples are +, -, /, *: ")
if operation != "+" or operation != "-" or operation != "/" or operation != "*":
while(operation != "+" and operation != "-" and operation != "/" and operation != "*"):
operation = input("You have entered an incorrect operation, please pick from the following: +, -, /, * ")
num2 = int(input("Please enter a second number: "))
math = MathEquations()
print(num1, " ", operation, " ", num2, " = ", math.math(num1,operation, num2))
except:
print("Oops, the exception: ", sys.exc_info()[0], " occured.")
userInput = input("Do you want to do some math? Type yes or no: ")
else:
userInput = input("You have entered an incorrect response, please enter either yes or no. ") | true |
b07bb451f52677b019822cf3d38e61a781f838c6 | quizhpi/python-dictionaries | /app.py | 977 | 4.46875 | 4 | #
# Dictionary with python
#
# Access all key value pairs of a dictionary
sports = {
1: "Basketball",
2: "Skateboard",
3: "Ping pong"
}
for sport in sports:
print(str(sport) + ": " + sports[sport])
# Create and access a dictionary based on user input
car_shop = {
"gas": "Ford Focus",
"hybrid": "BMW i8",
"electric": "Tesla Model X"
}
print("")
no_answer = True
while no_answer:
car_choice = input("What type of car do you prefer: gas, hybrid or electric: ")
if car_choice.lower() == "gas" or car_choice.lower() == "hybrid" or car_choice.lower() == "electric":
print("---------------------------------------------------------")
print("Based on your selection, the following car is recommended")
print("---------------------------------------------------------")
print(car_shop[car_choice.lower()])
no_answer = False
else:
print("Try typing in one of the three options provided.")
| true |
6ade4681bcf8d1a4d5b165ed56f2e78e9fa6e215 | LalitTyagi/New-Onboards-Training-Solution | /Python/ProblemSet02/PS0207.py | 505 | 4.1875 | 4 | import string
def remove_punctuations(word):
return "".join(i.lower() for i in word if i in string.ascii_letters)
def isPalindrome(temp):
l = len(temp)
i=0
j=l-1
count=0;
for m in range(l//2):
if(temp[i]!=temp[j]):
print("Not a Palindrome")
count+=1
return
else:
i+=1
j-=1
if(count==0):
print("It is a Palindrome")
word = input()
temp = remove_punctuations(word)
isPalindrome(temp)
| true |
5778cade45930a9755861ed60d5fc66fa4bc39b7 | lyr124423132/Liu-Yiran | /shop_calculator.py | 374 | 4.125 | 4 | num_of_items = int(input("Number of items: "))
#Get the number
total_price = 0
for i in range(1, num_of_items+1):
the_price_of_item = float(input("Price of items: "))
#Get the price
total_price += the_price_of_item
if total_price > 100:
#Decided range
total_price *= 0.9
print("Total price for ", num_of_items, "items is", total_price)
#Next loop | true |
9c97f06c6c399e8bcaa3f4ba6f90bdda2db342cc | bakjee/Python20200322 | /st01.Python๊ธฐ์ด/py07์ ํ๋ฌธ/py07_01ex1_ifํ์ง.py | 1,064 | 4.3125 | 4 | # ์ ์๋ฅผ ์
๋ ฅ์ ๋ฐ์ต๋๋ค.
# ์
๋ ฅ ๋ฐ์ ๋ฌธ์์ด์ ์ ์๋ก ๋ฐ๊ฟ๋๋ค.
num=int(input("์ ์๋ฅผ ์
๋ ฅํ์์ค"))
# ์ซ์๋ก ๋ณํํ๊ธฐ
#######################################
# ํ์, ์ง์ ํ๋ณ๋ฒ
# ๋ฐฉ๋ฒ1. ๋๋จธ์ง๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ
# ๋ฐฉ๋ฒ2. ๋ฌธ์์ด์ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ
#######################################
#######################################
# ๋ฐฉ๋ฒ1. ๋๋จธ์ง๋ฅผ ์ฌ์ฉํ์ฌ ์ง์ , ํ์ ํ๋ณํ๋ ๋ฐฉ๋ฒ
#######################################
# ์ง์ ํ์ธ
if num%2==0:
print("Even")
else:
print("Odd")
# ํ์ ํ์ธ
if num%2==1:
print("Odd")
print()
print()
print("=================================")
print("๋ฐฉ๋ฒ2")
#######################################
# ๋ฐฉ๋ฒ2. ๋ฌธ์์ด์ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ
#######################################
num=input("์ซ์๋ฅผ ์
๋ ฅํ์ธ์.... " )
if num[-1]=="0" or num[-1]=="2" or num[-1]== "4" or num[-1]=="6" or num[-1]=="8":
print("Even")
else:
print("Odd")
# ๋ง์ง๋ง ์๋ฆฌ ์ซ์๋ฅผ ์ถ์ถ
# ์ซ์๋ก ๋ณํํ๊ธฐ
| false |
9ddc587eb5c8e068fac9deb45847a8cdc3f7edec | ehicks05-kata/project-euler | /src/python-wip/Problem243.py | 1,493 | 4.21875 | 4 | # A positive fraction whose numerator is less than its denominator is called a proper fraction.
# For any denominator, d, there will be dโ1 proper fractions; for example, with dโ=โ12:
# 1/12 , 2/12 , 3/12 , 4/12 , 5/12 , 6/12 , 7/12 , 8/12 , 9/12 , 10/12 , 11/12 .
#
# We shall call a fraction that cannot be cancelled down a resilient fraction.
# Furthermore we shall define the resilience of a denominator, R(d), to be the ratio of its proper fractions
# that are resilient; for example, R(12) = 4/11 .
# In fact, dโ=โ12 is the smallest denominator having a resilience R(d) < 4/10 .
#
# Find the smallest denominator d, having a resilience R(d) < 15499/94744 .
#
# Answer:
import time
import math
def main():
start = time.time()
resilience_target = 15499 / 94744
print("target=" + str(resilience_target))
smallest_resilience = 1
d = 9699690
while True:
resilience = get_resilience(d)
if resilience < smallest_resilience:
smallest_resilience = resilience
print("d=" + str(d) + ", resilience=" + str(resilience))
if resilience < resilience_target:
break
d += 9699690
print("\nanswer: " + str(d))
print("\ntook " + str(time.time() - start) + " seconds")
def get_resilience(n):
resilience = 0
for i in range(n):
gcd = math.gcd(i, n)
if gcd == 1:
resilience += 1
return resilience / (n - 1)
if __name__ == '__main__':
main()
| true |
19915a7d3355460a0793c71024852151cb949276 | DarkMaguz/CP-Python | /strings.py | 443 | 4.15625 | 4 | #!/usr/bin/python3.6
# This should be introduced in the interactive python shell. Where the arguments to print should just be passed to the shell.
firstStr = "This is a string of text."
print(firstStr)
secondStr = "This is another string."
print(firstStr + secondStr)
print(firstStr + " " + secondStr)
thirdStr = firstStr + " " + secondStr
print(thirdStr)
strLength = len(thirdStr)
print("thirdStr has %d characters." % strLength)
| true |
73c80ed9b894cd9212187229b7cd52f9e22fd479 | lswh/pytorchstudy | /nltkbook/bigramstrigrams.py | 453 | 4.125 | 4 | from nltk import bigrams, trigrams, word_tokenize
text = "John works at Intel."
tokens = word_tokenize(text)
print(list(bigrams(tokens))) # the `bigrams` function returns a generator, so we must unwind it
# [('John', 'works'), ('works', 'at'), ('at', 'Intel'), ('Intel', '.')]
print(list(trigrams(tokens))) # the `trigrams` function returns a generator, so we must unwind it # [('John', 'works', 'at'), ('works', 'at', 'Intel'), ('at', 'Intel', '.')]
| true |
4b9cd6dd04fe07290f5338065a92a4a3f684571e | th3zigg/pythonprogdawson | /chap5/heros_inventory3.py | 704 | 4.125 | 4 | # Hero's Inventory 3.0
# Demonstrates lists
# create a list with some items and display with a for loop
inventory = ["sword","armor", "shield", "healing potion"]
print("You have", len(inventory), "items in your possession")
print("\nYour items:")
for item in inventory:
print(item)
index = int(input("\nEnter the index number for an item in inventory: "))
print("At index", index, "is", inventory[index])
print("\nDisplaying a slice")
start = int(input("\nEnter the index number to begin a slice: "))
finish = int(input("Enter the index number to end the slice: "))
print("inventory[", start, ":", finish, "] is", end=" ")
print(inventory[start:finish])
input("\nPress the enter key to continue")
| true |
35ee2606771fffc723aa073c486970fea67a2f27 | oescob16/Cracking-the-Coding-Interview | /Chapter 1 - Arrays and Strings/isUnique.py | 1,340 | 4.15625 | 4 | # Problem 1.1 - Implement an algorithm to determine if a string has all
# unique characters
import hash_table_chain as htc
# Time Complexity -> O(n)
# Space Complexity -> O(n)
def isUniqueHash(s):
h = htc.HashTableChain(len(s))
for char in s:
letter = h.retrieve(char) # Counter
if letter == None: # Character is not on the hashtable yet
h.insert(char,1)
else: # Character appears 2 or more times in the string
return False
return True
# Time Complexity -> O(n)
# Space Complexity -> O(n)
def isUniqueArray(s):
if len(s) > 128: # String has duplicated characters
return False
char_set = [False] * 128
for char in s:
val = ord(char) # Variable to map the character
if char_set[val]: # Character appears 2 or more times in the string
return False
char_set[val] = True # Character appears at least once in the string
return True
print('~~~~ Using HashTable ~~~~~~~')
print(isUniqueHash('Hello'))
print(isUniqueHash('Ana'))
print(isUniqueHash('Google'))
print(isUniqueHash('string'))
print('\n~~~~~~~~ Using Arrays ~~~~~~~~~')
print(isUniqueArray('Hello, World!'))
print(isUniqueArray('Oswaldo'))
print(isUniqueArray('Arrays'))
print(isUniqueArray('Microsoft'))
| true |
54044dca532241ebe2afa1497f2b6b11fe9e2f08 | TaylorWizard/python-learning | /check_palindrome.py | 718 | 4.125 | 4 | from string import punctuation
def reverse(text):
# if not isinstance(text, str):
# raise Exception('type of text is not str')
return text[::-1]
def is_palindrome(text):
text = text.lower()
text = text.replace(' ', '')
for char in punctuation:
text = text.replace(char, '')
return text == reverse(text)
def main():
something = input('Please input your what do you want to say:')
if is_palindrome(something):
print('Yes, "{0}" is a palindrome '.format(something))
else:
print('Yes, "{0}" is not a palindrome '.format(something))
main()
if __name__ == '__main__':
main()
else:
print('this module was imported by another module!')
| true |
1a3ff302df5b5da804e5e3d32455f61a950ff951 | 05k001/WinterNetworkFinal | /TCP_Echo.py | 1,952 | 4.28125 | 4 | '''
Sockets can be configured to act as a server and listen for incoming messages,
or connect to other applications as a client. After both ends of a TCP/IP socket
are connected, communication is bi-directional.
This sample program, based on the one in the standard library documentation,
receives incoming messages and echos them back to the sender. It starts by
creating a TCP/IP socket.
'''
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
'''
Then bind() is used to associate the socket with the server address.
In this case, the address is localhost, referring to the current server,
and the port number is 10000.
'''
# Bind the socket to the port
server_address = ('localhost', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
'''
Calling listen() puts the socket into server mode, and accept()
waits for an incoming connection.
'''
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
'''
accept() returns an open connection between the server and client,
along with the address of the client. The connection is actually a
different socket on another port (assigned by the kernel).
Data is read from the connection with recv() and transmitted with sendall().
'''
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16)
print >>sys.stderr, 'received "%s"' % data
if data:
print >>sys.stderr, 'sending data back to the client'
connection.sendall(data)
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
| true |
4ee35ff3ab2c8152e2fddd25e7cac9f81ad863bb | btparker70/Python-Basics | /datastructures/addingremoving.py | 765 | 4.40625 | 4 | # in python everything is an object
letters = ["a", "b", "c"]
# how to add new items to a list or remove existing items
# add:
# append adds to the end of the list
# functions of objects are methods
letters.append("d")
print(letters)
# ['a', 'b', 'c', 'd']
# if you want to add an item at any position, use insert method
letters.insert(0, "-")
print(letters)
# ['-', 'a', 'b', 'c', 'd']
# remove
# remove from end of list: pop method
letters.pop()
print(letters)
# you can add values to pop to remove at any index
letters.pop(0)
# when you dont know the index you can use remove method
letters.remove("b")
# removes first occurance
# delete method removes a range of items
del letters[0]
del letters[0:3]
# remove all the objects on the list
letters.clear() | true |
11472fec71a66e09daedde6db330aef6e7d66d0c | RussellMoore1987/resources | /python/hello.py | 2,839 | 4.4375 | 4 | # print statement
print("Hello World")
# # integers and floats
answer = 42
pi = 3.14159
print(answer + pi)
print(pi)
print(int(pi))
print(int(answer + pi))
print(float(answer + pi))
# # strings
# strings can be used like 'hello world' = "hello world" = """hello world"""
print('hello world')
print("hello World")
print("""hello world""")
# string functions
print('hello world'.capitalize())
print('hello world'.replace("o", "*"))
print('hello world'.isalpha())
print('123'.isdigit())
print('some,csv,values'.split(","))
# interjecting variables into a string
name = "Bob"
machine = "HAL"
print("Nice to meet you {0}. My name is {1}".format(name, machine))
# another why to do it
print(f"Nice to meet you {name}. My name is {machine}")
# # bullion and none
Python_course = True
Java_course = False
print(int(Python_course))
print(int(Java_course))
print(str(Python_course)) # string interpretation
# None is like NULL
aliens_found = None
# # if statments
# no type juggling
number = 5
if number == 5:
print("Number is five")
else:
print("Number is NOT five")
# not
if number != "5":
print("Number is five")
else:
print("Number is NOT five")
# truthy and falsity values
text = "Joe"
if number:
print("Number passed, truthy")
if text:
print("text passed, truthy")
# falsity = "", 0, None
Python_course = True
aliens_found = None
if not aliens_found:
print("got here, if not aliens_found")
if not Python_course:
print("got here, if not Python_course") # won't pass
# multiple conditions
number = 3
# and
Python_course = True
if number == 3 and Python_course:
print("got here, if number == 3 and Python_course")
# or
if number == "3" or Python_course:
print("got here, if number == \"3\" and Python_course")
# ternary if statement
a = 1
b = 2
print("bigger" if a > b else "smaller")
# # lists/array
student_names = []
# or
student_names = ["Joe", "Russell", "sam", "Gill"]
print(student_names)
print(student_names[1])
print(student_names[-1])
# replace list value
student_names[1] = "I-soso"
print(student_names)
# add to list
student_names.append("Homer")
print(student_names)
# in list
print(str("Joe" in student_names))
# count/length/len
print(len(student_names))
# remove list item
del student_names[1]
print(student_names)
# slicing
student_names = ["Joe", "Russell", "sam", "Gill"]
# get all after the first item
print(student_names[1:])
# ignore the first and the last item
print(student_names[1:-1])
# # loops
# https://app.pluralsight.com/player?course=python-getting-started&author=bo-milanovich&name=python-getting-started-m2&clip=7&mode=live
# for loop
student_names = ["Joe", "Russell", "sam", "Gill"]
for name in student_names:
print(f"Nice to meet you {name}.")
# rang, how many times to run
x = 0
for index in range(10):
x += 10
print(f"The value of x is {x}.") | true |
8f011e6ac2b8ea99ad9c8dc8b6cb05f31189cd10 | RussellMoore1987/resources | /python/MIS-5400/exam1/guess2.py | 1,179 | 4.4375 | 4 | # Write the following code in a .py file and upload it:
# * to run: python python/MIS-5400/exam1/guess2.py
# Using the random module in the Python standard library generate a number between 1 - 10.
# Using while(True) prompt a user to guess a number between 1 - 10.
# Continue to prompt the user for another guess until the guess the correct number, then exit the loop and print an awesome congratulatory message.
# Also - Tell the user if they guessed too high or too low.
# # code starting here ===============================================================================
from random import randint
playing = True
while playing:
user_input = input('\nGuess a number between 1 and 10. ')
rand_int = randint(1,10)
if user_input.isnumeric():
user_input = int(user_input)
if int(user_input) == rand_int:
print('Congratulations you guessed correctly!')
break
else:
guess_type = 'high' if rand_int - user_input < 0 else 'low'
print(f'Sorry the number was {rand_int}, you were {abs(rand_int - user_input)} off! You guessed to {guess_type}.')
print('Thanks for playing, goodbye!') | true |
4e9d67f1ec95c2b2d02779b0785928dd831db2ee | RussellMoore1987/resources | /python/MIS-5400/exam1/favorite2.py | 1,129 | 4.40625 | 4 | # Write the following code in a .py file and upload it:
# * to run: python python/MIS-5400/exam1/favorite2.py
# 1) Prompt a user for their name, age, and favorite color.
# 2) Assign each value to a variable.
# 3) Use your preferred Python string formatter to print out the following:
# "Hello {insert_name_here}, I didn't know {insert_age_here} year old's liked {insert_favorite_color_here} so much!"
# Make sure to include all punctuation (apostrophes included).
# # code starting here ===============================================================================
# 1) Prompt a user for their name, age, and favorite color.
# 2) Assign each value to a variable.
name = input('What is your name? ')
age = input('What is your age? ')
color = input('What is your favorite color? ')
# 3) Use your preferred Python string formatter to print out the following:
# "Hello {insert_name_here}, I didn't know {insert_age_here} year old's liked {insert_favorite_color_here} so much!"
# Make sure to include all punctuation (apostrophes included).
print(f"Hello {name}, I didn't know {age} year old's liked {color} so much!") | true |
3370f3f663c07adf58649a2cae3ea0a8dc893c7f | dpembert26/Python | /Multiples.py | 400 | 4.34375 | 4 | # This is a script that will look at multiples of 3 or 5 for numbers less than 10. Those are 3,5,6,9. These add up to 23
# Then the script will do the same thing for numbers less than 1000 and find the sum
total = 0
total_list = []
for num in range(1, 1000):
if num % 3 == 0 or num % 5 == 0:
total_list.append(num)
total += num
print("The total is: %d "% total)
print(total_list) | true |
164b856e578f9266499733bb7414af957e1b7542 | vmorsatti/python-challenge | /script.py | 2,948 | 4.46875 | 4 | # Verna's Exercise on how to use defaultdict, sorted, append, items, print, join
# for a tuple, sorted & printing the results without formatting
#
# NOT A CLASS EXERCISE !
# Goal is to print each state with cities listed after - one state followed by list of cities.
# Sort by state
# ADD user friendly dialog
# Run code in terminal! It works!
#Here's what is supplied:
# Unsorted list of some
# states and cities in them as tuples
state_city_list = [('TX','Georgetown'), ('CO','Denver'),('CO','Denver'), ('TX','Houston'), ('NY','Albany'), ('AK','Valdez'),('AK','Homer'),('AK','Fairbanks'),('NY', 'Syracuse'), ('NY', 'Buffalo'),
('NY', 'Rochester'), ('TX', 'Dallas'), ('CA','Sacramento'), ('CA', 'Palo Alto'), ('GA', 'Atlanta'),('MN','St. PAUL'),('CO','Greeley'),('CO','Pueblo')]
# Take a look at it in terminal:
print() # Blank line
print("state_city_list = ")
print(state_city_list)
print()
# Get some cool tools:
import csv
from collections import defaultdict
sorted_city_list = sorted(state_city_list)
print("sorted_city_list")
print(sorted_city_list)
# sort the states first here
print()
# Let's tool it into a list of states with their grouped associated cities:
# Defines cities_by_state as a defaultdict function list variable
# for the following tools to work on:
cities_by_state = defaultdict(list)
for state, city in sorted_city_list:
cities_by_state[state].append(city) # tool to create a tuple of
# each state associated with a list of unique cities (I HAD DENVER LISTED TWICE
# but only shows up in resutlts, once)
# Take a look at it in terminal:
print() # Blank line
print("The new list, cities_by_state is this as a result of defaultdict(list):")
print(cities_by_state)
# Will print like this:
# {'TX': ['Austin', 'Houston', 'Dallas'], 'NY': ['Albany', 'Syracuse',
# 'Buffalo', 'Rochester'], 'CA': ['Sacramento', 'Palo Alto'], 'GA': ['Atlanta']})
print() # Blank line
print("Here are the formatted results:")
for state, cities in cities_by_state.items():
# IMPORTANT: Using 'items' keeps elements in the state whole,
# otherwise WITHOUT IT, the state wll be broken up into 2 characters
# in the following print statement, and you won't pick up the cities !!!
print(state,"cities are:",'/'.join(sorted(cities)))
# '/'.join(cities) will remove the the formatting
# and use a 'slash' or whatever you use to separate the cities.
# I added a secondary sort to the cities in cities_by_state per state
# Output will look like this - just what we wanted!
# Here are the formatted results:
# AK cities are: Fairbanks/Homer/Valdez
# CA cities are: Palo Alto/Sacramento
# CO cities are: Denver/Greeley/Pueblo
# GA cities are: Atlanta
# MN cities are: St. PAUL
# NY cities are: Albany/Buffalo/Rochester/Syracuse
# TX cities are: Dallas/Georgetown/Houston
print() # Blank line
print("YAY - I hope this helped you!")
| true |
2083123cc8df9c7894afa8e91c7f8f365cbc1481 | posborne/learning-python | /part4-functions/p4ex3.py | 638 | 4.15625 | 4 | #!/usr/bin/env python
def adder(arg1, arg2, *args):
"""
Adds up the all parameters passed into the function. At least
two are are required.
"""
sum = arg1 + arg2
for arg in args:
sum += arg
return sum
if __name__ == '__main__':
print "Testing Adder:"
print "adder(1, 2):", adder(1, 2)
print "adder('a', 'b'):", adder('a', 'b')
print "adder([1,2], [3,4]):", adder([1,2], [3,4])
print "adder(1.453, 3.1415926):", adder(1.453, 3.1415926)
print "adder(1, 2, 3, 4, 5):", adder(1,2,3,4,5)
print "adder('he', 'is', 'a', 'bird', 'nope'): ", adder('he', 'is', 'a', 'bird', 'nope')
| true |
fab6d5a8820aa6fcd552ab1426159a1ce9b8e10b | posborne/learning-python | /part4-functions/p4ex5.py | 513 | 4.3125 | 4 | #!/usr/bin/env python
def copyDict(dictionary):
"""
Create a copy of the dictionary passed into the function. This
is a shallow copy so only references of underlying elements are
copied.
"""
newdict = {}
for key in dictionary.keys():
newdict[key] = dictionary[key]
return newdict
if __name__ == '__main__':
mydict = {'cows': 'moo', 'dogs': 'woof', 'python': 'pssss'}
newdict = copyDict(mydict)
print "mydict =>", mydict
print "newdict =>", newdict
| true |
0dd342405b9d734ceb267cf65c3443417a421f98 | akosourov/codility-tasks | /countdiv.py | 941 | 4.125 | 4 | """
Write a function:
def solution(A, B, K)
that, given three integers A, B and K, returns the number of
integers within the range [A..B] that are divisible by K, i.e.:
{ i : A โค i โค B, i mod K = 0 }
For example, for A = 6, B = 11 and K = 2, your function should
return 3, because there are three numbers divisible by 2 within
the range [6..11], namely 6, 8 and 10.
Assume that:
A and B are integers within the range [0..2,000,000,000];
K is an integer within the range [1..2,000,000,000];
A โค B.
Complexity:
expected worst-case time complexity is O(1);
expected worst-case space complexity is O(1).
"""
def solution(A, B, K):
import math
a1 = K * math.ceil(float(A) / K)
an = K * math.floor(float(B) / K) # an = a1 + (n-1)K
if a1 <= an <= B:
N = (an - a1)/K + 1
else:
N = 0
return int(N)
if __name__ == '__main__':
print(solution(6, 11, 2), 3)
print(solution(1,1,11), 0) | true |
e10d76f3304aaa90daa48e531b5bb8f972f1bd2f | inderpal2406/python | /udemy/01_walkthrough/for_practice_4.py | 1,872 | 4.625 | 5 | #!/usr/bin/env python3
# to use for loop to fetch each character in the string
my_name="Inderpal Singh Saini"
for i in my_name:
print(i)
# to use join function to fetch each character in the string
print(f"{':'.join(my_name)}")
# for loop over a list
my_list=[1,2,3,4,5]
print(f"my_list={my_list}")
for i in my_list:
print(i)
# for loop over a tuple
my_tuple=(1,2,3,4,5)
print(f"my_tuple={my_tuple}")
for i in my_tuple:
print(i)
# for loop over a list which has tuple as elements in it
list_with_tuple=[(1,2),(3,4),(5,6)]
for i in list_with_tuple:
print(f"{i}")
# to unpack each value from tuple which is element in list
list_with_tuple=[(9,8),(7,6),(5,4)]
print(f"List with tuple is : {list_with_tuple}")
for x,y in list_with_tuple:
print(f"x={x} y={y}")
# for loop in a dictionary
my_dict={'a':1,'b':2,'c':3}
print(f"my_dict={my_dict}")
for i in my_dict:
print(f"{i}") # will print only keys in the dictionary
# for loop over my_dict.keys() function
print(f"The keys in the dictionary are:")
for i in my_dict.keys():
print(i) # will print key values
# for loop over my_dict.values() function
print(f"The values in the dictionary are:")
for i in my_dict.values():
print(i) # will print only values of keys
# for loop over each item in the dictionary, an item is combination of a key-value pair in a dictionary
# by default my_dict.items() function will produce output as a list of key-value pairs as tuple
print(f"Each item in the dictionary is:")
for i in my_dict.items():
print(i)
# for loop to fetch keys in the dictionary using items() function of the dictionary
print(f"Keys using items() function:")
for i,j in my_dict.items():
print(i)
print(f"Values using items() function:")
for i,j in my_dict.items():
print(j)
print(f"Key and values using items() function:")
for i,j in my_dict.items():
print(i,j)
| false |
4c8994d8a8de64bb2e1a6589352873a99acf1823 | inderpal2406/python | /udemy/01_walkthrough/input_output.py | 734 | 4.25 | 4 | #!/usr/bin/env python3
'''
a=2
b=7
sum=a+b
print(f"Sum of {a} and {b} is {sum}.")
'''
'''
a=input("Enter value of a: ")
b=input("Enter value of b: ")
print(f"The value of variable a is {a} and its type is {type(a)}.")
print(f"The value of variable b is {b} and its type is {type(b)}.")
'''
'''
a=int(input("Enter value of a: "))
b=int(input("Enter value of b: "))
print(f"The value of variable a is {a} and its type is {type(a)}.")
print(f"The value of variable b is {b} and its type is {type(b)}.")
'''
a=eval(input("Enter tha value of a: "))
b=eval(input("Enter the value of b: "))
print(f"The value of variable a is {a} and its data type is {type(a)}.")
print(f"The value of variable b is {b} and its data type is {type(b)}.")
| true |
6a450fd654901ed8561297c6ec99e5293dbd13e0 | inderpal2406/python | /udemy/01_walkthrough/regex_4.py | 1,445 | 4.625 | 5 | #!/usr/bin/env python3
# Fourth script to explain RegEx examples
import os
import re
os.system("clear")
def initiate():
print()
print(f"text : {text}")
text="this is python This is good thIs is not bad"
initiate()
pattern=r"\bthis\b" # search this anywhere/wherever it appears
print(re.findall(pattern,text,re.IGNORECASE)) # or print(re.findall(pattern,text,re.I))
text="""this is first line
This is second line
thIs is third line
this is fourth line
this is last line"""
initiate()
#pattern=r"\bthis\b"
#print(re.findall(pattern,text)) # prints all occurrences of this
pattern=r"\b^this\b" # search for this and print it wherever it appears in the beginning
#print(re.findall(pattern,text)) # will print only one this as ^ looks for this at the start of the multiline string
#print(re.findall(pattern,text,re.MULTILINE)) # will look for ^this in all lines of multiline string
#print(re.findall(pattern,text,re.MULTILINE|re.IGNORECASE))
print(re.findall(pattern,text,re.M|re.I)) # same as above
text="""this is first line enD
This is second line End
thIs is third line
this is fourth line
this is last line end"""
initiate()
pattern=r"\bend$\b" # search for end and print it wherever it appears in the end
#print(re.findall(pattern,text)) # output is end as $ will print the search at the end of the multiline string
#print(re.findall(pattern,text,re.M)) # same output as above
print(re.findall(pattern,text,re.M|re.I))
| true |
9c6a746865e6f6557d4b7ca65af3c32f0c655e4c | inderpal2406/python | /practice_programs/scripts/numbers_to_list_and_tuple.py | 1,463 | 4.625 | 5 | #!/usr/bin/env python3
###############################################################################
# File : numbers_to_list_and_tuple.py
# Author : Inderpal Singh Saini <inderpal2406@gmail.com>
# Created : 07 Nov, 2020
# Updated : 07 Nov, 2020
# Description : A script to accept user input in form of comma separated numbers.
# : Then it'll genarate a list and a tuple from those numbers.
# : Enhancement needs to be added which is the ability to detect wrong input.
################################################################################
# Import modules
import os
import platform
import sys
# Detect the OS and clear the screen.
if platform.system()=="Windows":
os.system("cls")
elif platform.system()=="Linux":
os.system("clear")
else:
print(f"The operating system couldn't be identified. Exiting script!")
sys.exit(1)
# Print the purpose of the script.
print(f"The script accepts input as comma separated numbers and generate a list and tuple from those numbers.")
# Accept user input.
print(f"Please provide input in the form of: 1,2,3,4")
user_str=input("Enter the comma separated numbers: ")
# Split the user input string with comma as a delimiter.
# This split operation automatically results into a list as an output.
numlist=user_str.split(",")
# Convert the list to tuple and store it in a separate variable.
numtup=tuple(numlist)
# Print output
print(f"The list is: {numlist}")
print(f"The tuple is: {numtup}")
| true |
a23dff0ea5d468250941253afd5d6dcc9d8fb4e5 | inderpal2406/python | /udemy/01_walkthrough/food_menu_1.py | 637 | 4.28125 | 4 | #!/usr/bin/env python3
# This script has food iems in a list
# User enters a food item of his choice
# The script then gives an answer if food item is present in list or not
import os
os.system("clear")
food_items=["Burger","Pizza","French Fries","Ice-cream"]
print(f"Welcome to our food bazaar :)")
print()
input_food_item=input("Enter the food item name which you want to order : ")
if bool(food_items.count(input_food_item)):
print(f"Bravo! We have {input_food_item} in our kitchen. We'll deliver it in few minutes :)")
else:
print(f"Alas! We don't have {input_food_item} in our kitchen. Please visit again next time :(")
| true |
1418467686d4d6ebd276f9dfae540f79a9cdab20 | inderpal2406/python | /practice_programs/scripts/num_sum_prod.py | 1,415 | 4.3125 | 4 | #!/usr/bin/env python3
###############################################################################
# File : num_sum_prod.py
# Author : Inderpal Singh Saini <inderpal2406@gmail.com>
# Created : 07 Nov, 2020
# Updated : 07 Nov, 2020
# Description : A script to present food to animals.
# : This script demonstrates calling of another script from within a script.
# : The food.sh script is called with arguments passed to zoo.sh
# : Depending on the exit status of food.sh, further processing is performed.
################################################################################
# Import modules.
import os
import platform
import sys
# Detect OS and clear screen.
if platform.system()=="Windows":
os.system("cls")
elif platform.system()=="Linux":
os.system("clear")
else:
print("The operating system couldn't be identified. Exiting script!")
sys.exit(1)
# Display purpose of script.
print(f"This script will accept a number 'n' and number of iterations.")
print(f"Then it will display the output of n+nn+nnn+... as per the number of iterations.")
# Accept user input.
num=int(input("Please enter the number: "))
iterations=int(input("Please enter the number of iterations: "))
# For loop to iterate over number of iterations and calculate the sum.
sum=0
for i in list(range(1,iterations+1,1)):
product=1
for j in list(range(1,i+1,1)):
product*=num
sum+=product
print(sum) | true |
e57a8c453fd6a6a987b2b72cdc37e64e0ce3a3a0 | inderpal2406/python | /udemy/01_walkthrough/for_practice_3.py | 571 | 4.40625 | 4 | #!/usr/bin/env python3
# This script will accept a string from user and display its individual characters along with index values.
# Logic 2
import os
import platform
OS=platform.system()
if OS=="Linux":
os.system("clear")
elif OS=="Windows":
os.system("cls")
user_string=input("Enter string : ")
print(f"The string is : {user_string}")
print(f"length of string is : {len(user_string)}")
print(f"\nBelow is output of string in format: \n[character] --> [index_vaue]")
index_value=0
for i in user_string:
print(f"{i} --> {index_value}")
index_value+=1
| true |
bef086fc90a1735d3d73a6afecd89c6b8b99f2c7 | SURAJTHEGREAT/vector_udacity_khan_python | /Linear_Algebra/vector_mag_normal.py | 2,570 | 4.1875 | 4 | """http://interactivepython.org/courselib/static/pythonds/Introduction/ObjectOrientedProgramminginPythonDefiningClasses.html - to know more about str and eq ... str is used to know what needs to be done when print method is called and _eq_ is to find equal to
and http://stackoverflow.com/questions/16548584/adding-two-tuples-elementwise for add - i have used izip since sub is not supported using map and operator """
#from itertools import izip
from operator import add,sub,mul
import math
"""https://www.tutorialspoint.com/python/number_pow.htm - for computing square"""
class Vector(object):
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple(coordinates)
self.dimension = len(coordinates)
except ValueError:
raise ValueError('The coordinates must be nonempty')
except TypeError:
raise TypeError('The coordinates must be an iterable')
def __str__(self):
return 'Vector: {}'.format(self.coordinates)
def __eq__(self, v):
return self.coordinates == v.coordinates
def __add__(self,other):
a=self.coordinates
b=other.coordinates
c=(map(add,a,b))
print 'Vector addition is'
return Vector(c)
def __sub__(self,other):
a=self.coordinates
b=other.coordinates
c=(map(sub,a,b))
print 'Vector subtraction is'
return Vector(c)
""" This is multipication of vector function
def __mul__(self,other):
a=self.coordinates
b=other.coordinates
c=(map(mul,a,b))
print 'Vector multipication is'
return Vector(c)"""
def scalar_mul(self,other):
c=[other*x for x in self.coordinates]
print 'Vector multiplication is'
return Vector(c)
def magnitude(self):
c=math.sqrt(sum(math.pow(x,2) for x in self.coordinates))
print 'Squared vector is'
return c
def normalized(self):
d=self.magnitude()
e=self.scalar_mul(1/d)
return e
my_vector_mag_1 = Vector([-0.221,7.437])
my_vector_mag_2 = Vector([8.813,-1.331,-6.247])
my_vector_nor_1 = Vector([5.581,-2.136])
my_vector_nor_2 = Vector([1.996,3.108,-4.554])
square_vector=my_vector_mag_1.magnitude()
print square_vector
square_vector2=my_vector_mag_2.magnitude()
print square_vector2
normalized_vector=my_vector_nor_1.normalized()
print normalized_vector
normalized_vector2=my_vector_nor_2.normalized()
print normalized_vector2
| true |
8cf7da545a64535d187a4f38d53edaa1b8f36bc1 | FlawlessFalcon/Pythonista | /InteractivePy/Lists/ListPerf.py | 1,355 | 4.125 | 4 | '''
Two common operations are indexing and assigning to an index position. Both of these operations take the same amount of time no matter
how large the list becomes. When an operation like this is independent of the size of the list they are O(1).
Another very common programming task is to grow a list. You can use the append method or the concatenation operator. The append method is O(1).
However, the concatenation operator is O(k) where k is the size of the list that is being concatenated
'''
__author__ = "Ganesh"
import timeit
# Generate a list of n numbers starting with 0
# Concat
def listN1():
l = []
for i in range(1000):
l = l + [i]
# Append
def listN2():
l = []
for i in range(1000):
l.append(i)
# Comprehension
def listN3():
l = [i for i in range(1000)]
# List Range
def listN4():
l = list(range(1000))
t1 = timeit.Timer("listN1()", "from __main__ import listN1")
print("concat ", t1.timeit(number=1000), "milliseconds")
t2 = timeit.Timer("listN2()", "from __main__ import listN2")
print("append ", t2.timeit(number=1000), "milliseconds")
t3 = timeit.Timer("listN3()", "from __main__ import listN3")
print("comprehension ", t3.timeit(number=1000), "milliseconds")
t4 = timeit.Timer("listN4()", "from __main__ import listN4")
print("list range ", t4.timeit(number=1000), "milliseconds")
| true |
8df977f477c5f49146a3caef321c08d3153267fd | KittPhi/python-projects | /py_examples/isPathIn2DMatrix.py | 1,222 | 4.28125 | 4 | # Challenge: Given a 2D array(m x n). The task is to check if
# there is any path from top left to bottom right. In the matrix,
# -1 is considered as blockage (canโt go through this cell) and
# 0 is considered path cell (can go through it).
row = 5
col = 5
# Python3 program to find if there is path from top left to right bottom
def isPath(arr):
# set arr[0][0] = 1
arr[0][0] = 1
# Mark reachable (from top left)
# nodes in first row and first column.
for i in range(1, row):
if (arr[i][0] != -1):
arr[i][0] = arr[i-1][0]
for j in range(1, col):
if (arr[0][j] != -1):
arr[0][j] = arr[0][j-1]
# Mark reachable nodes in
# remaining matrix.
for i in range(1, row):
for j in range(1, col):
if (arr[i][j] != -1):
arr[i][j] = max(arr[i][j - 1],
arr[i - 1][j])
# return yes if right
# bottom index is 1
return (arr[row - 1][col - 1] == 1)
# Driver Code
# Given array
arr = [[ 0, 0, 0, -1, 0 ],
[-1, 0, 0, -1, -1],
[ 0, 0, 0, -1, 0 ],
[-1, 0, -1, 0, -1],
[ 0, 0, -1, 0, 0 ]]
# path from arr[0][0] to arr[row][col]
if (isPath(arr)):
print("Yes")
else:
print("No")
# This code is contributed
# by sahilshelangia
| true |
8ffd062b053e9c4fcc43ef69e3c98599cc34b4ab | Misa-X/Flow-Control-Exercises | /Flow Control Ex2.py | 384 | 4.375 | 4 | def max_of_three() :
x = float(input("Please input x value: "))
y = float(input("Please input y value: "))
z = float(input("Please input z value: "))
if x > y and z :
print("x is larger")
elif y > x and z :
print("y is larger")
elif z > y and x :
print("z is larger")
else:
print("They are equal")
max_of_three() | false |
c68cde590ea140f0468cd6b66c6448d69f420077 | Manga295/MyPythonRepo | /Priority_Queue_Implementation.py | 794 | 4.125 | 4 | import heapq
class PriorityQueue:
def __init__(self):
self._queue=[]
self._index=0
def push(self,item,priority):
heapq.heappush(self._queue,(-priority,self._index,item))
self._index+=1
def pop(self):
heapq.heappop(self._queue)[-1]
'''heappush and heappop functions work on a list queue so that first item in the list has the smallest priority
here we have negated the priority value since we want the list to work or sort from highest to the lowest priority
'''
class Item:
def __init__(self):
self.name=name
def __repr__(self):
return 'Item({!r})'.format(self.name)
q=PriorityQueue()
q.push(Item('manga'),1)
q.push(Item('kumar'),4)
q.push(Item('saroja'),5)
q.push(Item('narasimha rao'),1)
q.pop()
q.pop()
q.pop()
q.pop()
| false |
363a862d14adf7cb999b45a2818f56956d89f4e6 | Stanslaw/python_less | /caps_lock.py | 1,092 | 4.15625 | 4 | def caps_lock(text: str) -> str:
# your code here
caps_check = False
result = ""
print(text)
for i in text:
if i == i.upper():
result += i
continue
if i in ["a", "A"]:
caps_check = not caps_check
# print(caps_check)
continue
if not caps_check:
result += i
elif caps_check:
if i == i.upper():
result += i.lower()
else:
result += i.upper()
# print(i)
print(result)
return result
if __name__ == '__main__':
# print("Example:")
# print(caps_lock("Why are you asking me that?"))
# These "asserts" are used for self-checking and not for an auto-testing
assert caps_lock("Why are you asking me that?") == "Why RE YOU sking me thT?"
assert caps_lock("Always wanted to visit Zambia.") == "AlwYS Wnted to visit ZMBI."
assert caps_lock("Madder than Mad Brian of Madcastle") == "MDDER THn MD BRIn of MDCstle"
print("Coding complete? Click 'Check' to earn cool rewards!")
| true |
e7e003d0491ceff6b6949d09f6ca74e828d11e46 | Touchfl0w/python_practices | /advanced_grammer/practice1-10/practice2/p1.py | 533 | 4.1875 | 4 | student = ('jim',18,'shanxi','china')
#ๆนๆณไธ๏ผไผชๅธธไบฎ
#ๅขๆทปไบๅ
จๅฑๅ้๏ผไธๆจ่
NAME,AGE,PROVINCE,COUNTRY = range(4)
print(student[NAME])
print(student[AGE])
#ๆนๆณไบ๏ผไฝฟ็จnamedtuple
from collections import namedtuple
#ๅๆฐ1๏ผnamedtupleๅฝๆฐ่ฟๅไธไธชTupleๅญ็ฑป๏ผ็ฌฌไธไธชๅๆฐๆฏๅญ็ฑปๅ็งฐ๏ผๅๆฐ2๏ผindexๅ็งฐๅ่กจ
Student = namedtuple('Student',['name','age','province','country'])
#Studentๅ
็ป็ฑปๅฎไพๅ,sๆฏไธไธชๅธฆๅ็งฐ็ๅ
็ป
s = Student('jim',18,'shanxi','china')
print(s.name) | false |
b9090a2156ee631da4ada49da0c9c7d0eb337b38 | Touchfl0w/python_practices | /basic_grammer/functional_programming/f5.py | 544 | 4.1875 | 4 | #lambdaๅฝๆฐๆ ๅฝๆฐๅ๏ผไธๅฏ็ดๆฅ่ฐ็จ๏ผ้่ตๅผ็ปๅ้
#ๆ ผๅผ๏ผlambda parameter_list: expression
#expressionไธๅฏไปฅๆฏ่ตๅผ่ฏญๅฅใๅฝๆฐ็ญใใๅช่ฝๆฏ็ฎๅ่กจ่พพๅผ
f = lambda x: x**2
print(f(2))
#map
a = [1,3,5,2,4]
def convert(x):
return x**3
#็ฌฌไบไธชๅๆฐๅฟ
้กปๆฏๅบๅ๏ผๆฏๅฆ้ๅๅฐฑไธ่ฝไฝฟ็จmap
y = map(convert, a)
#่ฟๅ็ปๆๆฏmapๅฏน่ฑก๏ผๅฟ
้กปๅๅฉmapๅ
็ฝฎๆนๆณlistๆๅฏไปฅๅๅฐๅบๅ
print(y)
print(list(y))
print('*'*30)
y = map(lambda x : x**3,a)
print(list(y))
#aไธไผๆนๅ
print(a) | false |
10e5a81973216537760cc0a8961f85ce2fd00d7f | nehabais31/LeetCode-Solutions | /328. Odd Even Linked List.py | 2,533 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Four conditions for the while-loop:
odd and odd.next -> wrong when 1->2->3->4->None ( even nodes ) because even.next is None, which has no attribute 'next'
odd and even.next -> wrong when 1->2->3->4->5->None ( odd nodes ) because even is None, which has no attribute 'next'
even and odd.next -> wrong when 1->2->3->4->None ( even nodes ) because even.next is None, which has no attribute 'next'
even and even.next -> correct
1. when 1->2->3->4->5->None ( odd nodes ) even will become None first and at the same time, odd points at the last node of the linked list; therefore, breaks from the while loop.
2. when 1->2->3->4->None ( even nodes ) even.next will become None first and at the same time, odd points at the last-2 node of the linked list and even points at the last node of the linked list; therefore, breaks from the while loop.
"""
class ListNode:
def __init__(self,data = None):
self.data = data
self.next = None
class Linked_List:
def __init__(self):
self.head = None
def add_elements(self, new_data):
new_node = ListNode(new_data)
if self.head is None:
self.head = new_node
return
tail = self.head
while tail.next:
tail = tail.next
tail.next = new_node
def print_list(self):
print_val = self.head
while print_val: # not NOne
print(print_val.data, end = ' ')
print_val = print_val.next
class Solution:
def oddEvenList(self, head) :
if not head:
return head
# Set odd and even pointers
odd = head
even = head.next
evenHead = even
while even and even.next:
odd.next = odd.next.next
even.next = even.next.next
odd = odd.next
even = even.next
odd.next = evenHead
return head
ll = Linked_List()
ll.add_elements(1)
ll.add_elements(2)
ll.add_elements(3)
ll.add_elements(4)
ll.add_elements(5)
ll.print_list()
sol = Solution()
sol.oddEvenList(ll.head)
print('\nOdd first and even next')
ll.print_list()
| true |
c055c94ee2af4985f20e46cbd3112f857a859af6 | danijimmy19/Python-Programming-Beginners-Guide | /07_datetime.py | 1,260 | 4.3125 | 4 | import datetime
# Default format for date is yyyy-mm-dd
gvr = datetime.date(1956, 1, 31)
print(gvr)
print(gvr.year)
print(gvr.month)
print(gvr.day)
# To add or subtract number of days from date use timedelta
mill = datetime.date(2000, 1, 1)
# This takes number of days as arg
dt = datetime.timedelta(100)
# Positive number will increase the date and negative number will decrease the date
print("mill + dt : ",mill + dt)
# Reformat the date
# Day-name, Month-name day #, Year
# Two ways to do this
print(gvr.strftime("%A, %B %d, %Y"))
message = "GVR was born on {:%A, %B %d, %Y}."
print(message.format(gvr))
# Format similar to launch date
launch_date = datetime.date(2017, 3, 30)
launch_time = datetime.time(22, 27, 0)
launch_datetime = datetime.datetime(2017, 3, 30, 22, 27, 0)
print(launch_date)
print(launch_time)
print(launch_datetime)
# Access current date and time
# This can be achieved using method today
now = datetime.datetime.today()
print(now)
# Taking date as a string and converting that string as a date
# This can be done using method String parse Time a.k.a strptime
moon_landing = "7/20/1969"
moon_landing_datetime = datetime.datetime.strptime(moon_landing, "%m/%d/%Y")
print(moon_landing_datetime)
print(type(moon_landing_datetime)) | true |
3b5c38a5ce0dff91842919b9da9c7a67677ccbfb | danijimmy19/Python-Programming-Beginners-Guide | /23_Prime_Numbers.py | 2,216 | 4.28125 | 4 | # Prime Numbers : Only divisible by itself and 1 (2, 3, 5, 7, 11, 13, 17, 19, ...)
# Composite Numbers : Can be factored into smaller integer is called composite number
# Unit 1 -> is Neither prime nor composite
import time
import math
def is_prime_v1(n):
"""Return 'True' if 'n' is a prime number. False otherwise."""
if n == 1:
return False # 1 is not prime
for d in range(2, n):
if n%d == 0:
return False
return True
print("="*80)
# ======== Test Function =========
for n in range(1, 21):
print(n, is_prime_v1(n))
print("="*80)
# ====== Time Function ===========
t0 = time.time()
for n in range(1, 100000):
is_prime_v1(n)
t1 = time.time()
print("Time required : ", t1 - t0)
print("="*80)
# ======== Making computing factors faster
# For that test all the divisors from from 2 to sqrt(n)
def is_prime_v2(n):
"""Return 'True' if 'n' is a prime number. False otherwise."""
if n == 1:
return False # 1 is not prime
max_divisor = math.floor(math.sqrt(n))
for d in range(2, 1 + max_divisor):
if n % d == 0:
return False
return True
# ======== Test Function v2
for n in range(1, 21):
print(n, is_prime_v2(n))
print("="*80)
# Computing the time required for second function
t0 = time.time()
for n in range(1, 100000):
is_prime_v2(n)
t1 = time.time()
print("Time required : ", t1 - t0)
print("*"*80)
def is_prime_v3(n):
"""Return 'True' if 'n' is a prime number. False otherwise."""
if n == 1:
return False # 1 is not prime
# if it's even and not 2, then it's not prime
if n == 2:
return True
if n > 2 and n % 2 == 0:
return False
max_divisor_2 = math.floor(math.sqrt(n))
for d in range(3, 1 + max_divisor_2, 2): # Third parameter is a step value. This range will start at 3, and cover all odd numbers up to our limit.
if n % d == 0 :
return False
return True
# ====== Test Function 3
for n in range(1, 21):
print(n, is_prime_v3(n))
print("*"*80)
# Testing Function 3 with Time
t0 = time.time()
for n in range(1, 100000):
is_prime_v3(n)
t1 = time.time()
print("Time required : ", t1 - t0)
print("="*80) | true |
240674a2c06975cb012c25be848698d7154e6c8f | danijimmy19/Python-Programming-Beginners-Guide | /27_Sorting.py | 1,672 | 4.6875 | 5 | # Alkaline earth metals
earth_metals = ["Beryllium", "Magnesium", "Calcium", "Strontium", "Barium", "Radium"]
# Sort the list alphabetically
earth_metals.sort()
print("List sorted alphabetically", earth_metals)
print("Sort the data in reverse order")
earth_metals.sort(reverse = True)
print(earth_metals)
print("#"*70)
"""
"in place" algorithm.
python does not create a 2nd data structure, modifies the input/existing data structure
"""
"""
format := (name, radius, density, distance from sun)
Radius: Radius at the equator in kilometers
Density: Average density in g/cm^3
Distance from sun: Average distance to sun in AUs
"""
planets = [
("Mercury", 2440, 5.43, 0.395),
("Venus", 6052, 5.24, 0.723),
("Earth", 6378, 5.52, 1.000),
("Mars", 3396, 3.93, 1.530),
("Jupiter", 71492, 1.33, 5.210),
("Saturn", 60268, 0.69, 9.551),
("Uranus", 25559, 1.27, 19.213),
("Neptune", 24764, 1.64, 30.070)
]
# Sorting the planets by size
size = lambda planet: planet[1]
planets.sort(key = size, reverse = True)
print("Sorted according to size ", planets)
print("-"*70)
# Sorting the planets by density
density = lambda planet: planet[2]
planets.sort(key = density)
print("Sorted according to density ",planets)
print("*"*80)
"""
list.sort() changes the original list?
Q: Can you create a sorted copy?
Q: How do you sort a tuple?
A: Use sorted()
"""
print("earth_metals before sorting : ",earth_metals)
sorted_earth_metals = sorted(earth_metals)
print("earth_metals after sorting : ", sorted_earth_metals)
print("$"*80)
# sorting the tuple
data = (7, 2, 5, 6, 1, 3, 9, 10, 4, 8)
print(sorted(data))
# Sorting the strings
print(sorted("Alphabetical"))
| true |
5532f3ccdfddb1c1cd2467a33a97e5a821919b6b | ishmam-hossain/problem-solving | /leetcode/617_merge_two_bin_trees.py | 1,448 | 4.125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if t1 is None:
return t2
if t2 is None:
return t1
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t2.right = self.mergeTrees(t1.right, t2.right)
return t1
tree1 = TreeNode(1)
tree1.left = TreeNode(3)
tree1.right = TreeNode(2)
tree1.left.left = TreeNode(5)
tree2 = TreeNode(2)
tree2.left = TreeNode(1)
tree2.right = TreeNode(3)
tree2.left.right = TreeNode(4)
tree2.right.right = TreeNode(7)
s = Solution()
print(s.mergeTrees(tree1, tree2))
"""
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
"""
| false |
02dc5be9d203279d380a0523181f64e50599793f | Danielbugio/Homework11 | /homework11.2/test.py | 372 | 4.28125 | 4 | # Python code demonstrate the working of
# sorted() with lambda
# Initializing list of dictionaries
lis = [{ "name" : "Nandini", "age" : 20},
{ "name" : "Manjeet", "age" : 20 },
{ "name" : "Nikhil" , "age" : 19 }]
# using sorted and lambda to print list sorted
# by age
print ("The list printed sorting by age: ")
print.sort(lis, key = lambda i: i['age'])
print ("\r")
| true |
79ac298fc6ca642592eb169d07d091c8fd475a1a | CoderXv/LeetCodePy | /PascalTriangle.py | 1,974 | 4.28125 | 4 | # --- Introduction ---
"""
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]
]
"""
# --- Solution ---
"""
- This triangle is named YangHui triangle in China.
- It shows the combination's result as :
C(0,0)
C(1,0),C(1,1)
C(2,0),C(2,1),C(2,2)
C(3,0),C(3,1),C(3,2),C(3,3)
C(4,0),C(4,1),C(4,2),C(4,3),C(4,4)
C(5,0),C(5,1),C(5,2),C(5,3),C(5,4),C(5,5)
- The C(n,k) function is:
C(n,k) = n! / k! * (n-k)!
n! is the factorial of n.
permutation in Chinese Pinyin is Pai-lie.
"""
# --- Code ---
import math
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return = []
result = []
for row in xrange(0, numRows):
cur_row = []
for col in xrange(0, row + 1):
# row!
f_row = math.factorial(row)
# col!
f_col = math.factorial(col)
# (row-col)!
f_row_sub_col = math.factorial(row-col)
# C(row, col)
number = f_row / f_col * f_row_sub_col
cur_row.append(number)
result.append(cur_row)
# --- One more thing ---
# There's also a smart method, by using map function.
"""
- map(function, sequence) calls function(item) for each of the sequence's items
and returns a list of the return values.
- More than one sequence may be passed; the function must then have as many
arguments as there are sequence (or None if some sequence is shorter than another).
- the current row of the triangle can be made by offset sum of the previous row.
- E.g:
0 1 3 3 1
+1 3 3 1 0
-----------
1 4 6 4 1
"""
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
result = [[1]]
for i in range(1,numRows):
reult += [map(lambda x,y: x+y, [0]+result[-1], result[-1]+[0])]
return result[:numRows]
| false |
50c77fe5314557e7953d95d39486b4281257cea7 | CoderXv/LeetCodePy | /maxSubAry.py | 1,364 | 4.1875 | 4 | # --- Introduction ---
"""
- Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
- For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
- the contiguous subarray [4,-1,2,1] has the largest sum = 6.
"""
# --- Medium ---
# --- Solution ---
"""
- this problem was discussed by Jon Bentley (Sep. 1984 Vol. 27 No. 9
Communications of the ACM P885)
- the paragraph below was copied from his paper (with a little
modifications)algorithm that operates on arrays: it starts at the left end
(element A[1]) and scans through to the right end (element A[n]), keeping track of
the maximum sum subvector seen so far. The maximum is initially A[0]. Suppose
we've solved the problem for A[1 .. i - 1]; how can we extend that to A[1 .. i]?
The maximum sum in the first i elements is either the maximum sum in the first i -
1 elements (which we'll call MaxSoFar), or it is that of a subvector that ends in
position i (which we'll call MaxEndingHere).
- MaxEndingHere is either A[i] plus the previous MaxEndingHere, or just A[i],
whichever is larger.
"""
# --- Code ---
class Solution(Object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
curMax, resMax = nums[0], nums[0]
for fig in nums[1:]:
curMax = max(fig, curMax + fig)
resMax = max(curMax, resMax)
return resMax | true |
36d23fc2e336809f65bbc540234e09119b45f714 | caseyagorman/interview_cake | /merge_meetings.py | 1,276 | 4.375 | 4 | def merge_meetings(meetings):
"""function takes an unsorted list of tuples and merges them into a new list of merged tuples
tuples where the start time of the meeting is before the ending time of another meeting in the list
are merged into that tuple so we have fewer blocks of time where meetings are running concurrently"""
# sort meeting list
meetings = sorted(meetings)
# initialize merged list using first item of sorted meetings list
merged_meetings = [meetings[0]]
# unpack and interate through sorted list
for start, end in meetings:
# get and unpack last item in the merged list so we can check if we should merge the new meeting into it
last_merged_start, last_merged_end = meetings[-1]
if start <= last_merged_end:
# reassign last item in merged meeting to the new merged tuple, checking to see if the new end should be
# the end of our current tuple, or the last end, meaning the current tuple would be totally subsumbed by the
# old tuple
merged_meetings[-1] = (last_merged_start,
max(last_merged_end, end))
# else, just add the current tuple
else:
merged_meetings.append((start, end))
| true |
87b23dec0478199c42df8866539a250dacc74cf1 | DanBeckerich/Python-Homework | /7-2.py | 1,390 | 4.3125 | 4 | #Written by Daniel Beckerich
#on 12/2/2017
#for exercise 53 of chapter 7
#this program is designed to allow the user to do math with fractions, with the numbers stored in tuples.
#im using this library so i get full control over the consol.
from sys import stdout
tup1 = (1,2);
tup2 = (3,4);
def add_fraction(tup1,tup2):
#variables for both the numerator and denominator. these will be paired in a tuple for output later.
result_num = 0
result_den = 0
#here is the logic for the math.
if tup1[1] == tup2[1]:
result_num = tup1[0] + tup2[0]
result_den = tup1[0]
elif tup1[1] != tup2[1]:
result_num = (tup1[0] * tup2[1]) + (tup2[0] * tup1[1])
result_den = (tup1[1] * tup2[1])
#create and return the tuple.
return (result_num, result_den)
def malt_fraction(tup1,tup2):
#do the math and return the tuple.
return ((tup1[0] * tup2[0]),(tup1[1] * tup2[1]))
#print out all the info
stdout.write("the first fraction is: " + str(tup1[0]) + "/" + str(tup1[1]) + "\n")
stdout.write("the second fraction is: " + str(tup2[0]) + "/" + str(tup2[1]) + "\n")
temp = add_fraction(tup1,tup2)
stdout.write("the result of the addition is: " + str(temp[0]) + "/" + str(temp[1]) + "\n")
#delete temp so i can use it again.
temp = None
temp = malt_fraction(tup1,tup2)
#print the new number information
stdout.write("the result of the maltiplication is: " + str(temp[0]) + "/" + str(temp[1]) + "\n")
| true |
e77b0658254806105486bb4eeb43bbd6eb20a9c8 | rsshalini/PythonExercises_Coursera | /Exercise7.py | 204 | 4.125 | 4 | __author__ = 'shalini'
fname = raw_input("Enter file name: ")
fhand = open(fname)
for line in fhand:
line = line.rstrip()
print line.upper()
#reads a txt file and prints them with caps letters.
| true |
6b8c6fd628d1447d43bfe2c37c9dc607576ed392 | streanger/tipts | /cycle_itertools_example.py | 218 | 4.3125 | 4 | import itertools
data = itertools.cycle([1, 2, 3])
for x in range(10):
item = next(data)
print(x, item)
'''
-how cycle works
-you create object, which stores specified values and return next in turn
'''
| true |
e4a2790d10c5e47521b36ffdce48149dc596f6f5 | Mystified131/DAPSupplementalCode | /Strings.py | 1,072 | 4.5 | 4 | #Here we create a string, assigning it to a variable
astr = "Hello my name is Thomas."
#Printing the string
print(astr)
#Let's try looping through the string, printing each element. What happens?
for x in range(len(astr)):
print(astr[x])
#Let's create a substring and see if it is "in" the longer string
bstr = "Thomas"
if bstr in astr:
print("That is a substring.")
if bstr not in astr:
print("That is not a substring.")
#Let's create a substring and see if it is "in" the longer string
cstr = "dre"
if cstr in astr:
print("That is a substring.")
if cstr not in astr:
print("That is not a substring.")
#Let's demonstrate slicing a string:
dstr = astr[3:5]
print(dstr)
estr = astr[:4]
print(estr)
fstr = astr[5:]
print(fstr)
#CODE CHALLENGE#
#Can you do this: Crate a program, with a function. The function will test if one string is a subset of another.
#It will return true or false.
#In the main body ask for input.
#Use the input to test the input string against the one you chose.
#Have the program print whether it is a substring or not. | true |
a91f5361e5f8908db3e2189eedd247dca0c10a85 | Mystified131/DAPSupplementalCode | /Strings2.py | 577 | 4.28125 | 4 | #Here is a solution to the Strings Code Challenge
#Here is our function
def Test_If_Substring(a, b):
a1 = str(a)
b1 = str(b)
if a1 in b1:
rstr = "True"
if a1 not in b1:
rstr = "False"
return rstr
#Here is the main body
#Here we create a string, assigning it to a variable
astr = "Hello my name is Thomas."
#Let's take an input
bstr = input("Please enter a series of characters and press 'return': ")
#And we will call the function
ans = Test_If_Substring(bstr, astr)
print("Is the entered string a substring of the secret string?: ", ans)
| true |
32f1a11b945e237f8621b43c44809e01c2eb1000 | gnshjoo/ptyhon-basic | /chapter03-02.py | 2,261 | 4.34375 | 4 | # Chapter03-2
# Python ๋ฌธ์ํ
# ๋ฌธ์ํ ์ค์
# ๋ฌธ์์ด ์์ฑ
str1 = "I am Python"
str2 = 'Python'
str3 = """How are you?"""
str4 = '''Thank you!'''
print(type(str1), type(str2), type(str4), type(str4))
print(len(str1), len(str2), len(str3), len(str4))
# ๋น ๋ฌธ์์ด
str1_t1 = ''
str2_t2 = str()
print(type(str1_t1), len(str1_t1))
print(type(str2_t2), len(str2_t2))
# ์ด์ค์ผ์ดํ ๋ฌธ์ ์ฌ์ฉ
"""
์ฐธ๊ณ : Escape ์ฝ๋
\n : ๊ฐํ
\t : ํญ
\\ : ๋ฌธ์
\' : ๋ฌธ์
\" : ๋ฌธ์
\000 : ๋ ๋ฌธ์
"""
# I'm Boy
print("I'm Boy")
print('I\'m Boy')
print('I\\m Boy')
print('a\t b')
print('a\n b')
print('a \"\" b')
excape_str1 = "Do you have a \"retro gates\"?"
print(excape_str1)
excape_str2 = 'What\'s on Tv'
print(excape_str2)
# ํญ, ์ค ๋ฐ๊ฟ
t_s1 = "CLick \t Start"
t_s2 = "New Line \n Check"
print(t_s1)
print(t_s2)
print()
# Raw String
raw_s1 = r'd:\python\test'
print(raw_s1)
print()
# ๋ฉํฐ๋ผ์ธ ์
๋ ฅ
multi_str = \
"""
๋ฌธ์์ด
๋ฉํฐ๋ผ์ธ
์
๋ ฅ
ํ
์คํธ
"""
print(multi_str)
# ๋ฌธ์์ด ์ฐ์ฐ
str_o1 = "python"
str_o2 = "Apple"
str_o3 = "How are you doing"
str_o4 = "Seoul Deajeon Busan ChangWon"
print(str_o1 * 3)
print(str_o1 + str_o2)
print('y' in str_o1)
print('n' in str_o1)
print('P' not in str_o2)
# ๋ฌธ์์ด ํ ๋ณํ
print(str(66), type(str(66)))
print(str(10.1))
print(str(True), type(str(True)))
# ๋ฌธ์์ด ํจ์ (upper , isalnum, startswith, count, endswitch, isalpha...)
print("Capitalize: ", str_o1.capitalize()) # ์ฒซ ์์๊ธ์๋ฅผ ๋๋ฌธ์๋ก ๋ฐ๊พธ์ด์ค๋ค.
print("endwith?: ", str_o2.endswith("e")) # ๋ง์ง๋ง ๋ฌธ์๊ฐ ๋ฌด์์ธ์ง ...
print("replace", str_o1.replace("thon", " Good"))
print('sorted : ', sorted(str_o1))
print("split: ", str_o4.split(" "))
# ๋ฐ๋ณต(์ํ์ค)
im_str = "Good Boy!"
print(dir(im_str)) #__iter___ ์ ์ฒด ์์ฑ์ ๊ฐ์ง๊ณ ์๋ค.
# ์ถ๋ ฅ
for i in im_str:
print(i)
# ์ฌ๋ผ์ด์ฑ
str_s1 = "Nice Python"
# ์ฌ๋ผ์ด์ฑ ์ฐ์ต
print(str_s1[0:3]) # 0 1 2 ๊น์ง ๋์จ๋ค
print(str_s1[5:]) # [5:11]
print(str_s1[:len(str_s1)]) # str_s1[:11]
print(str_s1[:len(str_s1)-1])
print(str_s1[1:9:2])
print(str_s1[-5:])
print(str_s1[1:-2])
print(str_s1[::2])
print(str_s1[::-1])
# ์์คํค์ฝ๋
a = 'z'
print(ord(a)) # ์์คํค ์ฝ๋๋ก
print(chr(122)) # ๋ฌธ์๋ก | false |
93383a5d104c3d662920447888551e82261f3e18 | YishiLIU-pill/LearningPython | /loop statement/loop.py | 722 | 4.1875 | 4 | print("Welcome to loop statement!")
# Python ๅพช็ฏ่ฏญๅฅ
'''
Python ๆไพไบforๅพช็ฏๅwhileๅพช็ฏ (ๅจPythonไธญๆฒกๆdo...whileๅพช็ฏ)๏ผ
whileๅพช็ฏ ๅจ็ปๅฎ็ๅคๆญๆกไปถไธบtrueๆถๆง่กๅพช็ฏไฝ๏ผๅฆๅ้ๅบๅพช็ฏไฝ
forๅพช็ฏ ้ๅคๆง่ก่ฏญๅฅ
ๅตๅฅๅพช็ฏ ไฝ ๅฏไปฅๅจwhileๅพช็ฏไฝไธญๅตๅฅforๅพช็ฏ
'''
#ๅพช็ฏๆงๅถ่ฏญๅฅ
''' ๅพช็ฏๆงๅถ่ฏญๅฅๅฏไปฅๆดๆน่ฏญๅฅๆง่ก็้กบๅบ๏ผPythonๆฏๆไปฅไธๅพช็ฏๆงๅถ่ฏญๅฅ:
break่ฏญๅฅ ๅจ่ฏญๅฅๅๆง่ก่ฟ็จไธญ็ปๆญขๅพช็ฏ๏ผๅนถไธ่ทณๅบๆดไธชๅพช็ฏ
continue่ฏญๅฅ ๅจ่ฏญๅฅๅๆง่ก่ฟ็จไธญ็ปๆญขๅฝๅๅพช็ฏ๏ผ่ทณๅบ่ฏฅๆฌกๅพช็ฏ๏ผๆง่กไธไธๆฌกๅพช็ฏ
pass่ฏญๅฅ passๆฏ็ฉบ่ฏญๅฅ๏ผๆฏไธบไบไฟๆ็จๅบ็ปๆ็ๅฎๆดๆง
''' | false |
098552dd510d834a34197066df2ba59943f32bf3 | YishiLIU-pill/LearningPython | /Basic data type/datatype.py | 1,901 | 4.46875 | 4 | print('Welcome to Basic data type!')
#Pythonๅบๆฌๆฐๆฎ็ฑปๅ
'''
Pythonไธญ็ๅ้ไธ้่ฆๅฃฐๆ
ๆฏไธชๅ้ๅจไฝฟ็จๅ้ฝๅฟ
้กป่ตๅผ๏ผๅ้่ตๅผไปฅๅ่ฏฅๅ้ๆไผ่ขซๅๅปบ
ๅจPythonไธญ๏ผๅ้ๅฐฑๆฏๅ้๏ผๅฎๆฒกๆ็ฑปๅ
ๆไปฌๆ่ฏด็"็ฑปๅ"ๆฏๅ้ๆๆ็ๅ
ๅญไธญๅฏน่ฑก็็ฑปๅ
็ญๅท(=)็จๆฅ็ปๅ้่ตๅผ
็ญๅท(=)่ฟ็ฎ็ฌฆๅทฆ่พนๆฏไธไธชๅ้ๅ๏ผๅณ่พนๆฏๅญๅจๅจๅ้ไธญ็ๅผ
'''
counter = 100 #ๆดๅๅ้
miles = 1000.0 #ๆตฎ็นๅๅ้
name = "runoob" #ๅญ็ฌฆไธฒ
print (counter)
print (miles)
print (name)
#ๅคไธชๅ้่ตๅผ
#Pythonๅ
่ฎธไฝ ๅๆถไธบๅคไธชๅ้่ตๅผ
a = b = c = 1 #ๅๅปบไธไธชๆดๅๅฏน่ฑก๏ผๅผไธบ1๏ผไปๅๅๅ่ตๅผ๏ผไธไธชๅ้่ขซ่ตไบ็ธๅ็ๆฐๅผ
print(a,b,c)
#ไนๅฏไปฅไธบๅคไธชๅฏน่ฑกๆๅฎๅคไธชๅ้
a, b, c = 1, 2, "runoob"
print(a,b,c)
#ๆ ๅๆฐๆฎ็ฑปๅ
'''
ไธๅฏๅๆฐๆฎ(3ไธช): Number(ๆฐๅญ), String(ๅญ็ฌฆไธฒ), Tuple(ๅ
็ป);
ๅฏๅๆฐๆฎ(3ไธช): List(ๅ่กจ), Dictionary(ๅญๅ
ธ), Set(้ๅ)ใ
'''
#Number
#ๆฏๆint, float, bool, complex
#ๅ
็ฝฎ็type()ๅฝๆฐๅฏไปฅ็จๆฅๆฅ่ฏขๅ้ๆๆ็ๅฏน่ฑก็ฑปๅ
a, b, c, d = 20, 5.5, True, 4+3j
print(a,type(a),b,type(b),c,type(c),d,type(d))
'''
#ๆญคๅค๏ผ่ฟๅฏไปฅ็จisinstanceๆฅๅคๆญ
a = 111
isinstance(a,int)
True
isinstanceๅtype็ๅบๅซๅจไบ:
type()ไธไผ่ฎคไธบๅญ็ฑปๆฏไธ็ง็ถ็ฑป็ฑปๅ
isinstance()ไผ่ฎคไธบๅญ็ฑปๆฏไธ็ง็ถ็ฑป็ฑปๅ
class A:
pass
class B(A):
pass
isinstance(A(),A)
True
type(A()) == A
True
isinstance(B(),A)
True
type(B()) == A
False
'''
#ๅฝไฝ ๆๅฎไธไธชๅผๆถ๏ผNumberๅฏน่ฑกๅฐฑไผ่ขซๅๅปบ๏ผ
var1 = 1
var2 = 10
print(var1,var2)
#ไนๅฏไปฅไฝฟ็จdel่ฏญๅฅๅ ้คไธไบๅฏน่ฑกๅผ็จ
#del่ฏญๅฅ็่ฏญๆณๆฏ๏ผ
#del var1[,var2[,var3[...,varN]]]
#ไนๅฏไปฅไฝฟ็จdel่ฏญๅฅๅ ้คๅไธชๆๅคไธชๅฏน่ฑก๏ผๅฆ๏ผ
#del var1
#del var_a, var_b
word = 'Python'
print(word[0],word[5])
print(word[-1],word[-6])
| false |
a8f563cc2ee4ef7064a6d329d676963610243478 | Shivanshgarg-india/pythonprogramming-day4 | /class and object/questio 4.py | 468 | 4.125 | 4 | # Write a Python class named Student with two attributes student_id, student_name. Add a new attribute student_class. Create a function to display the entire attribute and their values in Student class
class Student:
student_id = 'V10'
student_name = 'Jacqueline Barnett'
def display():
print(f'Student id: {Student.student_id}\nStudent Name: {Student.student_name}')
print("Original attributes and their values of the Student class:")
Student.display() | true |
f2f6457bb672a65bda1a99935ddd7f9867feb232 | Heroes-Academy/IntroPython_Winter_2016 | /code/week2/input_if.py | 1,667 | 4.5 | 4 | """
The following exercises will combine the input function and if statements.
The combination fo these two features of Python is really powerful.
I will provide extra directions for each of the exercises.
I have also completed the first one.
"""
### A Menu
# You can use input and if statements to create a menu for users
# The only thing that is required is a consistency between what you tell
# your users to input and what you check for with the if statement.
print("Welcome to my menu!")
print("Enter the number of the thing you want to do.")
print("1. See cool ascii art")
print("2. Hear a joke")
print("3. Leave the program")
their_choice = int(input("Please your choice (1,2, or 3): "))
if their_choice == 1:
print(""" Here you go!
; / ,--.
["] ["] ,< |__**|
/[_]\ [~]\/ |// |
] [ OOO /o|__| """)
elif their_choice == 2:
print("Why can't you trust atoms?")
print("Because they make up everything!")
elif their_choice == 3:
print("Okay. Bye!")
else:
print("I have no idea what you type.. but it wasn't 1, 2, or 3")
### Password checker
# Make a log in system
# Ask the user for the password to log in
# If it's the right password, then tell them it was successful!
# If it's not the right password, give them a failure message.
### Personalized Greeter
# Ask the user for their name
# Check if their name is your name
# If it's you, then put a personalized message
# You can use 'elif' and check if it is other names as well
# You can put personalized messages for them too!
# If it's not any of the names you check for, have a default message in the else
| true |
fe1508b5df05375a55e2285d48da9356f32be629 | kaushik4u1/Python-100-programming-tasks-with-solutions-Data-Types- | /11-Coding Exercise.py | 794 | 4.375 | 4 | #Create the function 'is_string_valid', which checks if provided to it string meets the following requirements:
# String cannot be empty
# String does not end up with 'em'
# String contains only lowecase characters
# String cannot contain a space character
def is_string_valid(string: str) -> bool:
return not string.endswith('em') and string.islower() and ' ' not in string
sentences = ['abcdef', 'abcdem', 'abcfEd', 'ab cde', 'bbbbbb', '']
for sentence in sentences:
if is_string_valid(sentence):
print(f'"{sentence}" is valid')
else:
print(f'"{sentence}" is not valid')
#Output: "abcdef" is valid
# "abcdem" is not valid
# "abcfEd" is not valid
# "ab cde" is not valid
# "bbbbbb" is valid
# "" is not valid
| true |
4b0b6a5c9a03f300ec368e688fa51f2bdb3da31f | HimanshubhusanRath/basics-all-in-one | /database/SQLite.py | 1,252 | 4.25 | 4 | import sqlite3
def test():
# Connect to database
conn = connect()
# Create a table
createTable(conn)
# Insert some records in to the table
insertRecords(conn)
# Read records from table
readRecords(conn)
def connect():
return sqlite3.connect('test_hr.db')
def createTable(conn):
conn.execute('''CREATE TABLE IF NOT EXISTS USER (
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
SALARY REAL
);
''')
def insertRecords(conn):
conn.execute('''
INSERT INTO USER(ID,NAME,SALARY) VALUES (1000,'HIMANSHU',100000.00)
''')
conn.execute('''
INSERT INTO USER(ID,NAME,SALARY) VALUES (2000,'Heena',200000.00)
''')
conn.execute('''
INSERT INTO USER(ID,NAME,SALARY) VALUES (3000,'Sambit',300000.00)
''')
def readRecords(conn):
cursor = conn.execute('SELECT * FROM USER')
for record in cursor:
print('ID : {}'.format(record[0]))
print('NAME : {}'.format(record[1]))
print('SALARY : {}'.format(record[2]))
print('--------------------------')
| true |
3264263136e710db4225303ec8bec385279ba9b0 | kelvinng2017/python_oop | /12_1้กๅฅ็ๅฎ็พฉ่ๆ็จ/12_1_3้กๅฅ็ๅปบๆงๆนๆณ/12_4.py | 1,168 | 4.28125 | 4 | """
12_4.py๏ผๆดๅ
12_3.py,ไธป่ฆๆฏๅขๅ ๅท่กๅญๆฌพ่ๆๆฌพๅ่ฝ๏ผๅๆๅจ้กๅฅๅ
ๅฏไปฅ็ดๆฅๅๅบ็ฎๅ้ค้ก
"""
class Banks():
'''ๅฎ็พฉ้่ก้กๅฅ'''
bankname = 'Taipei Bank' # ๅฎ็พฉๅฑฌๆง
def __init__(self, uname, money): # ๅๅงๅ็ผๆพ initๆฏinitalization็็ธฎๅฏซ
self.name = uname # ่จญๅฎๅญๆฌพ่
ๅๅญ
self.balance = money # ่จญๅฎๆๅญ็้ข
def save_money(self, money): # ่จญๅฎๅญๆฌพๆนๆณ
self.balance = self.balance + money # ๅท่กๅญๆฌพ
print("ๅญๆฌพ ", money, " ๅฎๆ") # ๅๅฐๅญๆฌพๅฎๆ
def withdraw_money(self, money): # ่จญๅฎๆๆฌพๆนๆณ
self.balance = self.balance - money # ๅท่กๆๆฌพ
print("ๆๆฌพ ", money, " ๅฎๆ") # ๅๅฐๆๆฌพๅฎๆ
def get_balance(self): # ็ฒๅพๅญๆฌพ้ค้ก
print(self.name.title(), " ็ฎๅ้ค้ก: ", self.balance)
hungbank = Banks('huang', 100) # ๅฎ็พฉ็ฉไปถ hungbank
hungbank.get_balance() # ็ฒๅพๅญๆฌพ้ค้ก
hungbank.save_money(300) # ๅญๆฌพ300ๅ
hungbank.get_balance() # ็ฒๅพๅญๆฌพ้ค้ก
hungbank.withdraw_money(200) # ๆๆฌพ200ๅ
hungbank.get_balance() # ็ฒๅพๅญๆฌพ้ค้ก
| false |
6db46096373453b27b77fe7e0561a2487fffed68 | eelbot/Tutorials | /pyTutorial/tut4.py | 2,263 | 4.46875 | 4 | """
At this point simple scripts in Python should be an attainable goal. Solving
problems should be within your grasp. The final part of the puzzle
is creating functions, and taking input.
Topics: functions, input, output
"""
# In Python, functions are created with the 'def' keyword. They are given
# a name, and then arguments are defined. Finally, they may return a value.
def print_greeting():
print("Hello")
# This simple function shows the basic syntax. However, say we wanted to define
# a function that is slightly more useful.
def fibonacci_seq(cap):
a, b = 1, 1
while b < cap:
a, b = b, a + b
return a
# The function above is given a maximum number as an argument, and returns
# the largest fibonacci number beneath that cap. As this function shows, there
# are no brackets on the return statement.
# Function calls are also very simple
fibonacci_seq(100)
print_greeting()
#------------------------------------------------------------------------------
# The final thing to examine is input and output. For the purposes of this
# tutorial, we will only be focusing on a single form of input.
# The function used to get input from the keyboard is 'input()'. This
# function takes a string argument, which will appear as a prompt. everything
# is collected by this function, until the user presses return. To collect the
# data, assign a variable to the input call.
response = input("Please enter a number")
print("Your number is: " + response)
# The important thing to remember is that input() always returns a string. Even
# though we asked them to enter a number, the computer simply understands to
# get everything as a string.
# To convert our response to a number, we can typecast variables to change
# them how want.
int(response) # converts our input to an integer
float(response) # converts our input to a float
str(response) # converts our input back to a string
#-----------------------------------------------------------------------------
# This concludes our crash course into Python! Many resources are available
# online, and while you will probably have a solid understanding of Python
# syntax, there are many areas of Python to learn before building a
# full fledged application.
# Happy coding!
| true |
a000ccb95969adf50bc4da34f58bc9043343f7cf | jeffb0ycard0na/Python-Learning | /ifprogramflow.py | 2,080 | 4.21875 | 4 | # #Example1
# name = input("Please enter your name: ")
# age = int(input("how old are you, {0}".format(name)))
# print(age)
#
# if age >= 18:
# print("You are old enough to vote")
# print("Please put an X in the box")
# else:
# print("Please come back in {0} years".format(18-age))
# #Example2
# # print("Please pick a number between 1 and 10: ")
# # guess = int(input())
# #
# # if guess != 5:
# # if guess < 5:
# # print("Please guess higher")
# # else:
# # print("please guess lower")
# # guess = int(input())
# # if guess == 5:
# # print("Well done, you guess it")
# # else:
# # print("Sorry, you have not guessed correctly")
# # else:
# # print("You got it on your first try")
# #Example3 use paranthese to be more explicite
# age = int(input("How old are you? "))
#
# if (age >= 16) and (age <= 65):
# print("Have a good day at work")
# #Example 4
# age = int(input("How old are you? "))
#
# if 16 <= age <= 65:
# print("Have a good day at work")
# #Example 5
# age = int(input("How old are you? "))
#
# if 15 < age < 66:
# print("Have a good day at work")
# #Exmaple 6
# age = int(input("How old are you? "))
#
# if (age < 15) or (age > 65):
# print("Enjoy your free time")
# else:
# print("Have a good day at work")
# #Example 7
# x = "false"
# if x:
# print("x is true")
# # Example 8
# x = input(" Please enter some text ")
# if x:
# print("You entered '{}'".format(x))
# else:
# print("You did not enter anything")
# # Example 9
# print(not False)
# print(not True)
# # Example 10
# age = int(input("How old are you? "))
# if not(age < 18):
# print("yYou are old enough to vote")
# print("Please put an X in the box")
# else:
# print("Please come back {0} years".format(18-age))
# # Example 11 Searching for characters in parrot which is "Norwegian Blue"
# parrot = "Norwegian Blue"
#
# letter = input("Enter a character: ")
#
# if letter in parrot:
# print("Give me an {}, Bob".format(letter))
# else:
# print("I don't need that letter")
| true |
0d549534230474ff4eedf02fd6ef70d1b5c79711 | guillsav/Technical-Practice | /palindrome-linkedlist/palindrome_linkedlist.py | 2,497 | 4.21875 | 4 | """
This problem was asked by Google.
Determine whether a doubly linked list is a palindrome.
What if it's singly linked?
For example, 1 -> 4 -> 3 -> 4 -> 1 returns True
while 1 -> 4 returns False.
"""
class Node:
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
def __str__(self):
return f'{self.value}'
class Doubly_linked_list:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def insert(self, value):
node = Node(value)
self.length += 1
if not self.head:
self.head = node
self.tail = node
tail = self.tail
tail.next = node
node.prev = tail
self.tail = node
self.tail.next = None
def size(self):
print(self.length)
return self.length
def print(self):
current = self.head
print('\n')
while current:
print(current.value, end= ' -> ')
current = current.next
print('\n')
return
def is_palindrome(linked_list: Doubly_linked_list) -> bool:
start, end = linked_list.head, linked_list.tail
while start != end:
if start.value != end.value:
linked_list.print()
return False
start = start.next
end = end.prev
linked_list.print()
return True
linked_list = Doubly_linked_list();
linked_list.insert(1);
linked_list.insert(4);
linked_list.insert(3);
linked_list.insert(4);
linked_list.insert(1);
print(is_palindrome(linked_list))
def reverseInParentheses(s):
# Write your code here
start = 0
end = len(s) - 1
while start <= end:
if s[start] == "(":
j = i = start + 1
while s[j] != ")":
j += 1
swapLetters(s, i, j - 1)
start += 1
s.replace("(", "")
s.replace(")", "")
return s
def swapLetters(s, i, j):
while i != j:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
def condense(head):
# Write your code here
currentNode = head
previousNode = None
data = {}
while currentNode:
if currentNode.data not in data:
data[currentNode.data] = 1
elif currentNode.data in data:
previousNode.next = None if not currentNode.next else currentNode.next
previousNode = currentNode
currentNode = currentNode.next
print(data)
return head | true |
15f5de0436205fa7ce5572a530354e7851b24a2f | liguanghe/test2 | /try/ex40r.py | 600 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# ๆ้
# ่ฎพ็ฝฎไธไธชๅ้a = ๅฝไปคopen ๏ผ๏ผ้ๆฏๆๅผ็ๅ
ๅฎน
def open_read_txt(a):
a = open(weather_info.txt)
# ่ฏปa๏ผไนๅฐฑๆฏๆๅผ็ๆไปถใa.read() ๆฏๆread a
print (a.read())
open_read_txt
# ๆ ผๅผๅๅญ็ฌฆไธฒ
# ่ฎพ็ฝฎๅ้city = ๅฝไปคinput๏ผ๏ผ ่พๅ
ฅๆ้
city = input("่ฏท่พๅ
ฅไฝ ๆฅ่ฏข็ๅๅธ")
print ("%s" % city)
elements = []
for city in open_read_txt(city):
print ("%s" % city)
elements.append(city)
for i in elements:
print ("%s" % i)
# ่ฆๅ ไธไธชๅพช็ฏ๏ผ่ฝไธๆญๅบ็ฐ city = input("่ฏท่พๅ
ฅไฝ ๆฅ่ฏข็ๅๅธ") | false |
45cb6f0ab3b86206b3fb079f1e48e4530ba39a8e | awanjila/codewars | /insertion_sort_prob.py | 952 | 4.40625 | 4 | """
Insert element into sorted list
Given a sorted list with an unsorted number in the rightmost cell, can you write some simple code to insert into the array so that it remains sorted?
Print the array every time a value is shifted in the array until the array is fully sorted. The goal of this challenge is to follow the correct order of insertion sort.
Guideline: You can copy the value of to a variable and consider its cell "empty". Since this leaves an extra cell empty on the right, you can shift everything over until can be inserted. This will create a duplicate of each value, but when you reach the right spot, you can replace it with . total_size=int(input())
"""
numbers=[int(num) for num in input().split(" ")]
key=numbers[-1]
current= len(numbers)-2
while current>=0 and numbers[current]>key:
numbers[current+1]=numbers[current]
print(" ".join(map(str,numbers)))
current-=1
numbers[current+1]=key
print(" ".join(map(str,numbers)))
| true |
56cfb855f2ba3b1cc5dd0d058981dd5f1b35c899 | SobblesBobbles/Python | /Algorithms/sortByObject.py | 1,604 | 4.28125 | 4 | # This file includes the classs definition of 'Person'.
# Params : Name, Age
# Functions: Init, setName, setAge, getAge, getName
class Person:
name = ""
age = 0
def __init__ (self):
name="undefined";
def setName(self,n):
self.name = n;
def getName(self):
return self.name;
def setAge(self,a):
self.age = a;
def getAge(self):
return self.age;
def printSelf(self):
print("Name : "+self.name);
print("Age : "+str(self.age));
# printList prints the list's objects by their attributes: name, age.
# params: L which is a List
def printList(L):
for x in range (0,len(L)):
print ("Name: "+L[x].getName());
print ("Age : "+str(L[x].getAge()));
return;
## object creation
p1 = Person();
p1.setName("Roger Waters");
p1.setAge(70);
p2 = Person();
p2.setName("David Gilmour");
p2.setAge(41);
p3 = Person();
p3.setName("Bick Bason");
p3.setAge(78);
p4 =Person();
p4.setName("Wichard Wright");
p4.setAge(61);
p5 = Person();
p5.setName("Syd Barret");
p5.setAge(81);
# creates a list and pushes the person objects onto it.
L = list();
L.append(p1); L.append(p2); L.append(p3); L.append(p4); L.append(p5);
# sorting function of a list, it uses attribute 'age' to sort through the objects.
L.sort(key = lambda x: x.age);
print('**********Sorted by Age********');
## when passing to a function, we need to declare that L being passed is going to become L in the formal params of func.
printList(L =L);
L.sort(key = lambda y :y.name);
print("*********Sorted by Name********");
printList(L =L);
| true |
d6aac7530bd9d77e93352284dee33f9ee7556634 | TriambakGoyal/psychic-invention | /solution.py | 1,561 | 4.15625 | 4 | from collections import OrderedDict
import datetime
import unittest
# Function to find the day of the key values which are in YYYY-MM-DD format
def findDay(date):
try:
year, month, day = (int(i) for i in date.split('-'))
days = datetime.date(year, month, day)
return days.strftime("%a")
except Exception:
False
pass
# Funtion that returns the solution to the problem
def solution(D):
if len(D)<2:
return False
# creating ordered dictionary variable
days=OrderedDict()
# creating a dictionary with abbreviated date values
days={'Mon':None,'Tue':None,'Wed':None,'Thu':None,'Fri':None,'Sat':None,'Sun':None}
# creating a list of abbreviated days
days_list=list(days)
# This loop adds sum of integer values of key(Dates) respective to their days in the dictionary
for i in D:
if days[findDay(i)]==None:
days[findDay(i)]=0+D[i]
else:
days[findDay(i)]=days[findDay(i)]+D[i]
if days['Mon']==None or days['Sun']==None:
return False
# if the days are missing in the dictionary
# this loops checks those days and add the mean of prev and next day integer value to this missing day
for i in days_list:
if days[i]==None: #checks whether the day is missing
days[i] = 2*days[days_list[days_list.index(i)-1]] - days[days_list[days_list.index(i)-2]] #this will assign integer value to the missing day
return days
| true |
6d2af608605cb662db1bf48ae6ee9bd66c9d103c | RahulK0307/Projects | /future_implementations/insert_chars_in_digits.py | 445 | 4.15625 | 4 |
def enterChars_inDigits(chars, digits):
if len(chars) > 0:
ring = str(digits)
print chars.join([ring[i] for i in range(0, len(ring))])
else:
print "print enter chars properly, your chars size is 0"
char = raw_input("Enter you chars : ")
try:
digit = input("Enter your Digit : ")
except:
print "Only Digits are acceptable , Please try one more time !!"
enterChars_inDigits(char, digit)
| true |
e8b7aaf109b4ecd2bd6667ba3d23e62b316c7fa6 | RahulK0307/Projects | /tkinter_beginner/window_with_buttons.py | 828 | 4.21875 | 4 | from Tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack() # it will create the frame widget and pack it
self.button = Button(frame, text="Quit", fg='red', command=frame.quit)
self.button.pack(side=LEFT)
self.hello = Button(frame, text="Say hello", command=self.say_hello)
self.hello.pack()
# frame1 = Frame(width=268, height=276, bg="", colormap="new")
# frame1.pack()
Label(text="one").pack()
separator = Frame(height=2, bd=10, relief=SUNKEN)
separator.pack(fill=X, padx=5, pady=5)
def say_hello(self):
print "Hello to everyOne This is my first code for tkinter"
root = Tk()
w = Label(text="Hello bro", fg='green')
w.pack()
app = App(root)
root.mainloop()
root.destroy()
| true |
571b16857e6302ae01b44ac19cf5b78af81ab745 | islandhuynh/turtle-race | /main.py | 1,017 | 4.15625 | 4 | import random
from turtle import Turtle, Screen
is_race_on = False
screen = Screen()
screen.setup(width = 500, height = 400)
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
y_positions = [-70, -40, -10, 20, 50, 80]
all_turtles = []
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ").lower()
for turtle_index in range(0,6):
new_turtle = Turtle(shape="turtle")
new_turtle.penup()
new_turtle.color(colors[turtle_index])
new_turtle.goto(x=-230, y=y_positions[turtle_index])
all_turtles.append(new_turtle)
if user_bet:
is_race_on = True
while is_race_on:
for turtle in all_turtles:
if turtle.xcor() > 230:
is_race_on = False
if user_bet == turtle.pencolor():
print(f"You won! The {turtle.pencolor()} is the winner!")
else:
print(f"You lost! The {turtle.pencolor()} is the winner!")
else:
rand_distance = random.randint(0,10)
turtle.forward(rand_distance)
screen.exitonclick() | true |
6b24baef36d4826f1d9965e7f22ccb30e8e9cae7 | candy02058912/unscramble | /Task4.py | 1,099 | 4.1875 | 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 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
calling = set()
answering = set()
send_texts = set()
receive_texts = set()
for record in calls:
calling.add(record[0])
answering.add(record[1])
for record in texts:
send_texts.add(record[0])
receive_texts.add(record[1])
telemarketers = sorted(list(calling - answering - send_texts - receive_texts))
print("These numbers could be telemarketers: ")
print(*telemarketers, sep="\n")
| true |
d4e080f391c61c580241960cbe978e6fdc49f29b | NjengaSaruni/LeetCode-Python-Solutions | /Andela/tree_compare.py | 2,246 | 4.21875 | 4 | import unittest
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Test(unittest.TestCase):
def test_should_return_true_for_equal_nodes(self):
self.assertTrue(compare(a_node, b_node))
def test_should_return_false_for_non_equal_nodes(self):
self.assertFalse(compare(a_node, c_node))
import collections
# return True if the two binary trees rooted and a and b are equal in value and structure
# return False otherwise
# def compare(a, b):
# # Use iterative approach, O(number of nodes in larger tree) space and O(number of nodes in larger tree) time
# # Recursive solution is more intuitive but have worse space complexity
# # because of the recursive call stack
#
# # Create a queue for each tree
# queue_a = collections.deque([a.val])
# queue_b = collections.deque([b.val])
#
# # Iterate while items in stack
# while queue_a and queue_b:
#
# # Pop stack and compare if values are equal
# if queue_a.pop() == queue_b.pop():
#
# # Append corresponding values in tree
# if a.left and b.left:
# queue_a.append(a.left.val)
# queue_b.append(b.left.val)
#
# # If one tree is left-heavy, trees are not equal
# elif a.left or b.left:
# return False
#
# # Append corresponding right values in tree
# if a.right and b.right:
# queue_a.append(a.right.val)
# queue_b.append(b.right.val)
#
# # If one tree is right-heavy, trees are not equal
# elif a.right or b.right:
# return False
#
# else:
# return False
#
# return True
def compare(a, b):
if a and b:
if a.val == b.val:
return compare(a.left, b.left) and compare(a.right, b.right)
elif a or b:
return False
else:
return True
return False
class Node:
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
a_node = Node(1, None, None)
b_node = Node(1, None, None)
c_node = Node(2, None, None)
| true |
7922b811dd16f38682ebc56587724bac1b69d0f7 | Prones94/Quiz-Time | /app.py | 1,500 | 4.125 | 4 | print("This is Football Trivia!")
questions = ['How many points is a touchdown?', 'How many teams are in the NFL?', 'True or False: Can the ball only be thrown forward once?\nEnter 1 for True and 0 for False',
'True or False: A first down is 5 yards from the line of play\nEnter 1 for True or 0 for False', 'How many people can be on the field from one team?\nEnter a number: ', 'Which year did football surpass baseball as America\'s favorite pasttime?\nEnter the year: ']
all_answers = ['a. 10\nb. 7\nc. 15\nd. 3\ne. 5\n:',
'a. 20\nb. 24\nc. 32\nd. 18\ne. 30\n:', ':', ':', ':', ':']
correct_answers = [{'b', '7'}, {'c', '32'}, {'0', 'true'},
{'1', 'false'}, {'11', 'eleven'}, {'1965', '1965'}]
answers = ['A touchdown is 7 points', 'There are 32 teams in NFL', 'You can only throw the ball forward once',
'A first down is 10 yards or more gained in an play', 'Eleven people from each team can be on the field', 'Football surpassed baseball in 1965']
def quiz():
score = 0
for question, choices, correct_answer, answer in zip(questions,all_answers,correct_answers,answers):
print(question)
user_input = input(choices).lower()
if user_input in correct_answer:
print('Correct!')
score += 1
else:
print('Incorrect!', answer)
print(score,'out of', len(questions),'that is', float(score / len(questions)) * 100, '%')
if __name__=='__main__':
quiz()
| true |
fbe5e3bf4f7e3b71fe27fffd7cf7d445d1141481 | jackngogh/Python-For-Beginners | /codes/05_conditional_statements/004/forloop.py | 325 | 4.3125 | 4 | # loop up index
fruits = ['Banana', 'Apple', 'Groups']
print('loop up via index value')
print(len(fruits))
for index in range(len(fruits)):
print(fruits[index])
list1 = [1, 2, 3, "Python"]
print('loop up index')
for i in list1:
print(i)
# Loop Item
print('loop up item')
for fruit in fruits:
print(fruit)
| false |
8b6c81cbc2d1597b6c2f6193f352f9bdc9498dbc | eshthakkar/calculator-2 | /calculator.py | 1,435 | 4.1875 | 4 | """
calculator.py
Using our arithmetic.py file from Exercise02, create the
calculator program yourself in this file.
"""
from sys import exc_info
from arithmetic import *
# Your code goes here
while True:
try:
user_request = raw_input(" >> ")
if user_request == "quit" or user_request == "q":
break
elif len(user_request) <= 1 or user_request[0] == " ":
print "Nice try! Please enter a valid number of inputs."
elif user_request[0:6] == "square" or user_request[0:4] == "cube":
if user_request[6] == " " or user_request[4] == " ":
tokens = user_request.split()
operator,num1 = tokens
num1 = int(num1)
if operator == "square":
print square(num1)
elif operator == "cube":
print cube(num1)
else:
print "Invalid command! Make sure you check your spelling."
else:
tokens = user_request.split()
operator,num1, num2 = tokens
num1 = int(num1)
num2 = int(num2)
if operator == "+":
print add(num1, num2)
elif operator == "-":
print subtract(num1, num2)
elif operator == "*":
print multiply(num1, num2)
elif operator == "/":
print divide(num1, num2)
elif operator == "pow":
print power(num1, num2)
elif operator == "mod":
print mod(num1, num2)
else:
print "Invalid command! Please try again!"
except ValueError:
print "Invalid command! Try again!"
except:
print "Goodbye ! Exiting the calculator !"
break
| true |
7881ae0747f687c89630bd7d88566ad96d9610fe | kavya459/letsupgrade-python-assignment | /Day3 assignment.py | 379 | 4.15625 | 4 | Program of the number is prime or not
Print("enter a number")
num1=input()
flag1=0
for each in range (2, num1):
If num1%each==0
Print("it is prime number")
flag1==1
Break
If(flag1==0)
print("it is prime number ")
Program of sum of n numbers
n= 10
Sum1= 0
each= 1
While each<= n:
Sum1= sum1+each
n= n+1
Print(" the sum of n numbers is " n)
| true |
39fbfeda5f2d78c6f8f339ded60e5dde6b17be24 | prajwal60/ListQuestions | /learning/List Excercises/multiply.py | 218 | 4.5 | 4 | # Write a Python program to multiplies all the items in a list
numbers = [2,5,8,7,4,1,3,6,9]
total_multiply = 1
for num in numbers:
total_multiply*=num
print(f'The product of the items in list is {total_multiply}') | true |
87d3bbc98f4c0046069eab01508091c4591e277b | prajwal60/ListQuestions | /learning/List Excercises/secondSmallest.py | 289 | 4.21875 | 4 | # Write a Python program to find the second largest number in a list.
sample=[17,1,1,1,1,1,1,1]
sample.sort()
smallest = sample[0]
for num in sample:
if num>smallest:
smallest=num
print(f'The second smallest is {smallest}')
break
else:
print('None')
| true |
694ce886911e33629741f950158542ad09c3ea95 | prajwal60/ListQuestions | /learning/BasicQuestions/Qsn60.py | 265 | 4.28125 | 4 | # Write a Python program to calculate the hypotenuse of a right angled triangle.
from math import sqrt
perp = float(input('Enter perpendicular of triangle'))
base = float(input('Enter base of triangle'))
height = sqrt(perp**2 + base**2)
print('Height = ',height) | true |
131ad08eb998891dba30cbca20a88ebc3fd13cce | prajwal60/ListQuestions | /learning/List Excercises/smallest.py | 222 | 4.21875 | 4 | # Write a Python program to get the smallest number from a list.
number = [56,84,76,23,94,12,90]
smallest = number[0]
for num in number:
if smallest>num:
smallest=num
print(f'The smallest number is {smallest}') | true |
c52969ab5a6631398691b70c3840e0be3adeab23 | prajwal60/ListQuestions | /learning/BasicQuestions/Qsn19.py | 365 | 4.40625 | 4 | # Write a Python program to get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchanged.
new_string = input('Enter any thing ')
def stringAdder(a):
oe = a[:2]
if oe.upper() =='IS':
return a
else:
return 'Is'+a
print(stringAdder(new_string)) | true |
a8f9b5c7bd2972bc22ff313b2026787712d7da3e | prajwal60/ListQuestions | /learning/BasicQuestions/Qsn27.py | 208 | 4.15625 | 4 | # Write a Python program to concatenate all elements in a list into a string and return it.
def concat(a):
res = ''
for i in a:
res = res+str(i)
return res
print(concat(["a",2,'s',4,5])) | true |
7b32b8183cdd73212424afbce6847470b8cdd7d5 | prajwal60/ListQuestions | /learning/ConditionalStatement And Loops/Qsn12.py | 246 | 4.125 | 4 | # Write a Python program that accepts a sequence of lines (blank line to terminate) as input and prints the lines as output (all characters in lower case).
item = input("Enter any thing")
res = ''
for i in item:
res += i.lower()
print(res)
| true |
7cc72550882f244b959c49415aa1e2fea76fd332 | prajwal60/ListQuestions | /learning/ConditionalStatement And Loops/Qsn6.py | 271 | 4.25 | 4 | # Write a Python program to count the number of even and odd numbers from a series of numbers.
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
even =0
odd = 0
for i in numbers:
if i %2 ==0:
even +=1
else:
odd +=1
print('Even = ',even)
print('Odd = ',odd) | true |
7abd3066941699aee22e13ac7d4b84d4920e0054 | haedal-programming/teachYourKidsToCode | /turtleGraphic/squareSpiral3.py | 233 | 4.125 | 4 | # ๋นจ๊ฐ์ ๊ณ๋จ ๋์ ์ ๋ง๋ญ๋๋ค
import turtle
cursor = turtle.Pen()
# ๋นจ๊ฐ์์ผ๋ก ๊ทธ๋ ค๋ด
๋๋ค
cursor.pencolor("red")
for x in range(100):
cursor.forward(x)
cursor.left(91)
input("Press enter to exit ;)")
| false |
62662991632555406851b74dec9b85ba23b4aef6 | Rajatbais1310/Python- | /Faulty Calculator.py | 1,702 | 4.125 | 4 | #Faulty Calculator
# 45 * 3 = 555, 56+9 = 77, 56/6 = 4
print("Faulty Calcuator Devoloped By Rajat Bais")
while(True):
opr = input("Which Kind of Operation Do You Want to Perform\n"
"Press + for Addition and Press Enter\n"
"Press - for Substraction and Press Enter\n"
"Press * for Multiplication and Press Enter\n"
"Press / for Division and Press Enter\n"
"Press % for Modulous and Press Enter\n")
no1=int(input("Enter Your First Number and Press Enter\n"))
no2=int(input("Enter Your Second Number and Press Enter\n"))
# Addition
if opr=="+":
if no1==56 and no2==9:
print("56+9 = 77")
else:
result=no1 + no2
print("Addition is :",+result)
#Substraction
if opr=="-":
if no1==0 and no2==0:
print("Error")
else:
result=no1-no2
print("Substraction is :",+result)
#Multiplicttion
if opr=="*":
if no1==45 and no2==3:
print("45 * 3 = 555")
else:
result=no1*no2
print("Multiplication is :",+result)
#Division
if opr=="/":
if no1==56 and no2==6:
print("56/6 = 4")
else:
result=no1/no2
print("Division is :",+result)
#Modulous
if opr=="%":
if no1==0 or no2==0:
print("Not Defined")
else:
result=no1%no2
print(result)
else:
print("Do You Want to Perform Operation Again Y/N?\n")
z=input()
if z=="y":
continue
if z=="n":
break
| false |
f42360652b1ce83448dfce63a7df518b2786c833 | SS4G/AlgorithmTraining | /exercise/leetcode/python_src/by2017_Sep/Leet380.py | 1,470 | 4.1875 | 4 | import random
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.nums = []
self.posFind = {}
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val not in self.posFind or self.posFind[val] == -1:
self.nums.append(val)
self.posFind[val] = len(self.nums) - 1
return True
return False
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val in self.posFind and self.posFind[val] != -1:
delPos = self.posFind[val]
self.nums[delPos] = self.nums[-1]
self.posFind[self.nums[-1]] = delPos
self.posFind[val] = -1
self.nums.pop()
return True
return False
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return self.nums[random.randint(0, len(self.nums) - 1)]
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom() | true |
8dd867249a24c621b5060337d34b00e67fe28c04 | SS4G/AlgorithmTraining | /exercise/leetcode/python_src/by2017_Sep/Leet208.py | 2,304 | 4.125 | 4 | class TrieNode(object):
def __init__(self, val):
self.wordFlag = False
self.isRoot = False
self.val = val
self.chars = {} # map to 26 characters
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode("st")
def toInt(self, c):
return ord(c) - ord('a')
def insert(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
curPtr = self.root
for c in range(len(word)):
if word[c] not in curPtr.chars:
curPtr.chars[word[c]] = TrieNode(word[c])
curPtr = curPtr.chars[word[c]]
else:
curPtr = curPtr.chars[word[c]]
if c == len(word) - 1:
curPtr.wordFlag = True
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
return self.dfsSearch(self.root, word, 0, False)
def dfsSearch(self, curNode, word, index, startWith):
while True:
if index < len(word):
c = word[index]
else:
return False
cint = c
if cint not in curNode.chars: # ๆพไธๅฐ่ฟไธชๅญ็ฌฆ
return False
elif index == len(word) - 1 and curNode.chars[cint].wordFlag is False: # ๆพๅฐไบๅญ็ฌฆไฝๆฏไธๆฏๅ่ฏ็ปๅฐพ
return False if not startWith else True
elif index == len(word) - 1 and curNode.chars[cint].wordFlag is True:
return True
else:
index += 1
curNode = curNode.chars[cint]
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
return self.dfsSearch(self.root, prefix, 0, True)
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix) | true |
dfa4196220b3358c4f912f3a74f3cd448c7ad54a | osbornetunde/100daysOfPython | /sqrtcal_day6.py | 909 | 4.15625 | 4 | ''' Write a program that calculates and prints the value according to the
given formula:
Q = squareroot of [(2*C*D)/H]
The following are fixed values of C and H, C is 5 and H is 30
D is the variable whose values should be input to your program in a comma-seperated sequence
Example:
Let us assume the following comma-seperated input sequence is given to the program:
100, 150, 180
The output of the program should be: 18,22,24
Hint: if the ouptut received is in decimal form, it should be rounded off
to its nearests value (for example if the output received is 26.0, it should be printed
as 26) in case of input data being supplied to the question it should be assumed to be a console input)'''
import math
c = 50
h = 30
value = []
items = [int(x) for x in input("Enter the value for d: ").split(',')]
for d in items:
value.append(str(round(math.sqrt((2 * c * float(d)) / h))))
print(','.join(value))
| true |
3c147a87f5a05ec9d6d2ce01b38bf70c8d221cab | SajedNahian/GraphicsWork02 | /matrix.py | 2,186 | 4.375 | 4 | """
A matrix will be an N sized list of 4 element lists.
Each individual list will represent an [x, y, z, 1] point.
For multiplication purposes, consider the lists like so:
x0 x1 xn
y0 y1 yn
z0 z1 ... zn
1 1 1
"""
import math
# print the matrix such that it looks like
# the template in the top comment
def print_matrix(matrix):
rowCount = get_row_count(matrix)
colCount = get_col_count(matrix)
for y in range(rowCount):
line = ''
for x in range(colCount):
line += str(matrix[x][y]) + ' '
print(line[:-1])
# turn the paramter matrix into an identity matrix
# you may assume matrix is square
def ident(matrix):
for y in range(len(matrix[0])):
for x in range(len(matrix)):
if (x == y):
matrix[x][y] = 1
else:
matrix[x][y] = 0
# multiply m1 by m2, modifying m2 to be the product
# m1 * m2 -> m2
def matrix_mult(m1, m2):
nm = new_matrix(len(m1[0]), len(m2))
for rowNum in range(get_row_count(m1)):
for colNum in range(get_col_count(m2)):
row = get_row(m1, rowNum)
col = get_col(m2, colNum)
value = multiply_add_two_arrays(row, col)
set_value(nm, rowNum, colNum, value)
# print_matrix(nm)
m2[:] = nm
def multiply_add_two_arrays(arr1, arr2):
sum = 0
for i in range(len(arr1)):
sum += arr1[i] * arr2[i]
return sum
def get_value(matrix, row, col):
return matrix[col][row]
def set_value(matrix, row, col, value):
matrix[col][row] = value
def get_row_count(matrix):
if (len(matrix) == 0):
return 0
return len(matrix[0])
def get_col_count(matrix):
return len(matrix)
def get_row(matrix, row):
arr = []
for i in range(get_col_count(matrix)):
arr.append(get_value(matrix, row, i))
return arr
def get_col(matrix, col):
return matrix[col]
def new_matrix(rows=4, cols=4):
m = []
for c in range(cols):
m.append([])
for r in range(rows):
m[c].append(0)
return m
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.