blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5bd3417da3fac43bd2657b2f50712f52d21f1114 | sindrimt/TDT4110 | /Eksamensøving/2013/Sudoku.py | 4,249 | 3.78125 | 4 | def readOneNumber():
rad = int(input("Rad (1-9)"))
kolonne = int(input("Kolonne (1-9)"))
tall = int(input("Tall (1-9)"))
print("Posisjon: (%d,%d) inneholder nå %df"%(rad,kolonne,tall))
def readPositionDigit(rowNr,colNr,board):
board[rowNr-1][colNr-1] = int(input("Hvilket tall vil du ha på (%d,%d)?"%(rowNr,colNr)))
print ("Verdi for posisjon (%d,%d) er nå %d"%(rowNr,colNr,board[rowNr-1][colNr-1]))
#readPositionDigit(2,3,[[1,0,0],[2,0,0],[3,0,0]])
def readValidPositionDigit(rowNr,colNr,board):
VALID_NR = list(range(0,10))
while(True):
try:
number = int(input("Hvilket tall vil du ha på (%d,%d)?"%(rowNr,colNr)))
if number not in VALID_NR:
print("Skriv et tall mellom 0-9.")
continue
break
except Exception:
print("Feil input! Det var ikke et tall")
continue
board[rowNr-1][colNr-1] = number
print ("Verdi for posisjon (%d,%d) er nå %d"%(rowNr,colNr,board[rowNr-1][colNr-1]))
return board
#readValidPositionDigit(2,3,[[1,0,0],[2,0,0],[3,0,0]])
def readSudokuBoard(board):
for row in range(1,len(board)+1):
for col in range(1,len(board[0])+1):
answer = input("Nummer %d er på posisjon (%d,%d). Ønsker du å endre? (Y/N) "%(board[row-1][col-1],row,col) )
if answer.upper() == "YES" or answer.upper()=="Y":
board = readValidPositionDigit(row,col,board)
elif answer.upper() =="NO" or answer.upper()=="N":
continue
return board
"""
print (readSudokuBoard(
[[1, 2, 3, 4, 5, 6, 7, 8, 9],
[2, 3, 4, 5, 6, 7, 8, 9, 1],
[3, 4, 5, 6, 7, 8, 9, 1, 2],
[4, 5, 6, 7, 8, 9, 0, 1, 2],
[3, 4, 5, 6, 7, 8, 9, 0, 1],
[2, 3, 4, 5, 6, 7, 8, 9, 0],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[9, 0, 1, 2, 3, 4, 5, 6, 7]]))
"""
#oppgave 4
def bidOK (meldt,resultat):
meldt = meldt.split()
tall = float(meldt[0][:2])
if tall+6 <= resultat:
return True
else:
return False
#print(bidOK ("4 ruter",10))
def utgang (meldt,resultat):
temp = meldt.split()
meldt_poeng = int(temp[0][0:])
trumf = str(temp[1][0:])
if bidOK(meldt,resultat)==True:
if trumf.upper() == "GRAND" and ((resultat) >=9) and meldt_poeng>= 3:
return True
elif (trumf.upper() == "HJERTER" or trumf.upper() == "SPAR") and ((resultat) >= 10) and (meldt_poeng>= 4):
return True
elif (trumf.upper() == "KLØVER" or trumf.upper() == "RUTER") and ((resultat)>= 11) and (meldt_poeng>= 5):
return True
else:
return False
else:
return False
#print(utgang("3 grand",9))
def poeng_trekk(meldt,resultat):
meldt = meldt.split()
antatt_poeng = float(meldt[0][0:])
poeng = resultat-6
trumf = str(meldt[1][0:])
if trumf.upper()=="KLØVER" or trumf.upper()=="RUTER":
return (poeng * 20)
elif trumf.upper()=="HJERTER" or trumf.upper()=="SPAR":
return (poeng * 30)
else:
return (poeng * 30)+10
def bridgePoints(meldt,resultat):
if utgang(meldt,resultat) == True:
return (300+poeng_trekk(meldt,resultat))
elif utgang(meldt,resultat) == False:
if bidOK(meldt,resultat) == True:
return (50+poeng_trekk(meldt,resultat))
else:
return -50
#print(bridgePoints('3 ruter', 10))
"""
bridgePoints( '3 ruter', 10) 130
bridgePoints( '3 ruter', 8) -50
bridgePoints( '3 spar', 12) 230
bridgePoints( '4 spar', 12)480
bridgePoints( '4 grand', 12)
490
"""
def main ():
lagnavn = ["N/S","Ø/V"]
spill = []
tot = []
for lag in range (1,3):
temp = []
print("Lag %s"%(lagnavn[lag-1]))
meldt = input("Melding? (eks. 3 ruter)")
resultat = int(input("Hva ble resultatet? (eks. 10)"))
temp.extend((lagnavn[lag-1],meldt,resultat,bridgePoints(meldt,resultat)))
spill.append(temp)
tot.append(temp[3])
print(("Totalt ble det utdelt %d-poeng. %d-poeng til %s og %d-poeng til %s")%(sum(tot),tot[0],lagnavn[0],tot[1],lagnavn[1]))
return spill
print(main())
|
308ee6d2d352389a14b3b407e01bbcabf00768e0 | shelcia/InterviewQuestionPython | /amazon/CountDistinct.py | 1,376 | 4.03125 | 4 | # Count distinct elements in every window of size k
# Given an array of size n and an integer k, return the count of distinct numbers in
# all windows of size k.
# Example:
# Input: arr[] = {1, 2, 1, 3, 4, 2, 3};
# k = 4
# Output: 3 4 4 3
# Explanation:
# First window is {1, 2, 1, 3}, count of distinct numbers is 3
# Second window is {2, 1, 3, 4} count of distinct numbers is 4
# Third window is {1, 3, 4, 2} count of distinct numbers is 4
# Fourth window is {3, 4, 2, 3} count of distinct numbers is 3
# Input: arr[] = {1, 2, 4, 4};
# k = 2
# Output: 2 2 1
# Explanation:
# First window is {1, 2}, count of distinct numbers is 2
# First window is {2, 4}, count of distinct numbers is 2
# First window is {4, 4}, count of distinct numbers is 1
def CountDistinctI(nums, k):
l, r = 0, 0
res = []
distintEleWindow = []
while r < len(nums):
print('begin', distintEleWindow)
# print('r', r)
if nums[r] not in distintEleWindow:
distintEleWindow.append(nums[r])
# window going out of bound
if r - l >= k - 1:
print(l, r, k, distintEleWindow)
l += 1
res.append(len(distintEleWindow))
distintEleWindow = []
# print('pointers', l, r, nums[l:r+1])
r += 1
print(res)
CountDistinctI([1, 2, 1, 3, 4, 2, 3], 4) # 3 4 4 3
|
087ae81971ce6cf01d48cf6a7fc2364d26d285a5 | fernandocostar/competitive-programming | /programming-challenges-2016-2/Codes/Tarefa05c.py | 497 | 3.625 | 4 | import itertools
def fazerAnagramas(x):
vet = ["".join(perm) for perm in itertools.permutations(x)]
return vet
def ordenar(x):
temp = []
x = sorted(x)
actual = 0
for i in range(len(x[0])):
user = int(input())
vet = []
for i in range(user):
vet += [input()]
aux = []
result = []
for each in vet:
aux += [fazerAnagramas(each)]
for each in aux:
result += [sorted(each, key=lambda L: (L.lower(), L))]
for each in result:
for opa in each:
print(opa) |
b6496a7e54deeda38ffd866cf97da05d4256aacc | matteocaruso98/matteo | /multiplesoften.py | 387 | 3.96875 | 4 | #multiplies of ten
numlist = range (1,11)
list = [i*10 for i in numlist]
print("i primi 10 multipli di 10:", list)
#cubes
cubelist = [i**3 for i in range (1,11)]
print("i primi dieci cubi:", cubelist)
#awesomeness
print("i am awesome!!")
namelist = ["matteo", "francesco", "michele", "chiara", "giorgio"]
awesomelist = [name + " is aweson" for name in namelist]
print(awesomelist)
#
|
bdb3e0d6dd20d4a4bf44b64dbada4e71e87d1b8d | ksnt/leet | /26.py | 368 | 3.75 | 4 | # Reference: https://www.lifewithpython.com/2013/11/python-remove-duplicates-from-lists.html
class Solution:
def removeDuplicates(self,nums):
"""
:type nums: List[int]
:rtype: int
"""
seen = set()
seen_add = seen.add
nums[:] = [ x for x in nums if x not in seen and not seen_add(x)]
return len(nums) |
c885e2c7951fe750da25bb0b5313bb1925210892 | CafeYuzuHuang/coding | /ReverseLinkedList.py | 578 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
# 2021.03.29
# 1st solution:
if not head: return head
before = None
after = None
while head:
after = head.next
head.next = before
before = head
head = after
return before
# 1st solution: 32 ms (87%) and 15.6 MB (76%)
|
51ccaaa6e83217e6cda9dc276e2e5b71afd619a6 | muhammed-ayman/CSCI-101-course-labs-solutions | /02/11.py | 113 | 3.859375 | 4 |
x = int(input('Enter X > '))
y = int(input('Enter Y > '))
res = 1
for i in range(y):
res *= x
print(res)
|
db04d66b999721fbcd37b1cca2981fd23ac1a530 | reutsharabani/the-magic-of-python | /5_flattening_lists_with_sum.py | 960 | 3.765625 | 4 | list_of_lists = [[1, 2], [3, 4]]
print(sum(list_of_lists, []))
def flatten_with_sum(ll):
return sum(ll, [])
def time_flattening(flat_func, sublists_count):
return flat_func([[1]] * sublists_count)
counts = (10, 100, 1000)
for count in counts:
import timeit
t = timeit.timeit('time_flattening(flatten_with_sum, count)',
setup="from __main__ import time_flattening,"
"flatten_with_sum, count", number=1000)
print('flattening of %d sublists took %f seconds' % (count, t))
def flatten_standard(ll):
from itertools import chain
return list(chain.from_iterable(ll))
for count in counts:
import timeit
t = timeit.timeit('time_flattening(flatten_standard, count)',
setup="from __main__ import time_flattening,"
"flatten_standard, count", number=1000)
print('flattening of %d sublists took %f seconds' % (count, t))
|
448a2f112bb087ff13996dd3a435ed4011572c3f | ipranshulsingla/python | /multiples.py | 87 | 3.765625 | 4 | no=int(input("Enter a no:"))
for i in range(1,11):
print(no,'x',i,'=',no*i)
|
19efe8752a327f67f9ca5007027ac4905d463372 | RamaVenkatSai/PYCHARM | /Nannakuprematho.py | 749 | 4.0625 | 4 | class node:
def __init__(self,data=None):
self.data=data
self.next=None
class Linked_list:
def __init__(self):
self.head=node()
def append(self,data):
new_node=node(data)
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next=new_node
def display(self):
cur_node=self.head
while cur_node.next!=self.head:
cur_node=cur_node.next
print(cur_node.data)
#print("head is")
#print((cur_node.next).data)
def last_node(self):
curr_node = self.head
while curr_node.next != None:
curr_node = curr_node.next
curr_node.next = self.head |
16a2f4477efb739556ef71367aab9f277dfce9f3 | YanpingDong/leetcodeSolution | /PowerOfTwo.py | 502 | 3.578125 | 4 | class PowerOfTwo(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and bin(n).count('1') == 1
def isPowerOfTwoOptimal(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and not(n&n-1)
if __name__ == '__main__':
pot = PowerOfTwo()
print pot.isPowerOfTwo(10)
print pot.isPowerOfTwo(16)
print pot.isPowerOfTwoOptimal(10)
print pot.isPowerOfTwoOptimal(16)
|
9dc5d88ca56085188450723c8aed5f1d03540569 | AirEliteMV24/Term-1-Portflio | /term 1/Cool Art.py | 446 | 3.546875 | 4 | from turtle import *
pencolor("deepskyblue")
fillcolor("silver")
begin_fill()
bgcolor("black")
speed = 100
sides = 5
distance = 100
for _ in range(50*sides):
distance += 20
forward(distance)
right(2*360.0/sides+1)
begin_fill()
fillcolor("silver")
speed=100
pencolor("silver")
sides=5
distance = 50
for _ in range(25*sides):
distance += 10
forward(distance)
right(2*180/sides+1)
end_fill()
|
6caa2dcf4fef92fa0f987b1d8132f3582fea89a2 | edgarcamilocamacho/usta_digital_systems_3 | /09_python/04_ejemplo.py | 191 | 3.625 | 4 |
numbers = [5.0, 7.0, 3.0, 8.0, 4.0, 5.0, 6.0]
# numbers_2 = []
# for number in numbers:
# numbers_2.append(number**2)
numbers_2 = [number**2 for number in numbers]
print(numbers_2)
|
6d3cc479922981559db56c8d75710985365e8d09 | CsokiHUN/python-practice | /5.py | 389 | 3.703125 | 4 | numbers = []
for i in range(3):
inum = None
while not inum:
try:
inum = int(input('Add meg a ' + str(i + 1) + '. számot: '))
except:
print('Hibás szám próbáld újra!')
numbers.append(inum)
for i in numbers:
counter = 0
for k in numbers:
if (k != i):
counter += k
print(i, (counter != i and "Nem " or "") + 'egyenlő a másik két számmal') |
2b2c8f4724e1f2cac9f0ad457a9792cb20310824 | Danny0596/PYTHON | /Año,Mes,Dia.py | 494 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 2 14:41:54 2020
@author: Danny Lema
"""
def daysInMonth(day,month,years):
if years % 400 == 0:
return True
elif years % 100 == 0:
return False
elif years % 4 == 0:
return True
else:
return False
year = 1900
print (year, daysInMonth(year))
year = 2000
print (year, daysInMonth(year))
year = 2016
print (year, daysInMonth(year))
year = 1987
print (year, daysInMonth(year))
|
c7a99f091a3da2f59f633bbc4dcd91c44c1bcd67 | mkioga/21_python_FileIO | /21_FileIO.py | 20,442 | 4.5625 | 5 |
# ===============
# 21_FileIO.py
# ===============
# =======================
# File Input Output
# =======================
# Reading text file in python
# Reading text files consist of three simple steps
# (1) Open file - using python built in function called "open"
# (2) Read the file - can read one line at a time or read entire file at one go.
# (3) Close file - when we are done with it. closing is important especially when writing to a file
# and if its not done well, the file can get corrupted
# This is the program that will read our sample file into python
# File is stored in path: C:\Users\moe\Documents\Python\sample.txt
# Note that you need to use / instead of \ when giving path to open function otherwise you get error
# so we will use path: C:/Users/moe/Documents/Python/sample.txt
# You can use a "full path" like we've done here or a "relative path"
# Open the file
# Then specify the mode i.e. what you want to do with the file. In this case we want read only ("r")
myFile = open("C:/Users/moe/Documents/Python/sample.txt", "r")
for line in myFile: # read the file one word at a time
print(line)
myFile.close() # close the file
print("="*60)
# Another way to do the string is to use double \\ so that \ is not translated as a command
# Output below works too.
print("Using double \ so that \ is not translated as command")
print()
myFile = open("C:\\Users\\moe\\Documents\\Python\\sample.txt", "r")
for line in myFile: # read the file one word at a time
print(line)
myFile.close() # close the file
print("="*60)
# ======================
# Using relative path
# =====================
# In above examples, we used full path to show where the sample.txt was located
# We can use relative path if the sample.txt is located where our python program is located.
# Example, Sample2.txt is here: C:\Users\moe\Documents\Python\IdeaProjects\21_FileIO
# We now use relative path and it is able to find sample2.txt and read it.
print("Using Relative Path")
print()
myFile = open("sample2.txt", "r") # using relative path
for line in myFile: # read the file one word at a time
print(line)
myFile.close() # close the file
print("="*60)
# ==================================
# Printing only specific characters
# ==================================
# In other programs, you may need to write code to check for end of file using while loop.
# But in python lets you iterate through the lines of the file as if it were a list which is good.
# you can also perform other processes as you iterate through the file
# For example we can check each line and only print out the ones containing a specific character
# Say we want to only print lines that contain the word "second"
myFile = open("sample2.txt", "r") # using relative path
for line in myFile: # read the file one word at a time
if "second" in line.lower(): # we check if second is in line, and convert them to lowercase.
print(line) # this prints only lines with word "second"
myFile.close() # close the file
print("="*60)
# ===============================
# Getting rid of extra newline
# ===============================
# Note that output from above code prints lines that have double spacing between them.
# This is because in the file itself, every end of line contains "newline" (\n) which
# python is reading and printing new line, hence it prints extra empty line
# To get rid of the extra empty line, we add (end='')
myFile = open("sample2.txt", "r") # using relative path
for line in myFile: # read the file one word at a time
if "second" in line.lower(): # we check if line has "second". Converts input to lowercase because we are testing for lower "second" after if.
print(line, end='') # this prints only lines with word "second"
myFile.close() # close the file. If you don't close, subsequent attempts to read file may fail. and if you wrote to file, it may become corrupted
print("="*60)
# ===================================
# Testing for character in uppercase
# ===================================
# Here is an example of testing for SECOND in upper case
# we will convert all input to upper so if it finds "second" in lower, it converts to upper and test it.
myFile = open("sample2.txt", "r") # using relative path
for line in myFile: # read the file one word at a time
if "SECOND" in line.upper(): # we check if line has "SECOND". Converts input to uppercase because we are testing for upper "SECOND" after if.
print(line, end='') # this prints only lines with word "second"
myFile.close() # close the file.
print("="*60)
# =================
# "with" function
# =================
# In above codes, if there is an error in the file, the program may stops before reaching the "close" function
# That means the file will not be closed, and in windows, you may not be able to open it or move it because python program is still using it
# we can use "with" function to open files and get rid of requirements to have "close" function
# "with" will close the file automatically once it is not needed in the program anymore.
# "with" will also close the file if there is an error in file and it cannot be read anymore
with open("sample2.txt", "r") as myFile: # Open file and save it in myFile variable
for line in myFile: # Iterate through myFile
if "SECOND" in line.upper(): # Test if SECOND is in line
print(line, end='') # Then print the line. No need for close function
print("="*60)
# =======================
# "readline" function
# =======================
# "readline" is another way to read a text file.
# "readline reads "one line at a time"
# Therefore it is recommended for reading large files so that it does not have to commit the entire file to memory
print("===== Using readline =====")
print()
with open("sample2.txt", "r") as myFile: # open file and save it in myFile
line = myFile.readline() # Reads first line to make sure there is text and assigns it to "line" to make it true.
while line: # tests line to see if it is True i.e. it has text inside
print(line, end='') # Then prints the first line
line = myFile.readline() # Then loops to second line and goes back to while loop and prints until the end
print("="*60)
# =================================================
# "readlines" function (NOTE is has s at the end)
# =================================================
# "readlines" reads the entire file at the same time and returns it in a single string into memory
# This is not recommended if you are reading large files because it will occupy a lot of memory
# it is different from "readline" which reads one line at a time
# it is useful to print line like: lines = myFile.readlines() for debugging to show you what exactly is in the output
print("============ Using readlines ============")
print()
with open("sample2.txt", "r") as myFile: # open file and store in myFile
lines = myFile.readlines() # use "readlines" to read it all and store in variable "lines". Note \n in output at end of every line
print(lines) # This prints the entire document in one line
print()
for line in lines: # you can use for loop to iterate through all the lines and print them
print(line, end='') # we use end='' to override above \n at end of every line
print("="*60)
# ================================================
# How to use "readlines" to read file in reverse
# ================================================
print("========= Using readlines in reverse ===========")
print()
with open("sample2.txt", "r") as myFile: # open file and store in myFile
lines = myFile.readlines() # use "readlines" to read it all and store in variable "lines". Note \n in output at end of every line
print(lines) # This prints the entire document in one line (same way it is written in original text file)
print()
for line in lines[::-1]: # Reads file "lines" in reverse, from end to beginning
print(line, end='') # we use end='' to override above \n at end of every line
print("="*60)
# =================
# "read" function
# =================
# "read" is used to read the entire file one word at a time and if its a text file, it returns
# a string containing the contents of the file.
# "read" can also take an extra parameter specifying how much data to read. We will see this later
print("======== using read =========")
print()
with open("sample2.txt", "r") as myFile: # open file and store in myFile
lines = myFile.read() # use "read" to read it all and store in variable "lines".
print(lines) # This prints the entire document in one line (same way it is written in original text file)
print("="*60)
# =======================================
# using "read" to read files in reverse
# =======================================
# the result here is that it reverses the file one word at a time.
# Whearas "readlines' reverses the file one line at a time
print("========== Using read in reverse ===========")
print()
with open("sample2.txt", "r") as myFile: # open file and store in myFile
lines = myFile.read() # use "readlines" to read it all and store in variable "lines". Note \n in output at end of every line
print(lines) # This prints the entire document in one line (same way it is written in original text file)
print()
for line in lines[::-1]: # Reads file "lines" in reverse, from end to beginning
print(line, end='') # we use end='' to override above \n at end of every line
print()
print("="*60)
# ===============
# Writing a file
# ===============
# use command "open" with "w" for write. This will write a new file in default location
# NOTE: city_file looks like just syntax. It gives this result. probably a file containing the write instruction
# <_io.TextIOWrapper name='MN_Cities.txt' mode='w' encoding='cp1252'>
# After the file "MN_Cities.txt" is created, you will see it at the left side under our folder 21_FileIO
# Note that if file "MN_Cities.txt" already existed, it will be overwritten
# NOTE: when writing or modifying a file, you use print and specify file=file_name (very important)
cities = ["Minneapolis", "St Paul", "Anoka", "Coon Rapids", "Blaine"] # list containing cities we want.
with open("MN_Cities.txt", 'w') as city_file: # Command to write into a text file named MN_Cities
print(city_file) # This line not necessary. I just use it to view city_file
for city in cities: # loop through all the entries in variable "cities"
print(city, file=city_file) # print the entries to file "MN_cities. See file=city_file below
print("="*60)
# for "file=city_file", the = sign here is used to pass named argument "city_file" to the "file" parameter
# We should not have any spaces on either side of =, otherwise it will look like an assignment
# "city_file" is the named argument and it is used in place of "file"
# ===================
# "Flush" function
# ===================
# Computer memory is much faster than output devices like screens and external drives
# So data being written to devices is buffered i.e. data is transfered to a buffer, then contents of the buffer
# are transfered to the drives in the background while you are doing something else
# This allows the program to continue processing without waiting for the write to complete hence things seem faster.
# for example, when you run this program and it says "Process finished with exit code 0" it still may have beeb
# saving things in the background. Expecially if the file was long
# Sometimes you want the data to be written out immediately e.g if the output is a screen
# and you want to see as it comes. With buffering, data can be written to screen from the buffer
# and then immediately overwritten with other data from the buffer. As the data scrolls up, the screen
# may appear to flicker.
# Closing a file causes the buffer to be flushed automatically.
# if you want your data to be written sooner, you can pass "flush=True" to cause the data to be written immediately
# This is not very important because modern computers are very powerful compared to when "flush" was developed
cities = ["Minneapolis", "St Paul", "Anoka", "Coon Rapids", "Blaine", "Fridley"] # list containing cities we want.
with open("MN_Cities.txt", 'w') as city_file: # Command to write
print(city_file) # This line not necessary. I just use it to view city_file
for city in cities: # loop through all the entries in variable "cities"
print(city, file=city_file, flush=True) # adding "flush"
print("="*60)
# ========================
# Reading a text file
# ========================
# Now we want to read the "MN_Cities.txt" file we created.
cities = [] # We define an empty list
print("Initial cities has: {}".format(cities)) # print show empty
with open("MN_Cities.txt", 'r') as city_file: # open MN_Cities.txt and save it as city_file
for city in city_file: # iterate through city_file
cities.append(city) # Then append every line to variable "cities"
print("Final cities has: {}".format(cities)) # This shows us all the cities. Notice the \n in results
print()
for city in cities: # We iterate through Cities and print line by line
print(city) # output here shows doubleline. We can remove this using print(city, end='') or using "strip" function below
print("="*60)
# ====================
# "strip" function
# =====================
# "strip" is used to remove a specified parameter or character from BEGGINING or END of a string
print("========== strip function examples ========")
print()
print("Minneapolis".strip('M')) # Strips M from the beggining
print("Minneapolis".strip('s')) # Strips s from the end
print("Minneapolis".strip('p')) # P is not stripped because it is not at the Beggining or End
print("Adelaide".strip('del')) # It only stips de which is at the end and ignores l. Does not touch the del after A
print()
print("="*60)
# In below, we want to remove the \n when we read "city_file" and append its contents to "cities"
# note that \n appears at the end of the lines hence can be removed
cities = [] # We define an empty list
print("Initial cities has: {}".format(cities)) # print show empty
with open("MN_Cities.txt", 'r') as city_file: # open MN_Cities.txt and save it as city_file
for city in city_file: # iterate through city_file
cities.append(city.strip('\n')) # we strip '\n here
print("Final cities has: {}".format(cities)) # Notice there is no \n in this result
print()
for city in cities: # We iterate through Cities and print line by line
print(city) # No more extra line because \n was stripped
print("="*60)
# ================================
# Write and read from text files
# ================================
# Everything you can see on the screen can be written into a text file
# However its not always possible to read it back in its original form
# We will show an example below, but first we get a refresher on tuples
# ======================
# Refresher on "tuple"
# ======================
imelda = "More Mayhem", "Imelda May", 2011, (
(1, "Pulling the rug"), (2, "Psycho"), (3, "Mayhem"), (4, "Kentish town walz"))
print(imelda)
print()
print("Album: {}".format(imelda[0]))
print("Title: {}".format(imelda[1]))
print("Year: {}".format(imelda[2]))
print("Tracks:")
track1, track2, track3, track4 = imelda[3] # unpacking
print(track1)
print(track2)
print(track3)
print(track4)
print("="*60)
# ==============================================
# You can do same thing above using for loop
# ==============================================
print()
print("Method 2 using for loop for 4th element")
print()
# We unpack tuple imelda and assign it to 4 variables
# Note that track will itself contain a tuple
title, artist, year, track = imelda
print(title)
print(artist)
print(year)
print(track) # This has a tuple in itself
print("="*20)
# you can also use a for loop to print the songs in track
print("Here are the songs in track:")
for song in track:
print(song)
print("="*60)
# =============================
# Writing into a file
# =============================
# Now we will give an example how you can write to a file
# But not read back from the file in the original form it was written
# This program creates a file imelda2.txt that is representative of the tuple imelda
# However there is no easy way to read it back into a tuple variable because it is now stored as a string
# We can use " eval" function to get content of the file back to a "tuple"
imelda = "More Mayhem", "Imelda May", 2011, (
(1, "Pulling the rug"), (2, "Psycho"), (3, "Mayhem"), (4, "Kentish town walz"))
print(imelda) # Results here are same as those in imelda2.txt. Stored as a string in imelda2.txt
print()
with open("imelda2.txt", 'w') as imelda_file:
print(imelda, file=imelda_file)
print("="*60)
# ====================
# "eval" function
# ====================
# We will use "eval" function to read back contents of imelda2.txt (stored as string) back to a tuple
# Note that above code already created imelda2.txt
# NOTE: using "eval" allows us to retrieve contents of imelda2.txt back to tuple
# but there are much better ways of doing it instead of using "eval"
# using "eval" is not a good way of retrieving data because the data could be changed or contain harmful instructions
# and the program would still execute it.
# its good to design programs without security vulnerabilities
with open("imelda2.txt", 'r') as imelda_file: # open imelda2.txt file and read
contents = imelda_file.readline() # use readline to read lines in imelda2.txt and assign results to contents
imelda = eval(contents) # Use "eval" function on "contents" to convert it to "tuple"
print("Below is imelda as a tuple")
print(imelda) # this is a printout of the tuple we created using "eval"
print()
title, artist, year, track = imelda # We unpack tuple imelda and assign its elements to these variables
print("Title = {}".format(title)) # Now we print the individual variables.
print("Artist = {}".format(artist))
print("Year = {}".format(year))
print("Track = {}".format(track))
# ===================
# built-in functions
# ===================
# Check built in functions options for open() on this link
# https://docs.python.org/2/library/functions.html
# =================================
# append" or "a" function of open
# =================================
# the function "a" used with open is used to append something to a file.
# Full description here: https://docs.python.org/2/library/functions.html#open
# Write a program to append the times table to our samples3.txt file
# We want the tables from 2 to 12 (similar to output from the for loop for multiplication
# The first column of members should be right justified.
# As an example, the 2 times table should look like this
# 1 times 2 is 2
# 2 times 2 is 4
# 3 times 2 is 6
# etc until
# 12 times 2 is 24
# This is the multiplication table to show you the results. We will comment it out
print()
print("Multiplication table")
for i in range(2,13): # When i is 1
for j in range(1,13): # j loops four times
print("{1:>2} times {0} is {2}".format(i, j, i*j)) # does multiplication until 2nd loop completes
print("============") # Change indent level on this print to see different formats
print("="*60)
# When you run this program, it will append the multiplication table above to sample3.txt
# Each time you run the program, it appends to the program
with open("sample3.txt", 'a') as tables: # Specify sample3.txt and use 'a' for append
for i in range(2,13):
for j in range(1,13):
print("{1:>2} times {0} is {2}".format(i, j, i*j), file=tables) # write to file. use print but specify file=tables
print("=" *20, file=tables) # separator line. Also use file=tables since you are also writing it to file
print("="*60)
# You can also create a new file with the multiplication table by using 'w'
with open("sample4.txt", 'a') as tables: # New file sample4.txt and use 'w' to write (create new one)
for i in range(2,13):
for j in range(1,13):
print("{1:>2} times {0} is {2}".format(i, j, i*j), file=tables) # write to file. use print but specify file=tables
print("=" *20, file=tables) # separator line. Also use file=tables since you are also writing it to file
|
3061ff62f2aff6b39086ca3e4b577fe801cda7dd | hawkinsbl/02-ObjectsFunctionsAndMethods | /src/m2_functions.py | 4,467 | 4.28125 | 4 | """
Practice DEFINING and CALLING
FUNCTIONS
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Aaron Wilkin, their colleagues, and Ben Hawkins.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
###############################################################################
# Done: 2.
# Allow this module to use the rosegraphics.py module by marking the
# src
# folder in this project as a "Sources Root", as follows:
#
# In the Project window (to the left), right click on the src folder,
# then select Mark Directory As ~ Sources Root.
#
###############################################################################
import rosegraphics as rg
import math
def main():
a = 3
b = 4
print(pythagoreantheorem(a,b))
construct('red',2)
"""
TESTS the functions that you will write below.
You write the tests per the _TODO_s below.
"""
###############################################################################
# DONE: 3a. Define a function immediately below this _TODO_.
# It takes two arguments that denote, for a right triangle,
# the lengths of the two sides adjacent to its right angle,
# and it returns the length of the hypotenuse of that triangle.
# HINT: Apply the Pythagorean theorem.
#
# You may name the function and its parameters whatever you wish.
#
# DONE: 3b. In main, CALL your function and print the returned value,
# to test whether you defined the function correctly.
#
###############################################################################
def pythagoreantheorem(a,b):
a2 = a**2
b2 = b**2
c = math.sqrt(a2+b2)
return(c)
###############################################################################
# Done: 4a. Define a function immediately below this _TODO_.
# It takes two arguments:
# -- a string that represents a color (e.g. 'red')
# -- a positive integer that represents the thickness of a Pen.
#
# The function should do the following (in the order listed):
# a. Constructs a TurtleWindow.
# b. Constructs two SimpleTurtles, where:
# - one has a Pen whose color is "green" and has the GIVEN thickness
# - - the other has a Pen whose color is the GIVEN color
# and whose thickness is 5
#
# Note: the "GIVEN" color means the PARAMETER that represents a color.
# Likewise, the "GIVEN" thickness means the PARAMETER for thickness.
#
# c. Makes the first (green) SimpleTurtle move FORWARD 100 pixels, and
# makes the other (thickness 5) SimpleTurtle move BACKWARD 100 pixels.
#
# d. Tells the TurtleWindow to wait until the mouse is clicked.
#
# You may name the function and its parameters whatever you wish.
#
# Done: 4b. In main, CALL your function at least TWICE (with different values
# for the arguments) to test whether you defined the function correctly.
#
###############################################################################
def construct(color,g):
window = rg.TurtleWindow()
turtle1 = rg.SimpleTurtle('turtle')
turtle1.pen = rg.Pen('green',g)
turtle2 = rg.SimpleTurtle('turtle')
turtle2.pen = rg.Pen(color,5)
turtle1.forward(100)
turtle2.backward(75)
window.close_on_mouse_click()
###############################################################################
# DONE: 5.
# COMMIT-and-PUSH your work (after changing this TO-DO to DONE).
#
# As a reminder, here is how you should do so:
# 1. Select VCS from the menu bar (above).
# 2. Choose Commit from the pull-down menu that appears.
# 3. In the Commit Changes window that pops up,
# press the Commit and Push button.
# Note: If you see only a Commit button:
# - HOVER over the Commit button
# (in the lower-right corner of the window)
# - CLICK on Commit and Push.
#
# COMMIT adds the changed work to the version control on your computer.
# PUSH adds the changed work into your Github repository in the "cloud".
#
# COMMIT-and-PUSH your work as often as you want, but at the least, commit
# and push after you have tested a module and believe that it is correct.
#
###############################################################################
# -----------------------------------------------------------------------------
# Calls main to start the ball rolling.
# -----------------------------------------------------------------------------
main()
|
ab7928a9cccd70ab19a687b649125169e5c7fbf7 | ahirapatel/dspguide-stuff | /ch04/homework-comp.py | 3,315 | 4.09375 | 4 | #!/usr/bin/env python
"""
CHAPTER 4: DSP SOFTWARE
"""
"""
This exercise looks at the problem of adding numbers that are very different
is size. Write a computer program(s) to complete the following.
1. Generate a 256 samples long sine wave with an amplitude of one, and a
frequency such that it completes 3 full periods in the 256 samples.
Represent each of the samples using single precision floating point. We
will call this signal, x[ ]
"""
def dothething(k):
import matplotlib.pyplot
def sin_wave():
"""
return a pair of lists with sample time in one list and output values in other
"""
from math import sin
from math import pi
num_samples = 256
sample_steps = 1 / num_samples
xdata, ydata = [], []
for i in range(num_samples):
x = i * sample_steps * 2*pi # Convert to radians with 2pi
y = sin(3*x)
xdata.append(i*sample_steps) # We want the time in seconds, not the radian values
ydata.append(y)
return xdata, ydata
t,x = sin_wave()
#matplotlib.pyplot.plot(t, x, marker='.')
#matplotlib.pyplot.title('256 samples of 3 periods')
#matplotlib.pyplot.xlabel('time')
#matplotlib.pyplot.ylabel("Signal Amplitude")
#matplotlib.pyplot.show()
"""
2. Add a constant, k = 300,000 to each of the samples in the signal.
3. Subtract the same constant, k, from each of the samples. Call this
reconstructed signal, y[ ]
4. Find the difference (i.e., the reconstruction error) between x[ ] and
y[]. Call this signal, d[ ].
5. Plot the reconstructed signal, y[ ], and the difference signal, d[ ].
"""
y = [val+k for val in x]
y = [val-k for val in y]
d = [old - new for old,new in zip(x,y)]
fig,ax1 = matplotlib.pyplot.subplots()
ax2 = ax1.twinx()
ax2.set_xlabel('time')
ax2.set_ylabel("Signal Amplitude")
ax1.set_ylabel("Error", color='r')
matplotlib.pyplot.title('Error of adding then subtracting {}'.format(k))
ax2.plot(t, y, marker='.')
ax1.plot(t, d, 'r', marker='.')
matplotlib.pyplot.show()
"""
6. Repeat steps 1-5 for k = 3,000,000.
7. Repeat steps 1-5 for k = 30,000,000.
"""
dothething(300000)
dothething(3000000)
dothething(30000000)
# Python does not have single precision so let's be excessive to get the
# point of this exercise
dothething(300000000000000)
dothething(3000000000000000)
dothething(30000000000000000)
"""
8. Answer the following questions:
a. "When floating point numbers of very different size are added, the
quantization noise on the [fill in the blank] number destroys the
information contained in the [fill in the blank] number. "
# large number
# small number
"""
"""
b. The results of step 7 show that the information in the reconstructed
signal is completely destroyed with k is equal to 30 million, or greater.
If this exercise were repeated with the sine wave of amplitude 0.001, how
large of value of k would be needed to destroy the information in the
reconstructed signal?
# No idea cuz I'm not using single precision floats. Oh well
c. If this exercise were repeated using double precision, how large of value
for k would be needed to destroy the information in the reconstructed
signal?
# See 6 and 7
"""
|
d896718118f379992bae542fbc0738abafb7751f | yulya2787/python_advanced | /less4/#1.py | 3,276 | 3.90625 | 4 | from abc import *
from datetime import date
class Person(metaclass=ABCMeta):
def __init__(self, name, year, month, day):
self.name = name
self.year = year
self.month = month
self.day = day
print('(Person: {0})'.format(self.name))
def __str__(self):
'''Returns complex number as a string'''
return '(%s, %s,%s,%s)' % (self.name, self.year, self.month, self.day)
def __repr__(self):
return '(%s, %s,%s,%s)' % (self.name, self.year, self.month, self.day)
@abstractmethod
def tell(self):
print(f'Name: {self.name}', end='\n')
@abstractmethod
def get_age(self):
today = date.today()
age = today.year - self.year
if today.month < self.month:
age -= 1
elif today.month == self.month and today.day < self.day:
age -= 1
return age
class Entrant(Person):
'''Абитуриент'''
def __init__(self, name, year, month, day, faculty):
Person.__init__(self, name, year, month, day)
self.faculty = faculty
print(f'Entrant: {self.name}, date of birth: {self.day}.{self.month}.{self.day}, faculty: {self.faculty} ',
end='\n')
def get_age(self):
age = super().get_age()
return age
def tell(self):
Person.tell(self)
print(f'Name: {self.name}', end='\n')
class Student(Person):
'''Студент'''
def __init__(self, name, year, month, day, faculty, year_of_study):
Person.__init__(self, name, year, month, day)
self.faculty = faculty
self.year_of_study = year_of_study
print(f'Student: {self.name}, date of birth: {self.day}.{self.month}.{self.day}, faculty: {self.faculty}, '
f'year_of_study: {self.year_of_study} ', end='\n')
def get_age(self):
age = super().get_age()
return age
def tell(self):
Person.tell(self)
print(f'Name: {self.name}', end='\n')
class Teacher(Person):
'''Преподаватель'''
def __init__(self, name, year, month, day, faculty, position, experience):
Person.__init__(self, name, year, month, day)
self.faculty = faculty
self.position = position
self.experience = experience
print(f'Teacher: {self.name}, date of birth: {self.day}.{self.month}.{self.day}, faculty: {self.faculty}, '
f'position: {self.position}, experience: {self.experience} ', end='\n')
def get_age(self):
age = super().get_age()
return age
def tell(self):
Person.tell(self)
print('Faculty: "{0}"'.format(self.faculty))
t = Teacher('Smith', 1965, 4, 1,'Art','Professor', 20)
s = Student('Johnson', 1999, 1, 12, 'Art', 1)
ent = Entrant('Williams', 2002, 3, 12, 'Art')
def age_returne(list_of_persons):
min_age = int(input('min age: ').strip())
list_of_age = list(filter(lambda x: min_age <= x.get_age(), list_of_persons))
return list_of_age
list_of_persons = [Entrant('Williams', 2005, 3, 12, 'Art'),
Student('Johnson', 1999, 1, 12, 'Art', 1),
Teacher('Smith', 1965, 4, 1,'Art','Professor', 20)]
l = []
for p in age_returne(list_of_persons):
l.append(p)
print(l)
|
63763b3630bae305ebb4cbc163edcf88a51c0fe2 | MESragelden/leetCode | /Contiguous Array2.py | 415 | 3.59375 | 4 | def findMaxLength(nums):
d = dict()
longest = 0
sum = 0
for i in range(len(nums)):
if nums[i] == 0:
sum -= 1
else :
sum += 1
if sum == 0 :
longest = i+1
if sum in d:
longest = max(longest,(i - d[sum]))
else :
d[sum] = i
return longest
print(findMaxLength([1,0,0,0,1,1])) |
23bcf2b555311c84123314d5a9747162584fd2b3 | Magictotal10/FMF-homework-2020spring | /homework8/ast.py | 3,993 | 3.78125 | 4 | from enum import Enum
from typing import List
# a utility class to represent the code you should fill in.
class Todo(Exception):
pass
########################################
# This bunch of code declare the syntax for the language C--, as we
# discussed in the class:
'''
bop ::= + | - | * | / | == | != | > | < | >= | <=
E ::= n | x | E bop E
S ::= skip
| x=E
| S;S
| f(E1, …, En)
| if(E, S, S)
| while(E, S)
F ::= f(x1, …, xn){S; return E;}
'''
##################################
# bops
class BOp(Enum):
ADD = "+"
MIN = "-"
MUL = "*"
DIV = "/"
EQ = "=="
NE = "!="
GT = ">"
GE = ">="
LT = "<"
LE = "<="
##########################################
# expressions
class Exp:
pass
class ExpNum(Exp):
def __init__(self, n: int):
self.num = n
def __str__(self):
return f"{self.num}"
class ExpVar(Exp):
def __init__(self, var: str):
self.var = var
def __str__(self):
return f"{self.var}"
class ExpBop(Exp):
def __init__(self, left: Exp, right: Exp, bop: BOp):
self.left = left
self.right = right
self.bop = bop
def __str__(self):
if isinstance(self.left, ExpBop):
left_str = f"({self.left})"
else:
left_str = f"{self.left}"
if isinstance(self.right, ExpBop):
right_str = f"({self.right})"
else:
right_str = f"{self.right}"
return f"{left_str} {self.bop.value} {right_str}"
###############################################
# statement
class Stm:
def __init__(self):
self.level = 0
def __repr__(self):
return str(self)
class StmAssign(Stm):
def __init__(self, var: str, exp: Exp):
super().__init__()
self.var = var
self.exp = exp
def __str__(self):
indent_space = self.level * "\t"
return f"{indent_space}{self.var} = {self.exp};\n"
class StmIf(Stm):
def __init__(self, exp: Exp, then_stms: List[Stm], else_stms: List[Stm]):
super().__init__()
self.exp = exp
self.then_stms = then_stms
self.else_stms = else_stms
def __str__(self):
# TODO: Exercise 1 Code Here
for stm in self.then_stms:
stm.level = self.level + 1
for stm in self.else_stms:
stm.level = self.level + 1
indent_space = self.level * "\t"
then_stms_str = "".join([str(stm) for stm in self.then_stms])
else_stms_str = "".join([str(stm) for stm in self.else_stms])
res = (f"{indent_space}if({self.exp}){{\n"
f"{then_stms_str}"
f"{indent_space}}}\n")
if len(else_stms_str):
res += (f"{indent_space}else{{\n"
f"{else_stms_str}"
f"{indent_space}}}\n")
return res
class StmWhile(Stm):
def __init__(self, exp: Exp, stms: List[Stm]):
super().__init__()
self.exp = exp
self.stms = stms
def __str__(self):
# TODO: Exercise 1 Code Here
for stm in self.stms:
stm.level = self.level + 1
indent_space = self.level * "\t"
stms_str = "".join([str(stm) for stm in self.stms])
return (f"{indent_space}while({self.exp}){{\n"
f"{stms_str}"
f"{indent_space}}}\n")
###############################################
# function
class Function:
def __init__(self, name: str, args: List[str], stms: List[Stm], ret: Exp):
self.name = name
self.args = args
self.stms = stms
self.ret = ret
def __str__(self):
arg_str = ",".join(self.args)
for stm in self.stms:
stm.level += 1
stms_str = "".join([str(stm) for stm in self.stms])
return (f"{self.name}({arg_str}){{\n"
f"{stms_str}"
f"\treturn {self.ret};\n"
f"}}\n")
|
d24308ddd7c6d2546375f1fcec6149edffcf15cd | Tepah/Aim-Stats-Graph | /stat_tracker.py | 5,948 | 3.6875 | 4 | import json
from datetime import datetime
from datetime import date
import matplotlib.pyplot as plt
import os
# TODO: Clean and refractor a bit
def add_new_mode(all_modes):
"""Adds a new mode to the json dictionary
Args:
all_modes (dictionary):
Returns:
[type]: [description]
"""
answer = input("Add the mode that you want to track: \n")
# Creates a new mode
all_modes.append({'name': answer, 'date': [], 'high': [], 'low': [],
'high_acc': [], 'low_acc': []})
return all_modes[-1]
def add_stats(mode):
"""Adds stats for the current game mode
Args:
mode (dictionary): The mode that we want to modify and add to.
"""
# TODO: Is this working?
today = date.today()
if not mode['date']:
_initialize_new_date(mode)
elif today.strftime('%Y-%m-%d') != mode["date"][-1]:
_initialize_new_date(mode)
mode = _input_scores(mode)
return mode
def _initialize_new_date(mode):
"""Creates a new date for the mode to add a new high and low
Args:
mode (Dictionary): The mode we're adding a new day to
"""
mode["date"].append(date.today())
mode['high'].append(0)
mode['low'].append(99999999)
mode['high_acc'].append(0)
mode['low_acc'].append(0)
def _input_scores(mode):
"""A function to input and place scores into the data
Args:
mode (dictionary): The mode that we want to modify and add to
Returns:
dictionary: a modified dictionary with new values.
"""
while True:
try:
score = float(input('Please put in your score: '))
acc = float(input('Please put in your accuracy(%): '))
if score > mode["high"][-1]:
mode['high'][-1] = score
mode['high_acc'][-1] = acc
if score < mode['low'][-1]:
mode['low'][-1] = score
mode['low_acc'][-1] = acc
except ValueError:
print('Please enter another value.')
continue
escape = input("Put in more scores? Y/N: ")
if escape.lower() == 'n':
break
return mode
def choose_mode(all_modes):
"""
Makes the user choose a choice an option from all the modes.
Args:
all_modes (Dictionary): All the modes that have been recorded
"""
while True:
print("Select a mode: ")
for value, mode in enumerate(all_modes):
print(f"{value}: {mode['name']}")
print(f"{value + 1}: Add new mode")
answer = int(input())
error = "That is not one of the choices. \n"
try:
if answer == (value + 1):
add_new_mode(all_modes)
answer = -1
elif answer < (value + 1) and answer >= 0:
for value, mode in enumerate(all_modes):
if answer == value:
mode_data = answer
else:
print(error)
continue
except ValueError:
print(error)
continue
break
return answer
def show_score_graph(full_data, index):
"""Puts information into lists to later put into a graph
Args:
full_data (Dictionary): All the data from the json file
index (int): selects which mode we want to check
"""
highs = full_data['modes'][index]['high']
lows = full_data['modes'][index]['low']
dates = []
for date in full_data['modes'][index]['date']:
try:
dates.append(datetime.strptime(date, '%Y-%m-%d'))
except TypeError:
dates.append(date)
_plot_graph(highs, lows, dates)
def _plot_graph(highs, lows, dates):
"""Plots the highs and lows in a graph
Args:
highs (list): A list of highs
lows (list): A list of lows
dates (list): A list of dates
"""
plt.style.use('dark_background')
fig, ax = plt.subplots()
ax.plot(dates, highs, c='blue', alpha=0.5)
ax.plot(dates, lows, c='red', alpha=0.5)
ax.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
# Format the plot
ax.set_title(f"Daily high and low scores for \
{full_data['modes'][index]['name']}")
ax.set_xlabel('', fontsize=16)
fig.autofmt_xdate()
ax.set_ylabel("Scores", fontsize=16)
ax.tick_params(axis='both', which='major', labelsize=16)
# TODO: How to do hover data points??
plt.show()
# Tries to create the folder needed
path = "data"
if os.path.isfile(path):
os.mkdir(path)
# read the data file into the system
filename = 'data/aim_data.json'
try:
with open(filename) as f:
full_data = json.load(f)
except FileNotFoundError:
# creates the data file if none is found.
full_data = {'modes': []}
with open(filename, 'w') as f:
json.dump(full_data, f)
while True:
new_mode = False
if full_data['modes']:
# reads the modes that have already been input and lets the user choose.
amount_before = len(full_data['modes'])
index = choose_mode(full_data['modes'])
if amount_before < len(full_data['modes']):
new_mode = True
else:
# adds new mode and sets it as default
add_new_mode(full_data['modes'])
new_mode = True
index = 0
if new_mode:
full_data['modes'][index] = add_stats(full_data['modes'][index])
else:
ans = input('Do you want to add scores to this mode for today? Y/N: ')
if ans.lower() == 'y':
full_data['modes'][index] = add_stats(full_data['modes'][index])
with open(filename, 'w') as f:
json.dump(full_data, f, default=str)
ans = input('Do you want to see your chart for highs and lows? Y/N: ')
if ans.lower() == 'y':
show_score_graph(full_data, index)
ans = input("Do you want to continue? Y/N: ")
if ans.lower() == 'n':
break
|
b0ebe7981e6231f7c190dc32cda2caf091e3e6d7 | matthew-ding/primes-project-2020 | /compareRelay.py | 635 | 3.5625 | 4 | import matplotlib.pyplot as plt
import broadcastRelay
import trivialRelay
print("Beginning Broadcast Relay")
broadcastCost = broadcastRelay.main()
xList = []
for i in range(len(broadcastCost)):
xList.append(i)
print("\n" + "Beginning Trivial Relay")
trivialCost, diameter = trivialRelay.main()
xList2 = []
for i in range(len(trivialCost)):
xList2.append(i * diameter)
plt.plot(xList, broadcastCost, label="New Broadcast")
plt.plot(xList2, trivialCost, label="Trivial Broadcast")
plt.xlabel("Iteration")
plt.ylabel("Cost")
plt.title("Novel vs Trivial Gradient Descent")
plt.legend()
plt.savefig("cost.png")
plt.show()
|
7541654fa121ca6d285f1c99e6b9d0a8194f6e3b | lauramatchett/hackbright-intro-more-lists-and-loops | /02-range-and-loops/fun_for_loops.py | 280 | 3.8125 | 4 | #for i in range (10,-1, -1):
# if (i == 0):
# print "Blast off!"
# else:
# print i,
#fruits = ["apples", "oranges", "bananas"]
#for f in range(5):
# print fruits,
def sum_nums(num):
sum = 0
for i in range(num):
sum = i + sum
return sum
print sum_nums(10) |
2b10d7f92ee9d5e32a0b795d8041f3e7615d12b7 | vrishank97/Project-Euler | /euler project -145.py | 214 | 3.78125 | 4 | L = 6 #Limit is expressed as 10^L
C = 0
for n in xrange(2, L+1):
if n % 2 == 0: C += 20 * pow(30, n//2 - 1)
elif n % 4 == 3: C += 100 * pow(500, n//4)
print "Reversible numbers below 10 ^", L, '=', C
|
e71c8120249ba37f05ed28b0cbac6ef5f17544db | skdlfjl/network_programming | /HW3_JIHEE_LEE/hw3_2.py | 1,091 | 3.875 | 4 | # 2. 아래 내용에 대한 프로그램(1개)을 작성하라.
d=[{'name':'Todd', 'phone':'555-1414', 'email':'todd@mail.net'}, {'name':'Helga', 'phone':'555-1618', 'email':'helga@mail.net'},
{'name':'Princess', 'phone':'555-3141', 'email':''}, {'name':'LJ', 'phone':'555-2718', 'email':'lj@mail.net'}]
# 전화번호가 8로 끝나는 사용자 이름을 출력하라.
print('전화번호가 8로 끝나는 사용자 이름 >>')
for i in d:
a = list(i.values())
if '8' in a[1]:
print(a[0])
# 이메일이 없는 사용자 이름을 출력하라.
print('이메일이 없는 사용자 이름 >>')
for i in d:
a = list(i.values())
if '' == a[2]:
print(a[0])
# 사용자 이름을 입력하면 전화번호, 이메일을 출력하라. 이름이 없으면 '이름이 없습니다'라는 메시지를 출력하라
name = input('please enter user name : ')
names = []
d_list = []
for i in d:
d_list.append(list(i.values()))
a = list(i.values())
names.append(a[0])
if name in names:
print(d_list[names.index(name)])
else :
print("이름이 없습니다.")
|
42217183482af357897b74b9e916f32c63c6ec4d | feliperod0519/python | /ransom.py | 1,309 | 3.53125 | 4 | import argparse
import os
import random
def get_args():
parser = argparse.ArgumentParser(description='Ransom Note',formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('text', metavar='text', help='Input text or file')
parser.add_argument('-s','--seed',help='Random seed',metavar='int',type=int,default=None)
args = parser.parse_args()
if os.path.isfile(args.text):
args.text = open(args.text).read().rstrip()
return args
def choose(char):
return char.upper() if random.choice([0, 1]) else char.lower()
def main():
args = get_args()
text = args.text
#random.seed(args.seed)
ransom = []
for char in text:
ransom.append(choose(char))
print(''.join(ransom))
ransom = []
for char in text:
ransom += choose(char)
print(''.join(ransom))
ransom = []
ransom = map(choose,args.text)
print(''.join(ransom))
ransom = []
ransom = map(lambda c:c.upper() if random.choice([0, 1]) else c.lower(),args.text)
print(''.join(ransom))
if __name__ == '__main__':
main()
#Map
#def calculateSquare(n):
# return n*n
#numbers = (1, 2, 3, 4)
#result = map(calculateSquare, numbers)
#print(result)
#Map w. lambda
#numbers = (1, 2, 3, 4)
#result = map(lambda x: x*x, numbers)
#print(result) |
5a3d3ca610efd26bea6b5ee67da63b9181c6fcfa | guido-lab/Tasker | /helperScripts/taskFunctions.py | 346 | 3.5 | 4 | import time
from abc import ABC, abstractmethod
class Tasks(ABC):
def __init__(self):
pass
@abstractmethod
def SumTwoNumbers(num_one, num_two):
time.sleep(1)
return num_one + num_two
@abstractmethod
def MultipleThreeNumbers(num_one, num_two, num_three):
return num_one * num_two * num_three
|
c18638fb42a0d6c8e8a296e1c2890d8b7eee7fac | aditiabhang/Face_Detection | /webcam_main.py | 1,115 | 3.59375 | 4 | import cv2
# Importing the pre-trained data
cascade_path = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascade_path)
# Capturing the video using cv2
video_capture = cv2.VideoCapture(0)
while True:
# Capturing the video frame-by-frame
ret, frame = video_capture.read()
# Recognition method works only on grayscale images, so we convert the rgb to grayscale
# **cv2 processes images only in BRG, instead of RGB.
gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray_img,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
# Drawing a square around the detected faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Showing the detected faces in the video frames
cv2.imshow("Detected Faces", frame)
# Closing the window when 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Releasing the captured video
video_capture.release()
cv2.destroyAllWindows() |
f7d8aeb63190f98f4e2b268a900fdd0dda81a2d6 | Tobijoe/LPTHW | /ex15.py | 645 | 3.984375 | 4 |
#from sys import argv argument
from sys import argv
#add arguments to argv, in this case script name (ex15.py)and the text sample (ex15sample.txt)
script, filename = argv
#set var txt to open filename given in argument
txt = open(filename)
#print formatted string, with filename
print(f"Here is your file {filename}")
#print contents of filename
print(txt.read())
#prompt for user input
print("Type the filename again:")
#set var file_again to ask for user input of filename
file_again = input("->")
#set text_again var to open given filename
txt_again = open(file_again)
#print contents of given filename in text_again
print(txt_again.read())
|
19641ffe5b289f275e6e5a22f2e2eff645e81243 | holbertra/Python-fundamentals | /data_structures/test.py | 362 | 3.859375 | 4 | my_numbers = [1, 2, 3, 4, 5]
def sum_recurs(numbers, count):
print(f'calling sum_recurs {count} times')
count += 1
if len(numbers) == 1:
return numbers[0]
else:
print(f'from else: returning {numbers[0]} + {numbers[1:]}')
return numbers[0] + sum_recurs(numbers[1:], count)
my_count = 1
sum_recurs(my_numbers, my_count)
|
6d76e1e43f7974bfe9dcffc114682a6a758af344 | songyongzhuang/PythonCode_office | /lemon/python22/lemon_06_190828_for_while_函数/优秀作业_0828/Yuan_HomeWork_0828_02.py | 451 | 3.84375 | 4 | # -*-coding=utf-8-*-
# 2.分别使用for和while打印九九乘法表,格式:每项数据之间空一个Tab键,可以使用"\t"
# for方法
for i in range(1, 10):
for j in range(1, i+1):
print("{} * {} = {}".format(j, i, j*i), end="\t")
print()
print("*" * 120)
# while方法
i = 1
while i <= 9:
j = 1
while j <= i:
print("{} * {} = {}".format(j, i, j * i), end="\t")
j += 1
i += 1
print()
|
592993959bec9722c6273a79ed0bb989102e55b4 | vineetwani/PythonDevelopment | /ListAndSetBasics.py | 1,056 | 4.15625 | 4 | #Define a list, set
#Output of Function listBasics:
# <class 'list'>
# [['Punit', 79], ['Vineet', 66]]
# ['Punit', 'Vineet']
# [79, 66]
def listBasics():
#l1=list() Can define like this as well
l1=[]
print(type(l1))
l1.insert(0,["Vineet",66])
l1.insert(0,["Punit",79])
#l1=[["Vineet",66],["Punit",79]]
print(l1)
print([name for name,marks in l1])
print([marks for name,marks in l1])
#Output of Function setBasics:
# <class 'dict'>
# <class 'set'>
# <class 'set'>
# {44, 22}
def setBasics():
#Empty curly braces {} will make an empty dictionary in Python.
s={}
print(type(s))
s1={ 13 , 12 }
print(type(s1))
#To make a set without any elements, we use the set() function without any argument.
s2=set()
print(type(s2))
#Sets are mutable. However, since they are unordered, indexing has no meaning.
s2.add(22)
s2.add(44)
s2.add(22)
print(s2)
if __name__ == "__main__":
#listBasics()
setBasics() |
9f16cbcb2d2c93422411cc9c1b5d767c976ef33c | buckuw/pynet-ons-oct17 | /day1/exercises_day1/str2.py | 176 | 3.875 | 4 | #!/usr/bin/env python
ip_addr = input("Gimme an IP: ")
ip_addr = ip_addr.split(".")
print('{:<12}{:<12}{:<12}{:<12}'.format(ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3]))
|
73919ce5023cfd59dc6c1296126f1677700f4786 | almog20-meet/meet2018y1final-proj | /test.py | 2,025 | 4.25 | 4 | import turtle
import random
#make turtles
turtle.tracer(1,0) #removes delay
adam = turtle.Turtle()
valeria = turtle.Turtle()
valeria.shape("square") # so you can tell which turtle is which
player = turtle.Turtle()
valeria.up()
adam.up()
my_turtles = [adam, valeria] # this important
#make constant values, display screen
WIDTH = 1000
HEIGHT = 700
MAX_X = WIDTH/2 - 20 # -20 so that falling items don't touch edges
MAX_Y = HEIGHT/2 -20 # -20 so that falling items don't touch edges
turtle.setup(WIDTH, HEIGHT) # makes a screen with width 1000, height 700
DISTANCE = 10 # how far the turtles move each time step (decrease to move slower)
TIME_STEP = 10 # 10 milliseconds (1000 ms = 1 s) Increase to move slower
def move_turtle():
for t in my_turtles:
x,y = t.pos()
t.goto(x,y-DISTANCE) # move turtles in list down
# insert code to move player here! (Hint: it should be pretty similar to snake)
check_edge() # check if turtles hit the bottom edge
check_player() # check if player is hit by falling turtles
turtle.ontimer(move_turtle, 10)
# generates random x values for the falling items
def rand_x():
return random.randint(-MAX_X, MAX_X)
'''
Hides the turtle if it is below bottom edge
This turtle will continue to fall until 10 is randomly selected.
Think of it like rolling a 10 sided dice and waiting for a 10 to
be rolled. This causes the items to fall at random times.
'''
def check_edge():
for t in my_turtles:
x,y = t.pos()
if y <= -MAX_Y:
t.hideturtle()
# decrease rate at which objects start falling by increasing range. Ex (1,20)
if random.randint(1,10) == 10:
t.goto(rand_x(),MAX_Y)
t.showturtle()
#checks if player has been hit by falling turtle
def check_player():
for t in my_turtles:
if player.pos() == t.pos():
quit()
# first time the turtles fall
for t in my_turtles:
t.goto(rand_x(),-MAX_Y)
move_turtle() #this must be the last line of your code.
|
9deb02aa1b78807192a9c57d723396b909ea1242 | runley/KazTranslit | /Ascii changer/test.py | 1,110 | 3.515625 | 4 | import tkinter as tk
from tkinter import filedialog as fd
def callback():
name= fd.askopenfilename()
print(name)
def documentKTL(): #top level func to create a new window as Toplevel
docKTL = tk.Toplevel(bg = "#f16161")
docKTL.title('Document to Text - KTL')
global directory
global saveDirectory
#row 0
logotxt = tk.Label(callback, text="TransKazLit", bg="#f16161", fg="white",font="Bahnschrift 24 bold")
logotxt.grid(row=0, column=0, padx=10, pady=5)
#row 1
btn = tk.Button(docKTL, text="Choose a file", command=askFile, font="none 14", bg="#EF4A4A", fg="white", width=12, height=1)
btn.grid(row=1, column=0, padx=5, pady=5)
consoleUI = Text(docKTL, height = 20, width = 50) #consoleUI element
consoleUI.grid(row=1, column=1, pady = 5, padx = 5, columnspan=2, rowspan=5)
errmsg = 'Error!'
btn = tk.Button( text="Document to Text", command=documentKTL, font="none 14", bg="#EF4A4A", fg="white", width=20, height=5)
btn.pack(fill=tk.X)
tk.Button(text='Click to Open File',
command=callback).pack(fill=tk.X)
tk.mainloop()
|
42ef9a5adb37520edc405d2e85085dd4d3c8776d | P0LISH-SAUSAGE/python3 | /tester.py | 127 | 3.671875 | 4 | test_str = "Hey, I'm a string, and I have a lot of characters...cool!"
print (test_str)
print ("String length:", len(test_str)) |
d5a72710057b2da78071b19790533af46546819d | knight-byte/Codeforces-Problemset-Solution | /Python/A_Replacing_Elements.py | 560 | 3.53125 | 4 | '''
Author : knight_byte
File : A_Replacing_Elements.py
Created on : 2021-04-14 09:55:54
'''
def min_sum(arr, i, d):
for j in range(len(arr)-1):
for k in range(j+1, len(arr)):
if j != i and k != 0 and arr[j]+arr[k] <= d:
return arr[j]+arr[k]
return -1
def main():
n, d = map(int, input().split())
arr = sorted(list(map(int, input().split())))
print("YES" if min(arr[-1], arr[0]+arr[1]) <= d else "NO")
if __name__ == '__main__':
t = int(input())
for _ in range(t):
main()
|
68c15adf3245d7337047f9f63634d61ef680e0a3 | laasya15g/looping | /fibanaaccinumbers and positive range.py | 916 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[16]:
terms=int(input("enter the number of terms:"))
i=0
j=1 #initialsing the first 2 numbers
count=0;
if terms<=0 :
print("print the valid postive number")
terms=int(input("enter the number of terms:"))
elif terms == 1 :
print("fibancci series:1")
else:
pass
print("fibanacci sequence for given no of terms","%i"%terms)
while count<=terms :
k=i+j
print(i)
i=j
j=k
count+=1
# In[34]:
list1=[14,34,-87,98,-43,21,-65]
print(list1)
for iterate in list1:
if iterate > 0:
print(iterate,",",end=" ")
print( )
list2=[12,14,-54,89,67,-34]
print(list2)
new_list = list(filter(lambda n: n>0 ,list2)) #we can use lamba for single iteration than looping for functions and filter
#and check the iteratable for the given list with the help of function
print(new_list)
# In[ ]:
|
dd713d2b6770954815de1b1830fa44b3ccee5a53 | YoungXu06/MachineLearning | /kNN/kd tree/BinaryTree.py | 2,132 | 3.84375 | 4 | # -*- coding: utf-8 -*-
'''
NOTE: This Code is borrowed from: http://blog.csdn.net/v_victor/article/details/51131283
Created on 2017年9月24日
@author: XY
'''
class BinaryTree(object):
'''
创建结点
'''
class __node(object):
def __init__(self, value, k,left=None, right=None):
self.value = value
self.left = left
self.right = right
self.s = k
def getValue(self):
return self.value
def setValue(self, value):
self.value = value
def getLeft(self):
return self.left
def getRight(self):
return self.right
def setLeft(self, newLeft):
self.left = newLeft
def setRight(self, newRight):
self.right = newRight
def getS(self):
return self.s
def __iter__(self):
if self.left != None:
for elem in self.left:
yield elem
yield self.value
if self.right != None:
for elem in self.right:
yield elem
'''
创建根
'''
def __init__(self, length):
self.length = length
self.root = None
def insert(self, value):
k = 0
length = self.length
def __insert(k, root, value):
index = k % length # length是特征空间维数,k是树的深度
k += 1
if root == None:
return BinaryTree.__node(value, index)
if value[index] < root.getValue()[index]:
root.setLeft(__insert(k, root.getLeft(), value))
else:
root.setRight(__insert(k, root.getRight(), value))
return root
self.root = __insert(k, self.root, value)
def __iter__(self):
if self.root != None:
return self.root.__iter__()
else:
return [].__iter__()
def main():
pass
if __name__=='__main__':
main()
|
857d5e0eb9cde724ef86b7e2da10c73eb6777e6e | tomki1/bin-packing | /binpack.py | 5,609 | 3.875 | 4 | # binpack.py
# name: Kimberly Tom
# CS325 Homework 8
import sys
import os
# create a Bin class
# https://www.w3schools.com/python/python_classes.asp
class Bin:
# creating a new bin
def __init__(self, capacity):
self.capacity = capacity
# setting capacity
def createCapacity(self, capacity):
self.capacity = capacity
# put each item as you come to it into the first (earliest opened) bin into which it fits
# if there is no available bin then open a new bin
# https://www.geeksforgeeks.org/bin-packing-problem-minimize-number-of-used-bins/
def firstFitAlgorithm(numItems, binCapacity, itemWeights):
# numberOfBins holds the total number of bins we are using, start with 1 bin
numberOfBins = 1
# create an array totalBins to hold all the bins we are using
totalBins = []
# create a bin with max capacity
makeBin = Bin(binCapacity)
# add the created bin to totalBins array
totalBins.append(makeBin)
# place items into the bins
for i in range(numItems):
itemStored = 0
# go through the bins
for b in range(numberOfBins):
# if item can fit into a bin we already created, store in that bin
if itemWeights[i] <= totalBins[b].capacity:
totalBins[b].capacity = totalBins[b].capacity - itemWeights[i]
itemStored = 1
break
# if not, store in a new bin
if not itemStored:
newBinCapacity = binCapacity - itemWeights[i]
makeBin = Bin(newBinCapacity)
totalBins.append(makeBin)
numberOfBins = numberOfBins + 1
return numberOfBins
# first sort the items in decreasing order by size, then use First-Fit on the resulting list
def decreasingAlgorithm(numItems, binCapacity, itemWeights):
# make a copy of the array itemWEights
decreasingWeights = itemWeights.copy()
# sort the array decreasingWeights from greatest to least weight
# https://www.geeksforgeeks.org/python-list-sort/
decreasingWeights.sort(reverse = True)
# call firstFitAlgorithm function and store in number of bins then return the number of bins
numberOfBins = firstFitAlgorithm(numItems, binCapacity, decreasingWeights)
return numberOfBins
# Place the items in order in which they arrive. Place next item into bin which will leave the least room
# left over after the item is placed in the bin. If it doesn't fit in any bin, start new bin
def bestFitAlgorithm(numItems, binCapacity, itemWeights):
# numberOfBins holds the total number of bins we are using, start with 1 bin
numberOfBins = 1
# create an array totalBins to hold all the bins we are using
totalBins = []
# create a bin with max capacity
makeBin = Bin(binCapacity)
# add the created bin to totalBins array
totalBins.append(makeBin)
# place items into the bins
for i in range(numItems):
tempStore = -1
leastRoomLeftOver = binCapacity
currentBinRoomLeftOver = 0
# go through the bins
for b in range(numberOfBins):
# if item can fit into a bin we already created, potentially store in that bin
if itemWeights[i] <= totalBins[b].capacity:
currentBinRoomLeftOver = totalBins[b].capacity - itemWeights[i]
# if the current bin has less room left over than the prior least room left over bin, update temp bin
if currentBinRoomLeftOver < leastRoomLeftOver:
leastRoomLeftOver = currentBinRoomLeftOver
tempStore = totalBins[b]
# place the item in the bin with the least amount of room leftover
if tempStore != -1:
tempStore.capacity = tempStore.capacity - itemWeights[i]
# if no bin has enough room, store in a new bin
else:
newBinCapacity = binCapacity - itemWeights[i]
makeBin = Bin(newBinCapacity)
totalBins.append(makeBin)
numberOfBins = numberOfBins + 1
return numberOfBins
def main():
# open a file for reading
data_file = open("bin.txt", "r")
array = []
currentCase = 0
# for each line in the data file
for line in data_file:
array.extend(line.split())
array = list(map(int,array))
testCaseCount = array.pop(0)
# for each case in the number of test cases
for t in range(testCaseCount):
# store each bin's capacity
binCapacity = 0
# store the number of items in a test case
numItems = 0
# array to store the items' weights for a test case
itemWeights = []
# read number from file and store in binCapacity and numItems
binCapacity = array.pop(0)
numItems = array.pop(0)
# for each item in the number of items
for i in range(numItems):
# store item weights in the itemWeights array
itemWeights.append(array.pop(0))
# print results
print("\nTest Case #", currentCase + 1)
currentCase += 1
print(" First Fit: ", firstFitAlgorithm(numItems, binCapacity, itemWeights))
print(" First Fit Decreasing: ", decreasingAlgorithm(numItems, binCapacity, itemWeights))
print(" Best Fit: ", bestFitAlgorithm(numItems, binCapacity, itemWeights))
data_file.close()
# call main function to start program
if __name__ == '__main__':
main() |
f804d471ad7f2eb042981ddcfaa233c3a2c04167 | andy-ang/Codility_attempts | /1_1_BinaryGap.py | 605 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 1 14:02:04 2020
@author: andya
"""
# find longest 0
def solution(N):
bin_N = '{0:08b}'.format(N)
start = 0
for i in range(len(bin_N)):
if bin_N[i] == '1':
start = i
break
count =0
longest_0 = 0
for i in range(start, len(bin_N)):
if bin_N[i] == '0':
count += 1
else:
if longest_0 <= count:
longest_0 = count
count = 0
return longest_0
solution(15)
solution(147)
solution(483)
solution(647)
|
8551b781c01715f7c16b57c775f442b44f51ab2e | bhenne/PhotoPrivateMetadataViewer | /osm_map/lib/tilenames.py | 2,418 | 3.5 | 4 | #!/usr/bin/env python
"""Translates between lat/long and the slippy-map tile numbering scheme
http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames
@author: Oliver White
@date: 2007
@license: This file is public-domain.
"""
__author__ = "Oliver White"
__copyright__ = "(c) 2007, Oliver White"
__license__ = "This file is public-domain."
from math import *
def numTiles(z):
return(pow(2, z))
def sec(x):
return(1 / cos(x))
def latlon2relativeXY(lat, lon):
x = (lon + 180) / 360
y = (1 - log(tan(radians(lat)) + sec(radians(lat))) / pi) / 2
return(x, y)
def latlon2xy(lat, lon, z):
n = numTiles(z)
x, y = latlon2relativeXY(lat, lon)
return(int(n * x), int(n * y))
def tileXY(lat, lon, z):
x, y = latlon2xy(lat, lon, z)
return(int(x), int(y))
def xy2latlon(x, y, z):
n = numTiles(z)
relY = y / n
lat = mercatorToLat(pi * (1 - 2 * relY))
lon = -180.0 + 360.0 * x / n
return(lat, lon)
def latEdges(y, z):
n = numTiles(z)
unit = 1 / n
relY1 = y * unit
relY2 = relY1 + unit
lat1 = mercatorToLat(pi * (1 - 2 * relY1))
lat2 = mercatorToLat(pi * (1 - 2 * relY2))
return(lat1, lat2)
def lonEdges(x, z):
n = numTiles(z)
unit = 360 / n
lon1 = -180 + x * unit
lon2 = lon1 + unit
return(lon1, lon2)
def tileEdges(x, y, z):
lat1, lat2 = latEdges(y, z)
lon1, lon2 = lonEdges(x, z)
return((lat2, lon1, lat1, lon2)) # S,W,N,E
def mercatorToLat(mercatorY):
return(degrees(atan(sinh(mercatorY))))
def tileSizePixels():
return(256)
def tileLayerExt(layer):
if(layer in ('oam')):
return('jpg')
return('png')
def tileLayerBase(layer):
layers = {"tah": "http://cassini.toolserver.org:8080/http://a.tile.openstreetmap.org/+http://toolserver.org/~cmarqu/hill/",
#"tah": "http://tah.openstreetmap.org/Tiles/tile/",
"oam": "http://oam1.hypercube.telascience.org/tiles/1.0.0/openaerialmap-900913/",
"mapnik": "http://tile.openstreetmap.org/mapnik/"
}
return(layers[layer])
def tileURL(x, y, z, layer):
return "%s%d/%d/%d.%s" % (tileLayerBase(layer), z, x, y, tileLayerExt(layer))
if __name__ == "__main__":
for z in range(0,18):
x,y = tileXY(52.37930, 9.72310, z)
s,w,n,e = tileEdges(x,y,z)
print "%d: %d,%d --> %1.3f :: %1.3f, %1.3f :: %1.3f" % (z,x,y,s,n,w,e)
#print "<img src='%s'><br>" % tileURL(x,y,z) |
388e21a1646bbe9501cc3e3c056f7579f434be3d | houhailun/leetcode | /数组/leetcode561_数组拆分.py | 929 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Time : 2019/7/2 15:39
@Author : Hou hailun
@File : leetcode561_数组拆分.py
"""
print(__doc__)
"""
给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。
示例 1:
输入: [1,4,3,2]
输出: 4
解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4)
"""
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 方法1:排序后相邻2个元素作为1对,第1个数小,全部累加即可
# nums.sort()
# ret = 0
# for i in range(0, len(nums), 2):
# ret += nums[i]
# return ret
# 方法2:一行代码实现
return sum(sorted(nums)[::2])
obj = Solution()
ret = obj.arrayPairSum([1,4,3,2])
print(ret) |
edfae68fe3e00ad6c77d9a0ff507fd80fc339c4a | Deepakdd1402/Body-mass-index-BMI- | /Body mass index (BMI).py | 736 | 4.1875 | 4 | print('\033[1;34;40m Body mass index (BMI) CALCULATOR \n ')
print("\033[1;32;40m")
print(" Enter the following details to calculate your Body mass index (BMI) \n ")
Height=float(input(" Enter your height in centimeters(ex:175) : "))
Weight=float(input(" Enter your Weight in Kg: "))
Height = Height/100
BMI=Weight/(Height*Height)
print("your Body Mass Index is: ",BMI)
if(BMI>0):
if(BMI<=16):
print("you are severely underweight")
elif(BMI<=18.5):
print("you are underweight")
elif(BMI<=25):
print("you are Healthy")
elif(BMI<=30):
print("you are overweight ")
else: print("you are severely overweight")
else:("enter valid details")
print("\n\033[1;37;40m ©DEEPAK DHARSHAN \033[0;37;40m\n")
|
0f41f1b872ad047bcc7638d9de931edba24500eb | lihongwen1/XB1929_- | /ch04/if_else.py | 131 | 3.75 | 4 | num = int(input('請輸入一個整數?'))
if num%5:
print(num, '不是5的倍數')
else:
print(num, '為5的倍數')
|
1ae0f1aeb55762f604ceb435f16453b0e54189c5 | laithfayizhussein/data-structures-and-algorithm | /python/code_challenges/linked_list/linked_list/ll_zip.py | 967 | 3.875 | 4 | from linked_list import (
LinkedList ,
)
def zip_ll(ll1, ll2):
current1 = ll1.head
current2 = ll2.head
if current1 == None or current2 == None:
if current1:
return ll1.__str__()
elif current2:
return ll2.__str__()
else:
return " the linked list both empty"
vlist = []
while current1 or current2:
if(current1):
vlist+=[current1.value]
current1 = current1.next
if(current2):
vlist+=[current2.value]
current2 = current2.next
new=''
for i in vlist:
new+=f'( {i} ) -> '
new+='None'
return new
#test both linked list
if __name__ == "__main__":
ll1 = LinkedList()
ll1.append(1)
ll1.append(3)
ll1.append(5)
ll1.append(7)
ll2 = LinkedList()
ll2.append(2)
ll2.append(4)
ll2.append(6)
print(ll1.__str__())
print(ll2.__str__())
print(zip_ll(ll1, ll2))
|
eed72dc8d8c2edc5c90d6a1b729d07390a091f6f | zhudingsuifeng/python | /offer/fibonacci.py | 397 | 3.96875 | 4 | #!/usr/bin/env python3
#coding = utf-8
class Solution:
# @classmethod
def Fibonacci(self,n):
# starting from 0
if n < 2:
return n
l = [0]*(n+1)
l[1], l[2] = 1, 1
for i in range(3, n+1):
l[i] = l[i-1] + l[i-2]
return l[-1]
if __name__ == "__main__":
n = int(input())
f = Solution()
print(f.Fibonacci(n))
|
bba0bcabed225f6def2e3bdced98e8ca640c5438 | brpadilha/exercicioscursoemvideo | /DesafiosComFunctions/Desafio 022 - Mudança de tamanho da letra.py | 494 | 3.71875 | 4 | def maiusculo (x):
return x.upper()
def minusculo(x):
return x.lower()
def contar_letras_nome_todo(x):
x=len(x)-x.count(' ')
return x
def contar_letras_nome(x):
x=x.split()
return x
nome=str(input('Digite seu nome todo: ')).strip()
maiusc=maiusculo(nome)
minusc=minusculo(nome)
contar_todo=contar_letras_nome_todo(nome)
primeiro=contar_letras_nome(nome)
print(maiusc)
print(minusc)
print(contar_letras_nome_todo(nome))
print(len(primeiro[0])) |
3d6daf142591ed572946f5bbe2c1310fbb731763 | kentotakeuchi/data-structures-and-algorithms | /leetcode/easy/counting-words-with-a-given-prefix.py | 223 | 3.5625 | 4 | # https://leetcode.com/problems/counting-words-with-a-given-prefix/
class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
return sum(w.find(pref) == 0 for w in words)
# True is equal to 1
|
b51e335710c723e6a64f4e3a4d7f086cdb57548c | wwtang/code02 | /craking/BFS.py | 1,619 | 4.1875 | 4 | """
Implement bfs in python
"""
graph = {
'1': ['2', '3', '4'],
'2': ['5', '6'],
'5': ['9', '10'],
'4': ['7', '8'],
'7': ['11', '12']
}
def bfs(graph, start, end):
# maintain a queue of paths
queue = []
# push the first path into the queue
queue.append([start])
while queue:
# get the first path from the queue, path is a list,
path = queue.pop(0)
# print"path, %s"%path
# get the last node from the path
node = path[-1]
# path found
if node == end:
return path
# enumerate all adjacent nodes, construct a new path and push it into the queue, create a new path with each of its child
for adjacent in graph.get(node, []):
print "path is %s"%path
new_path = list(path)
print "The raw path is %s" %new_path
new_path.append(adjacent)
print"new_path %s"%new_path
# print
# print "Before enqueue, the queue is %s"%queue
queue.append(new_path)
# print "after enqueue, the enqueue is %s "% queue
# print
def traceBack(parent, start, end):
path = [end]
while path[-1] != start:
path.append(parent[path[-1]])
path.reverse()
return path
def bfs1(graph, start, end):
parent = {}
Q = [start]
while Q:
node = Q.pop(0)
if node == end:
return traceBack(parent, start, end)
for adj in graph.get(node, []):
Q.append(adj)
parent[adj] = node
print parent
def main():
print bfs1(graph, '1', '11')
if __name__=="__main__":
main() |
c674b252ad05bc0d137cee4864196eb9933ad666 | SewonShin/BLOCKCHAINSCHOOL | /Python Code 1/HelloCoding/testmodule/main.py | 5,430 | 3.859375 | 4 | class Test:
def __init__(self):
# # 클래스 선언
# class Student:
# count = 0
# # 생성자
# def __init__(self, name, korean, math, english, science):
# Student.count += 1
# self.name = name
# self.korean = korean
# self.math = math
# self.english = english
# self.science = science
# @classmethod
# def count(cls):
# print(Student.count)
# Student.count()
# a = Student()
# a.count()
# print(student_count)
# # 클래스 선언
# class Student:
# # 생성자
# def __init__(self, name, korean, math, english, science):
# self.name = name
# self.korean = korean
# self.math = math
# self.english = english
# self.science = science
# def get_sum(self):
# return self.korean + self.math + self.english + self.science
# def get_average(self):
# return self.get_sum() / 4
# def __str__(self):
# return "{}\t{}\t{}".format(self.name, self.get_sum(), self.get_average())
# def __eq__ (self, value):
# print("eq 함수가 호출되었습니다")
# return 0
# # 학생 리스트를 선언합니다.
# a = Student("윤인성", 87, 98, 88, 95)
# a == a
# # 클래스 선언
# class Student:
# # 생성자
# def __init__(self, name, korean, math, english, science):
# self.name = name
# self.korean = korean
# self.math = math
# self.english = english
# self.science = science
# def get_sum(self):
# return self.korean + self.math + self.english + self.science
# def get_average(self):
# return self.get_sum() / 4
# def to_string(self):
# return "{}\t{}\t{}".format(self.name, self.get_sum(), self.get_average())
# # 학생 리스트를 선언합니다.
# students = [
# Student("윤인성", 87, 98, 88, 95),
# Student("연하진", 92, 98, 96, 98),
# Student("구지연", 76, 96, 94, 90),
# Student("나선주", 98, 92, 96, 92),
# Student("윤아린", 95, 98, 98, 98),
# Student("윤명월", 64, 88, 92, 92),
# Student("김미화", 82, 86, 98, 88),
# Student("김연화", 88, 74, 78, 92),
# Student("박아현", 97, 92, 88, 95),
# Student("서준서", 45, 52, 72, 78)
# ]
# #학생 한 명씩 반복합니다.
# print("이름", "총점", "평균", sep="\t")
# for student in students:
# #출력합니다.
# print(student.to_string())
# # 딕셔너리를 리턴하는 함수를 선언합니다.
# def create_student(name, korean, math, english, science):
# return {
# "name": name,
# "korea": korean,
# "math": math,
# "english": english,
# "science": science
# }
# # 학생을 처리하는 함수를 선언합니다.
# def student_get_sum(student):
# return student["korean"] + student["math"] + student["english"] + student["science"]
# def student_get_average(student):
# return student_get_sum / 4
# def student_to_string(student):
# return "{}\t{}\t{}".format(student["name"]), student_get_sum(student), student_get_average(student))
# # 학생 리스트를 선언합니다.
# students = [
# create_student("윤인성", 87, 98, 88, 95),
# create_student("연하진", 92, 98, 96, 98),
# create_student("구지연", 76, 96, 94, 90),
# create_student("나선주", 98, 92, 96, 92),
# create_student("윤아린", 95, 98, 98, 98),
# create_student("윤명월", 64, 88, 92, 92),
# create_student("김미화", 82, 86, 98, 88),
# create_student("김연화", 88, 74, 78, 92),
# create_student("박아현", 97, 92, 88, 95),
# create_student("서준서", 45, 52, 72, 78)
# ]
# # 학생의 리스트를 선언합니다.
# students =[
# {"name": "윤인성", "korean": 87, "math": 98, "english": 88, "science": 95 },
# {"name": "연하진", "korean": 92, "math": 98, "english": 96, "science": 98 },
# {"name": "구지연", "korean": 76, "math": 96, "english": 94, "science": 90 },
# {"name": "나선주", "korean": 98, "math": 92, "english": 96, "science": 92 },
# {"name": "윤아린", "korean": 95, "math": 98, "english": 98, "science": 98 },
# {"name": "윤명월", "korean": 64, "math": 88, "english": 92, "science": 92 },
# {"name": "김미화", "korean": 82, "math": 86, "english": 98, "science": 88 },
# {"name": "김연화", "korean": 88, "math": 74, "english": 78, "science": 92 },
# {"name": "박아연", "korean": 97, "math": 92, "english": 88, "science": 95 },
# {"name": "서준서", "korean": 45, "math": 52, "english": 72, "science": 78 }
# ]
# # 학생을 한 명씩 반복합니다.
# print("이름", "총점", "평균", sep="\t")
# for student in students:
# # 점수의 총점과 평균을 구합니다.
# score_sum = student["korean"] + student["math"] +\
# student["english"] + student["science"]
# score_average = score_sum / 4
# # 출력합니다.
# print(student["name"], score_sum, score_average, sep="\t")
# import test_module as tm
# print("메인 파일입니다")
# print(__name__)
# clsimport test_module as tm
# print(tm.PI)
# input_num = tm.number_input()
# print(input_num) |
eed5f180330bb91bcb93553130424093c7dc542a | abmish/pyprograms | /100Py/Ex78.py | 195 | 3.8125 | 4 | """
Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.
"""
import random
print random.sample([num for num in range(100, 200) if num%2 == 0], 5) |
fa12b6b1ef08568b82ef3ca5ae4a11fa99834fef | freebz/Learning-Python | /ch38/getattr_v-getattr.py | 978 | 4.21875 | 4 | class GetAttr:
attr1 = 1
def __init__(self):
self.attr2 = 2
def __getattr__(self, attr): # 정의되지 않은 속성에 대해서만 호출됨
print('get: ' + attr) # attr1 제외: 클래스에서 상속함
if attr == 'attr3': # attr2 제외: 인스턴스에 저장됨
return 3
else:
raise AttributeError(attr)
X = GetAttr()
print(X.attr1)
print(X.attr2)
print(X.attr3)
print('-'*20)
class GetAttribute(object): # (object)는 2.X에서만 필요
attr1 = 1
def __init__(self):
self.attr2 = 2
def __getattribute__(self, attr): # 모든 속성 가져오기
print('get: ' + attr) # 여기서는 슈퍼클래스를 이용해 루프를 방지
if attr == 'attr3':
return 3
else:
return object.__getattribute__(self, attr)
X = GetAttribute()
print(X.attr1)
print(X.attr2)
print(X.attr3)
|
95e49b7983cf84c2c0b9d94fe2f1a1b41edaacfc | alexmatros/codingbat-solutions | /python/logic-2/make_chocolate.py | 243 | 3.578125 | 4 | def make_chocolate(small, big, goal):
max_big = goal / 5
if big >= max_big:
if small >= (goal - max_big * 5):
return goal - max_big * 5
if big < max_big:
if small >= (goal - big * 5):
return goal - big * 5
return -1 |
efb0333d0fb8d80b1675a465c64b26e5bddaf22e | minu-gatech/Data-Analytics-Challenge | /Python Challenge/PyPoll/main.py | 3,039 | 3.71875 | 4 |
''' PYTHON Homework 3 - PyPoll '''
'''Importing modules'''
import os, csv
filename = os.path.join("PyPoll_Resources_election_data.csv")
''' Intializing Variables'''
total_votes_cast = 0
candidates_list = []
candidate = ''
total_votes = []
khan_count = 0
correy_count = 0
li_count = 0
tooley_count = 0
votes_count = {}
''' Opening and Reading a csv file '''
with open(filename,'r') as file:
reader = csv.reader(file,delimiter=',')
header = next(reader)
#print(header)
for row in reader:
# The total number of votes cast
if row[0] != '':
total_votes_cast = total_votes_cast + 1
# Complete list of candidates who received votes
candidate = row[2]
if(candidate not in candidates_list):
candidates_list.append(candidate)
# The total number of votes each candidate won
if row[2] == 'Khan':
khan_count = khan_count + 1
elif row[2] == 'Correy':
correy_count = correy_count + 1
elif row[2] == 'Li':
li_count = li_count + 1
elif row[2] == "O'Tooley":
tooley_count = tooley_count + 1
else:
print("\n\nNO CANDIDATES")
# The percentage of votes each candidate won
khan_won_percent = (khan_count / total_votes_cast) * 100
correy_won_percent = (correy_count / total_votes_cast) * 100
li_won_percent = (li_count / total_votes_cast) * 100
tooley_won_percent = (tooley_count / total_votes_cast) * 100
#The winner of the election based on popular vote.
if(khan_count > correy_count and khan_count > li_count and khan_count > tooley_count):
winner = 'Khan'
if(correy_count > khan_count and correy_count > li_count and correy_count > tooley_count):
winner = 'Correy'
if(li_count > khan_count and li_count > correy_count and li_count > tooley_count):
winner = 'Li'
if(tooley_count > correy_count and tooley_count > khan_count and tooley_count > li_count):
winner = "O'Tooley"
''' Printing output to teminal '''
output1 = "\n ELECTION RESULTS"
print(output1)
print("-"*30)
print(f" Total Votes : {total_votes_cast}")
print("-"*30)
print(f" {candidates_list[0]}: {khan_won_percent:.3g}.000% ({khan_count})")
print(f" {candidates_list[1]}: {correy_won_percent:.3g}.000% ({correy_count})")
print(f" {candidates_list[2]}: {li_won_percent:.3g}.000% ({li_count})")
print(f" {candidates_list[3]}: {tooley_won_percent:.3g}.000% ({tooley_count})")
print("-"*30)
print(f" Winner : {winner}")
print("-"*30)
''' Exporting the output to text file '''
file = open("PyPoll_Analysis_Output.txt",'w')
file.write(output1 + "\n")
file.writelines("-"*30)
file.write(f"\n Total Votes : {total_votes_cast}\n")
file.write("-"*30)
file.write(f"\n {candidates_list[0]}: {khan_won_percent:.3g}.000% ({khan_count})\n")
file.write(f" {candidates_list[1]}: {correy_won_percent:.3g}.000% ({correy_count})\n")
file.write(f" {candidates_list[2]}: {li_won_percent:.3g}.000% ({li_count})\n")
file.write(f" {candidates_list[3]}: {tooley_won_percent:.3g}.000% ({tooley_count})\n")
file.writelines("-"*30)
file.write(f"\n Winner : {winner}\n")
file.write("-"*30)
|
e215a6f4841a6c0ebb7b32d1d694acbb45b789d5 | ValiumK/first_repo | /foods.py | 819 | 4.4375 | 4 | # 27.08.2021 Упражнение с срезами(slices)
my_foods =['borsch', 'dumplings', 'pizza', 'bacon', 'pies']
friend_foods = my_foods[:]
# Добавляем разные элементы в оба списка
my_foods.append('pasta')
friend_foods.append(' ice cream')
# Вывод списка в цикле for
for my_food in my_foods:
print(f"My favorite foods are {my_food.title()}")
for friend_food in friend_foods:
print(f"My friend favorite foods are {friend_food.title()}")
print("My favorite foods are:")
print(my_foods)
print("\nMy friend favorite foods are:")
print(friend_foods)
print("The first three items in the list are:\n")
print(my_foods[:3])
print("The last three items in the list are:\n")
print(my_foods[2:])
print("The middle two items in the list are:\n")
print(my_foods[1:3:1])
|
a3e63dba11a3a252d85b16456aa04d5ee203b4bb | satyam-seth-learnings/python_learning | /Harshit Vashisth/Chapter 2(All About String)/C-More About Variable/15.Variable_More.py | 84 | 3.5625 | 4 | name,age="Satyam","24"
print("Hello "+name+" Your age is "+age)
x=y=z=1
print(x+y+z) |
eaabe5e8c71751dae32dab33d62ed12a98351e03 | willkara/PyumIpsum | /datastore/Cache.py | 1,031 | 3.625 | 4 | import pickledb
class Cache(object):
"""
The main Cache object. All different types of caches will extend this class.
"""
def __init__(self):
"""
Create an instance of a cache.
:return:
"""
self.cachedb = pickledb.load('pickle.db', False)
def get(self, key):
"""
Return the model(value) of a given key from the cache.
:param key: The key to get and return the value of.
:return: The value of the specified key.
"""
return self.cachedb.get(key)
def add(self, key, model):
"""
Add a model(value) to the cache with a specified key.
:param key: The key of the model(value) you wish to return. This is the subject/word of the model.
:param model: The model object of the specified key.
:return:
"""
return self.cachedb.set(key, model)
def get_total(self):
total = 0
for _ in self.cachedb.getall():
total += 1
return total
|
a2292640c2551af34ef14aa8774cc2ebd958bf39 | dang-trung/learn-algorithms | /algorithms_data_structures/algorithms/search_binary.py | 551 | 4.09375 | 4 | def search_binary(input_array, value):
left, right = 0, (len(input_array) - 1)
while True:
if left <= right:
mid = int((left + right)/2)
if input_array[mid] == value:
return mid
elif input_array[mid] < value:
left = mid + 1
elif input_array[mid] > value:
right = mid - 1
else:
return -1
if __name__ == '__main__':
input_array = [1, 2, 3, 4, 5, 6]
search_binary(input_array, 3)
search_binary(input_array, 7) |
1e75535cffbecf42de228a4c293469efb6be0672 | rodmur/hackerrank | /algorithms/implementation/gridsearch.py | 1,053 | 3.546875 | 4 | #!/usr/bin/python3
def check_it(G,P,r,c):
ok = True
p = 1
row = r + 1
while ok and p < len(P) and row < len(G):
column = G[row].find(P[p],c)
if column < 0 or c != column:
ok = False
break
p += 1
row += 1
if row == len(G) and p < len(P):
ok = False
return ok
t = int(input().strip())
for _ in range(t):
R,C = map(int, input().split())
G = []
for _ in range(R):
G.append(input().strip())
r,c = map(int, input().split())
P = []
for _ in range(r):
P.append(input().strip())
position = []
start = 0
found = False
p = P[0]
g = 0
while not found and g < R:
column = 0
while not found and column < C:
try:
ctmp = G[g].index(p,column)
found = check_it(G,P,g,ctmp)
column += 1
except ValueError:
break
g += 1
if found:
print("YES")
else:
print("NO")
|
e44815f8d1c0bc5b211deb8151bdf74acf1ca914 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2405/60647/319754.py | 627 | 3.78125 | 4 | a=int(input())
list=[]
for i in range(a):
temp=input().split()
list.append(temp)
if list==[['1', '2'], ['1', '3'], ['2', '5'], ['3', '4'], ['4', '6'], ['6', '5']]:
print(4)
print(2)
print(8,end='')
elif list==[['1', '2'], ['1', '3'], ['2', '4'], ['4', '3']]or list==[['1', '2'], ['1', '3'], ['2', '4'], ['2', '5'], ['4', '3']]:
print(3)
print(2)
print(5,end='')
elif list==[['1', '2'], ['2', '3'], ['2', '4'], ['4', '5'], ['3', '6'], ['3', '7'], ['6', '8'], ['7', '9'], ['7', '10'], ['6', '8']]:
print(5)
print(3)
print(1,end='')
else:
print(4)
print(4)
print(8,end='') |
74fbffe2119082d8ef0d62cda203048d23a2ea7f | pppppp040/nlp-base-method | /EnglishModel/preprocessingMed/method01/findStr.py | 144 | 4.125 | 4 | str1 = "hello,Crise!"
str2 = "ello"
str3 = ","
#find()返回的是该字符串的下标索引
print(str1.find(str2))
print(str1.find(str3)) |
e4188456846e7327537512132160c5d0b969ed67 | pmediaandy/bullpen | /codility/frogjmp.py | 338 | 3.71875 | 4 | #!/usr/bin/env python
def solution(X, Y, D):
dist = Y - X
if dist % D == 0:
return dist / D
return dist / D + 1
if __name__ == '__main__':
print solution(10, 10, 3) == 0
print solution(10, 20, 2) == 5
print solution(10, 19, 2) == 5
print solution(10, 21, 2) == 6
print solution(10, 85, 30) == 3
|
32be34153db901b8fb9f6d85a7786dcbe39ddea6 | harshithaRao5/dumpfile | /cspp1/m1/p3/p3/longest_substring.py | 294 | 3.890625 | 4 | "'#finding the longest substring'"
S = input()
i = S[0]
j = ''
"'#checking for the string present in range'"
for a in range(1, len(S)):
if S[a] >= i[len(i)-1]:
i += S[a]
else:
if len(i) > len(j):
j = i
i = S[a]
if len(i) > len(j):
j = i
print(j)
|
ec8902eb992a9187e7d90f8d3428cee0a9bfbb0d | WQ-GC/Python_AbsoluteBeginners | /CH7_ExceptionHandling.py | 3,997 | 3.953125 | 4 | #Python Exceptions
import sys
def ExitProgram():
print("sys.exit() - Exiting Program...")
sys.exit()
def MyFunc(inputVar):
return "Hello World"
def ExceptionInput():
try:
num = float("Hello World")
except ValueError:
print("cannot convert to float")
def ExceptionDivision():
num = 1000
print("ExceptionDivision")
for i in range(-3, 3, 1):
print("divide by:", i, end=" ")
try:
num = 1000 / i
print(num)
except ZeroDivisionError:
print("***Exception: Division by 0")
continue
def TestExceptions():
filename = "nosuchfile.txt"
try:
getFile = open(filename, "r")
except IOError:
print("Exception: IOError ", filename, " - Not found")
###########################################################
print()
myList = list()
for i in range(10):
myList.append(i)
#print(i, ":", myList[i])
try:
myList[100] = 123
except IndexError:
print("Exception: IndexError - myList has no index at 100")
###########################################################
print()
myDict = {"abc": 123,
"def": 456}
try:
getData = myDict["xyz"]
except KeyError:
print("Exception: KeyError - myDict has no key ", '"xyz"')
###########################################################
print()
#myResult = myValue / 3
try:
myResult = myValue / 3
except NameError:
print("Exception: NameError - myValue does not exist")
try:
MyNoSuchFunction()
except NameError:
print("Exception: NameError - MyNoSuchFunction() does not exist")
###########################################################
#print()
#
#try:
#
#except SyntaxError:
# print("Exception: Syntax error")
###########################################################
print()
#getFile = open(123, 123)
try:
getFile = open(123, 123)
except TypeError:
print("Exception: TypeError - open inputs type wrong")
###########################################################
print()
try:
getData = MyFunc(123)
print(int(getData))
except ValueError:
print("Exception: ValueError - MyFunc returns string, not integer")
###########################################################
print()
try:
getData = 1000 / 0
except ZeroDivisionError:
print("Exception: ZeroDivisionError - Divide by zero")
def ExceptionCode():
myVar = 1000 / 0 #ZeroDivisionError
getFile = open("NoSuchFile.txt", "r") #FileNotFoundError
getFile = open(123, "r") #OSError
getFile = int(MyFunc(123)) #ValueError
getFile = MyFunc() #TypeError
def MultipleExceptions():
myExceptionTuple = (ZeroDivisionError, OSError, FileNotFoundError, IOError, ValueError, TypeError)
try:
ExceptionCode()
except myExceptionTuple:
print("Check for exceptions... ")
for eachItem in myExceptionTuple:
print(" Exception: ", eachItem)
def ReceiveException():
myExceptionTuple = (ZeroDivisionError, OSError, FileNotFoundError, IOError, ValueError, TypeError)
try:
print("Try...")
ExceptionCode()
except myExceptionTuple as e:
print("...CAUGHT Exception as: ", end="")
print(e)
try:
ExceptionCode()
except myExceptionTuple:
print("Within myExceptionTuple")
ExitProgram()
#############################################
ExceptionDivision()
print()
print("=====================================")
TestExceptions()
print()
print("=====================================")
MultipleExceptions()
print()
print("=====================================")
ReceiveException()
|
c69b34e2222c41700fa3af4aa85bee6beffe3b86 | Putind/Aca | /exerclse03.py | 5,119 | 3.625 | 4 | # num = 1
# # 短路逻辑逻辑运算时 如果前面的条件能判断出最终结果
# # 后面的代码就不会执行
# # 尽量降复杂的判断放在后面
# # and 发现第一个结果为False 就有结论了
# # 后续条件不在判断
# result = num > 1 and input('请输入a') == 'a'
#
# # or发现第一个结果为Ture
# # 后续条件不在判断
# result1 = num == 1 or input('请输入a') == a
# a = 800
# b = 1000
# # id函数 获取变量存储对象的地址
# print(id(a))
# print(id(b))
# print(a is b)#is运算本质是通过id 函数进行判断的
# c = a
# print(id(c))
# print(c is a)
#
# d = 1000
# print(b is d)
# 三个物理行 三个逻辑行
# a = 1
# b = a+1
# c = a+2
# 一个物理行, 三个逻辑航
# 在一个逻辑行中使用多个逻辑行 使用;分隔
# a = 1; b = a+1; c = a+2; #不建议这样写
# 隐式换行 在括号内换行()[]{}
# \折行符 必须放在末尾作用是告诉解释器下一行也是本行的语句
# price = float(input('输入商品单价'))
# count = int(input('请输入商品数量'))
# money = float(input('请输入金额'))
# res = money - price * count
#
# if res>=0:
# # 金额不足 找零执行代码
# result = '应找回: ' +str(res)
# else:
# # 不大于0要执行的
# result = '金额不足 回家去拿钱再来'
# # 输出结果
# print(result)
# 选择语句在执行过程中只会选择一个符合的代码
# a = 10
# b = 10
# if a>b:# 如果不满足向下执行
# # 满足条件a>b 执行代码
# print('最大数是a')
# elif a == b:#如果不满足向下执行
# # 满足条件a == b 执行代码
# print('a和b相等')
# elif a<b:#如果不满足向下执行
# # 满足条件a<b 执行代码
# print('最大的数是b')
#else
# pass#占位
# 调试
# 让程序中断 卓行执行
# 目的 审查程序运行是的变量以及变量取值
# 审查程序运行的流程
# 步骤
# 1.加断点(调试过程中遇到断点加断点)
# 2. 运行调试shift+f9
# 3.程序会在断点出停止 按f8
# 4.ctrl+f2停止调试
#season = input('请输入一个季度')
# if season == '春':
# print('1月2月3月')
# if season == '夏':
# print('4月5月6月')
# if season == '秋':
# print('7月8月9月')
# if season == '冬':
# print('10月11月12月')
#
# if season == '春':
# print('1月2月3月')
# elif season == '夏':
# print('4月5月6月')
# elif season == '秋':
# print('7月8月9月')
# elif season == '冬':
# print('10月11月12月')
op = input('是否有卖西瓜的')
if op == '有':
count = 1
print('老王买了' + str(count) + '西瓜')
else:
count = 4
print('老王买了'+str(count)+'包子')
#
# suzi = input('请输入一个数字')
# op = input('请输入一个运算符')
# suzi1 = input('请在输入一个数字')
# if op == '+':
# print(suzi+suzi1)
# elif op == '-':
# print(suzi-suzi1)
# elif op == '*':
# print(suzi*suzi1)
# elif op == '/':
# print(suzi+suzi1)
# else:
# print('运算符有误')
# num = input('请输入第一个数字:')
# num1 = input('请输入第二个数字:')
# if num > num1:
# print(num1)
# elif num == num1:
# print(num)
# else:
# print(nun1)
# num = input('请输入第一个数字:')
# num1 = input('请输入第二个数字:')
# num2 = input('请输入第三个数字:')
# if num > num1:
# print(num)
# if num > num2:
# print(num)
# else:
# print(num2)
# else:
# if num1 > num:
# print(num1)
# if num1 > num2:
# print(num1)
# else:
# print(num2)
#
# num1 = input('请输入第一个数字:')
# num2 = input('请输入第二个数字:')
# num3 = input('请输入第三个数字:')
# num4 = input('请输入第四个数字:')
# # 假设第一个数是最大值
# # 将最大值与第二个数比较 如果第二个数比最大值大
# max_value = num1
# if num2 > num1:
# max_value = num2
# if num3 > num2:
# max_value = num3
# if num4 > num3:
# max_value = num4
# print(max_value)
# 下面程序需要修改
# month = str(input('输入一个月份:'))
# if month == "1,3,5,7,8,10,12":
# print("31天")
# elif month == '6,9,11':
# print('30天')
# elif month == 2:
# print('28天')
# else:
# print('输入错误')
# if 100:
#
# print('真值为True')
# if '':
# print('yes')
# else:
# print('no')
# num = input('输入一个整数')
# if num % 2 == 0:
# state = '偶数'
# else:
# state = '奇数'
#
# if num % 2:
# state = '奇数'
# else:
# state = '偶数'
#
# state = '奇数'if num % 2 else '偶数'
# print(state)
# year = int(input('输入一个年份:'))
# if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
# day = 28
# else:
# day = 29
# print(day)
# day = 29 if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: else 28
while True:
dol = int(input('请输入美元'))
print(dol*6.9)
if input('输入exit退出') == 'exit':
break
|
73e88217bb68c7a999374f0258ce545aadd44201 | aga-wojteczko/PythonGGIT | /lab4zad1listy.py | 188 | 3.765625 | 4 | nazwiska = ["kowalski", "nowak", "iksinski", "dudek"]
szukane = input("podaj szukane nazwisko: ")
if szukane in nazwiska:
print("jest na liscie")
else:
print("nie znaleziono") |
38316ecb31378dbb1a967908fba27b7f1d7de2ac | yyyhhhrrr/pythonoldboy | /day4/decorator2.py | 722 | 3.84375 | 4 | #!/usr/bin/env python
# coding:utf-8
# Author:Yang
# 第一个特性:函数即“变量”
# def foo():
# print('in the foo')
# bar()
#
# foo()
# def bar():
# print('in the bar')
#
# def foo():
# print('in the foo')
# bar()
#
# foo()
# 匿名函数
# calc = lambda x:x*3
# print(calc(3))
# 第二个特性:高阶函数
import time
def bar():
time.sleep(3)
print("y")
def test(func): # 高阶函数 调用的形参是一个函数名
start_time=time.time()
func()
stop_time=time.time()
print(func) # 打印的函数内存地址
print("run %s"%(stop_time-start_time))
test(bar)
def test2(func):
print(func)
return func
# print(test2(bar))
bar=test2(bar)
bar |
a2170ba964c793d2d3b5d119ebf4d2fcb54ad49e | hicode/pythonFinance | /NewsFeedReader/parse2.py | 1,163 | 3.71875 | 4 | import feedparser
# Function to fetch the rss feed and return the parsed RSS
def parse_RSS(rss_url):
return feedparser.parse(rss_url)
# Function grabs the rss feed headlines (titles) and returns them as a list
def get_headlines(rss_url):
headlines = []
feed = parse_RSS(rss_url)
for newsitem in feed['items']:
headlines.append(newsitem['title'])
return headlines
# A list to hold all headlines
allheadlines = []
# List of RSS feeds that we will fetch and combine
newsurls = {
#'apnews': 'http://hosted2.ap.org/atom/APDEFAULT/3d281c11a96b4ad082fe88aa0db04305',
#'googlenews': 'https://news.google.com/news/rss/?hl=en&ned=us&gl=US',
#'yahoonews': 'http://news.yahoo.com/rss/'
#'yahooFinance': 'http://finance.yahoo.com/rss/headline?s=msft'
'boerse-online': 'http://www.boerse-online.de/rss'
}
# Iterate over the feed urls
for key, url in newsurls.items():
# Call get_headlines() and combine the returned headlines with allheadlines
allheadlines.extend(get_headlines(url))
# Iterate over the allheadlines list and print each headline
for hl in allheadlines:
print(hl)
# end of code |
8cc569ce39c39e22eb3964a3aad1bac8e2001aa3 | C-CCM-TC1028-102-2113/tarea-4-A01026608 | /assignments/25TrianguloAsteriscos/src/exercise.py | 331 | 3.890625 | 4 |
def main():
#Escribe tu código debajo de esta línea
def trian(h):
j=1
for i in range (h,0,-1):
espacios= " "*i
asteriscos= '*' *j
j= j+1
print(espacios, asteriscos)
h= int(input('Dame un número:'))
trian(h)
if __name__=='__main__':
main()
|
37b98d69351965078ffc00f1d8512057b0808ff6 | beaulucas/ucsd_algo | /algorithmic_warmup/fib_mod.py | 917 | 3.6875 | 4 | # Uses python3
import sys
def get_fib_mod(n, m):
if n <= 1:
return n
# first thing to do is find the pisano sequence length for m
# need to get f_n % m (remainder) until we encounter a sequence of 0 1, then stop
# create empty list with base-case, every sequence starts with 0 1
lst_mod = [0, 1]
# if base case or ending in 0, 1 keep going
while lst_mod == [0, 1] or lst_mod[-2:] != [0,1]:
# grab f_n mod n until pattern emerges
fib_mod = (lst_mod[-1] + lst_mod[-2]) % m
print("remainder of", lst_mod[-1], "and", lst_mod[-2])
print(fib_mod)
lst_mod.append(fib_mod)
print("new list is ", lst_mod)
sequence = lst_mod[:-2]
pisano_length = len(sequence)
rmndr = n % pisano_length
return sequence[rmndr]
if __name__ == '__main__':
input = sys.stdin.read();
n, m = map(int, input.split())
print(get_fib_mod(n, m))
|
a806a3a68e91ddcdbd29bf4a167f1d3421f548e0 | mthompson36/newstuff | /Exercise6.py | 265 | 4.4375 | 4 | #This will ask for a string, then will tell you if it's a palindrome or not.
inputstring = input("Please enter a word: ")
if inputstring[::-1] == inputstring[0:]:
print(str(inputstring) + " is a palindrome")
else:
print(str(inputstring) + " is not a palindrome") |
8c13cf28bbf86783819ca931b96e930c7d341f58 | luckmimi/leetcode | /LC889.py | 782 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not preorder:
return
val = preorder[0]
if len(preorder) == 1:
return TreeNode(val)
root = TreeNode(val)
leftrootval = preorder[1]
index = postorder.index(leftrootval)
leftsize = index + 1
root.left = self.constructFromPrePost(preorder[1:leftsize+1],postorder[:index+1])
root.right = self.constructFromPrePost(preorder[leftsize+1:],postorder[index+1:-1])
return root
|
6fc152c38dda6da00f16c73a2e65008299fb2f34 | vesche/breakout-curses | /board.py | 707 | 3.640625 | 4 | # -*- coding: utf-8 -*-
from random import randint
from breakout import B_ROWS, B_COLS
COLORS = ['white', 'grey', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan']
def checker(color_a, color_b):
board = []
code_a = COLORS.index(color_a)
code_b = COLORS.index(color_b)
for i in range(B_ROWS):
if i % 2:
board += [code_a, code_b]*(B_COLS//2)
else:
board += [code_a, code_b][::-1]*(B_COLS//2)
return board
def standard():
board = []
for i in range(2, B_ROWS+2):
board += [i]*B_COLS
return board
def random():
board = []
for i in range(B_ROWS):
board += [randint(0, 7) for _ in range(10)]
return board |
a3c1b19f562f4d47872fa48a0dc17387cfa5974a | erpost/python-beginnings | /functions/math_function_basic.py | 156 | 3.96875 | 4 | n1 = input("Input a number: ")
n2 = input("Input a second number: ")
def addition(num1, num2):
return num1 + num2
print(addition(int(n1), int(n2)))
|
031a3e0649689319bea7018b347307ecac269fb9 | yzgyyang/coala-utils | /coala_utils/FileUtils.py | 1,947 | 4.1875 | 4 | import codecs
import tempfile
import os
def create_tempfile(suffix="", prefix="tmp", dir=None):
"""
Creates a temporary file with a closed stream
The user is expected to clean up after use.
:return: filepath of a temporary file.
"""
temporary = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)
os.close(temporary[0])
return temporary[1]
def detect_encoding(filename, default='utf-8'):
"""
Detects the file encoding by reading out the BOM.
Given a file with a BOM signature:
>>> import os, tempfile
>>> text = 'ä'
>>> encoded = codecs.encode(text, 'utf-16-le')
>>> fhandle, filename = tempfile.mkstemp()
>>> os.write(fhandle, codecs.BOM_UTF16_LE + encoded)
4
>>> os.close(fhandle)
This will detect the encoding from the first bytes in the file:
>>> detect_encoding(filename)
'utf-16'
You can now open the file easily with the right encoding:
>>> with open(filename, encoding=detect_encoding(filename)) as f:
... print(f.read())
ä
If you have a normal file without BOM, it returns the default (which you
can give as an argument and is UTF 8 by default) so you can read them
just as easy:
>>> detect_encoding(__file__)
'utf-8'
This code is mainly taken from
http://stackoverflow.com/a/24370596/3212182.
:param filename: The file to detect the encoding of.
:param default: The default encoding to use if no BOM is present.
:return: A string representing the encoding.
"""
with open(filename, 'rb') as f:
raw = f.read(4) # will read less if the file is smaller
for enc, boms in [
('utf-8-sig', (codecs.BOM_UTF8,)),
('utf-16', (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)),
('utf-32', (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE))
]:
if any(raw.startswith(bom) for bom in boms):
return enc
return default
|
6b9286ba9e95d50af62cddf6d7daf205eb277b44 | barleen-kaur/LeetCode-Challenges | /DS_Algo/Trees/findDuplicateSubtrees.py | 1,346 | 3.953125 | 4 | '''
Q. Find Duplicate Subtrees
Given the root of a binary tree, return all duplicate subtrees.
For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]:
if root == None:
return []
global dict_
dict_ = {}
def returnDuplicates(root, ans):
global dict_
if root == None:
return "None"
else:
entry = str(root.val)+ "," + str(returnDuplicates(root.left, ans)) + "," + str(returnDuplicates(root.right, ans))
if entry not in dict_:
dict_[entry] = 1
else:
dict_[entry] += 1
if dict_[entry] == 2:
ans.append(root)
return entry
ans = []
returnDuplicates(root,ans)
return ans |
f585f0dd8411c2ec611ccca6c5d3c54ca2b9366e | SenthilKumar009/100DaysOfCode-DataScience | /Python/Programs/splitList.py | 197 | 4.03125 | 4 | sent = 'Print only the words that start with with s from the given sentance'
listStr = sent.split(' ')
print(listStr)
for val in listStr:
if val[0] == 's' or val[0] == 'S':
print(val) |
23602847dfcf94f96c5d890909138e524432b17d | ThanasisGio/PythonProjects | /oop/Bookstore/backend.py | 1,878 | 4.0625 | 4 | import sqlite3
class Database:
def __init__(self,db):
self.conn=sqlite3.connect(db)
self.cur=self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY,title text,author text,year integer,isbn integer) ")
self.conn.commit()
#have to call function so it can execute,if i run frontend connect() fun will run too
# pass for items in insert function
def insert(self,title,author,year,isbn):
#then i need to connect to database
self.cur.execute("INSERT INTO book VALUES (NULL,?,?,?,?)",(title,author,year,isbn))
self.conn.commit()
def view(self):
#then i need to connect to database
self.cur.execute("SELECT * FROM book")
rows=self.cur.fetchall()
#self.conn.commit()
#self.conn.close()
#data stored in row variable so i return that
return rows
# pass empty values just in case user only passes on variable
def search(self,title="",author="",year="",isbn=""):
self.cur.execute("SELECT * FROM book WHERE title=? OR author=? OR year=? OR isbn=?",(title,author,year,isbn))
rows=self.cur.fetchall()
#self.conn.commit()
#self.conn.close()
return rows
def delete(self,id):
self.cur.execute("DELETE FROM book WHERE id=?",(id,) )
self.conn.commit()
def update(self,id,title,author,year,isbn):
self.cur.execute("UPDATE book SET title=?,author=?,year=?,isbn=? WHERE id=?",(title,author,year,isbn,id) )
self.conn.commit()
self.conn.close()
def __del__(self):
self.conn.close()
#connect()
#insert("The Big","John woo",1914,888899)
#delete(4)
#update(4,"The moon","John Smooth",1917,999999)
#print(view())
#print(search(author="John Smith")) |
4179f730d62025e7eadfa64471f901a87851830c | SashaTlr/algos | /Chpt3_StacksQeueus/A_ThreeInOne_01.py | 1,898 | 3.5625 | 4 |
class Multistack:
def __init__(self, stackOne, stackTwo, stackThree):
self.topStack = [stackOne, stackTwo, stackThree]
self.array = [None] * (stackOne.capacity + stackTwo.capacity + stackThree.capacity)
class StackInfo:
def __init__(topIndex, capacity = 10):
self.top = topIndex
self.size = 0
self.capacity = capacity
return self
def isFull(self):
return self.size >= self.capacity
def isEmpty(self):
return self.size == 0
def _getIndex(self):
if (self.size + self.top - 1) > len(self.array):
return (self.size + self.top) % len(self.array)
return self.size + self.top
def push(self, value, stackNum):
if __allStacksAreFull():
raise Exception ("All stacks are full")
stack = self.topStack[stackNum]
if stack.isFull():
__expandStack(stackNum)
index = stack._getIndex()
self.array[index] = value
stack.size += 1
return self
def pop(self, stackNum):
stack = self.topStack[stackNum]
if stack.isEmpty():
return None
popped_value = self.array[stack._getIndex()]
self.array[stack._getIndex()] = None
stack.size -= 1
def peek(self, stackNum):
stack = self.topStack[stackNum]
if stack.isEmpty():
return None
popped_value = self.array[_getIndex(stack)]
stack.size -= 1
def __allStacksAreFull():
#are all stacks full
def __expandStack(stackNum):
#needs to expand stack
#if no room, has to shift other stacks, expand capacity
#Need to use space efficiently
#have an array that tracks beginning of each stack
#have a method that checks if next space is available. if not, call shift method
#shift method must check for availability of next space before shifting
#shift method - if you reach the end, can wrap around if beginning is empty
#topstack contains size of stack, first position
#if size + first position index is greater than length of array, there is an overflow
|
368900644e8b281dde8fdf61f3eab1adf85ade06 | emptybename/Ds-Algo | /tree/problems/height_balance.py | 1,326 | 3.578125 | 4 | class TNode:
def __init__(self, value=None):
self.left = None
self.right = None
self.val = value
class Implementation:
def __init__(self):
pass
@staticmethod
def add_left(node: TNode, value: int):
node.left = TNode(value)
@staticmethod
def add_right(node: TNode, value: int):
node.right = TNode(value)
def build(self):
root = TNode(10)
self.add_left(root, 2)
self.add_right(root, 3)
self.add_left(root.left, 4)
self.add_right(root.left, 5)
self.add_left(root.right, 20)
self.add_right(root.right, 8)
self.add_left(root.left.left, 11)
# self.add_left(root.left.left.left, 50)
self.add_left(root.left.right, 40)
return root
def balanced(self, root: TNode):
if root is None:
return True, 0
lst = self.balanced(root.left)
rst = self.balanced(root.right)
if lst[0] and rst[0] and abs(lst[1] - rst[1]) <= 1:
return True, (1 + max(lst[1], rst[1]))
else:
return False, 0
def isBalanced(self, root: TNode):
if self.balanced(root)[0]:
return True
else:
return False
tree = Implementation()
root = tree.build()
print(tree.isBalanced(root))
|
7ca211aa0b6c43e5adbb37c7218bc4073ed71d36 | dfarfel/QA_Learning_1 | /List/List_task_5.4.py | 197 | 3.796875 | 4 | list1 = input("Enter your first list with comma: ")
list1 = list(list1.split(','))
list2 = input("Enter your second list with comma: ")
list2 = list(list2.split(','))
list3=list1+list2
print(list3) |
4fd24a53161b543bb0c2f166fe655275a71a02e5 | AZhengW/wanderer_work | /2020-4-25 work/work3/Role/TongLao.py | 529 | 3.5 | 4 | # 天山童姥类:
# 初始hp10000,攻击力800,当血量<5000时,攻击力翻三倍,血量扣除一半,只生效一次
import random
class Tonglao():
def __init__(self, hp, power):
self.name = "童姥"
self.hp = hp
self.power = power
def bao_nu(self):
self.hp = self.hp / 2
self.power = self.power * 3
print("童姥说:小鬼,你惹怒我了!!,自身血量减半,武力值*3")
def baoji(self):
random1 = random.choice("aaaabbbbb")
return random1
|
0a7ac1d9d4ce922c18ea5fdaaaa80f108ffcb8c9 | mzb2599/python | /polymorphism/p2.py | 195 | 3.921875 | 4 | def add(x, y, z=0, v=1):
return x + y + z+v
def add(x, y, z=5, v=10): #Function overwrites the previous function add
return x + y + z+v
print(add(2, 3))
print(add(2, 3, 5))
|
bd192f5e93874233122fa1da732b58a441723d95 | dsujant/Python | /kevin_bacon_number.py | 1,246 | 3.90625 | 4 | import psycopg2
# Parameters for accessing movies db
params = {
'dbname': 'movies',
'user': 'dsujanto'
}
### Set up connection
conn = psycopg2.connect(**params) # Create a connection object
cur = conn.cursor() # Create cursor object
print("Let's find Kevin Beacon!")
guess = input("Enter an actor name: ")
print(guess)
sql = """SELECT m.title, a.name, b.name from movies m, actors a, movies_actors ma,actors b, movies_actors ma2
where m.movie_id = ma.movie_id and a.actor_id = ma.actor_id and b.actor_id = ma2.actor_id and m.movie_id =
ma2.movie_id and b.name like '%s'""" % guess
cur.execute(sql)
#record = cur.fetchall()
print("Executing SQL...")
### Gather results
movie_list = [] # Initialize a list with one count per movie title in db
found = False
first = True
for rec in cur: # Loop through records in cursor object
print (rec[0],rec[1])
if rec[1]=='Kevin Bacon':
if first:
print ("Kevin Bacon found return 1")
else:
print("Kevin Bacon found return 2")
found = True
break
first = False
if not found:
print ("Not found Kevin Bacon")
#movie_list.append(rec[0]) # and append them to movie list.
cur.close()
|
fc38c200b9343a6cb4c9b6445a846ce4c453e550 | Sruthi123-dg/LuminarDjangoPython | /Luminarproject/flowcontrols/decisionmakingstmnts/largestamongtwo.py | 189 | 4.1875 | 4 | num1=int(input("enter the number1"))
num2=int(input("enter the number2"))
if(num1>num2):
print(num1,"is largest")
elif(num1==num2):
print("equal")
else:
print(num2,"is largest") |
fe5041d904ce18f544f76496daf2485f604e44b0 | youandvern/Excel-Proj-Name-Matching | /projectNameReorder - refactor.py | 6,525 | 3.734375 | 4 | """
Created on Tue Oct 13, 2020
@author: Andrew-V.Young
Match project desctiption to project number
"""
import sys
import pandas as pd
from openpyxl import load_workbook
# character matching count function
# https://www.geeksforgeeks.org/python-count-the-number-of-matching-characters-in-a-pair-of-string/
def count(str1, str2):
c, j = 0, 0
# loop executes till length of str1 and
# stores value of str1 character by character
# and stores in i at each iteration.
for i in str1:
# this will check if character extracted from
# str1 is present in str2 or not(str2.find(i)
# return -1 if not found otherwise return the
# starting occurrence index of that character
# in str2) and j == str1.find(i) is used to
# avoid the counting of the duplicate characters
# present in str1 found in str2
if str2.find(i)>= 0 and j == str1.find(i):
c += 1
j += 1
return c
# function to loop through pandas dataframe and find closest match between name provided and df description
def loop_rows(df, fullname, rmvword = ""): # df=dataframe fullname = string of project name to match
charcount = [] # initialize empty list to store # of matching characters
# dataframe has columns: ProjNumber ProjName ProjType ProjCity ProjState
# loop through rows in dataframe
for index2, row2 in df.iterrows():
# build df full name by combining name and city (remove first 6chars of name)
namematch = str(row2[1])[6:] + " " + str(row2[3])
# string project name to compare with df names (option to remove input substring)
nummatch = count(fullname.replace(rmvword,""), namematch)
charcount.append(nummatch)
# locate position of closest match (last (most recent) instance if multiple)
maxindex = len(charcount) - 1 - charcount[::-1].index(max(charcount))
# compile output list (projNumber, dfName, inputName)
list_append = [df.iloc[maxindex, 0], df.iloc[maxindex,1], fullname]
return list_append
def reformat_number_table(inFileName = 'Book1.xlsx'):
# function to reformat spreadsheet - matches sheet of job names to sheet of job numbers and descriptions
# create dataframe for job number/description and job name sheets
jobsTable = pd.read_excel(inFileName, sheet_name = 'Jobs', index_col = None, header = None).fillna(" ")
nameTable = pd.read_excel(inFileName, sheet_name = 'Jname', index_col = None, header = None).fillna(" ")
# initialize list of job numbers to export back to excel as final result
numlist = []
# extract separate dataframes for uniquely named locations
guamJobs = jobsTable[jobsTable[4].str.contains("GUAM")]
qatarJobs = jobsTable[jobsTable[4].str.contains("QATAR")]
hiJobs = jobsTable[jobsTable[4].str.contains("HI")]
saipanJobs = jobsTable[jobsTable[4].str.contains("SAIPAN")]
# loop through each name from name df
for index, row in nameTable.iterrows():
# extract and format string name from df row
fullname = row[0]
names = row[0].split()
name = names[0].strip(",()")
# create new dataframe for job number/descriptions where the first word in the name is contained in a city name
freshCol = jobsTable[3].str.contains(name).fillna(False)
includedRows = jobsTable[freshCol]
# count number of rows found
numRows = len(includedRows.index)
# initialize default job number result as Not Found
list_append = ["Not Found","Not Found","Not Found"]
if numRows == 1: # only one tank in the city searched for
# append list (projName, projDescription, projName)
list_append = [includedRows.iloc[0,0], includedRows.iloc[0,1], fullname]
elif numRows == 0: # no city found in first word search --> unique location search
if "Guam" in fullname or "GU" in fullname:
list_append = loop_rows(guamJobs, fullname, rmvword="Guam")
elif "Qatar" in fullname:
list_append = loop_rows(qatarJobs, fullname)
elif "Hawaii" in fullname or "HI" in fullname:
# list_append = loop_rows(hiJobs, fullname)
list_append = list_append
elif "Saipan" in fullname:
list_append = loop_rows(saipanJobs, fullname)
elif numRows>1 and len(names) > 1: # multiple results returned for a name with multple words
# repeat search using first two words of input name
testname = names[0].strip(",()") + " " + names[1].strip(",()")
testfresh = jobsTable[3].str.contains(testname).fillna(False)
testincluded = jobsTable[testfresh]
testnumRow = len(testincluded.index)
# if no results found from new search, find closest match from old search
if testnumRow == 0:
list_append = loop_rows(includedRows, fullname)
# if new search returns more than one result, find closest match from new search
elif testnumRow > 1:
# print(fullname + " --->>> " + testincluded)
list_append = loop_rows(testincluded, fullname)
# if new search returns single tank, use this project number
elif testnumRow == 1:
list_append = [includedRows.iloc[0,0], includedRows.iloc[0,1], fullname]
# append result to list
numlist.append(list_append)
# if list_append == ["Not Found","Not Found","Not Found"]:
# print(fullname)
# create dataframe from compiled results and print to excel
numdf = pd.DataFrame(numlist, columns = ['Job Number', 'Job Name', 'Job Name 2'])
book = load_workbook(inFileName) # new data entry without deleting existing
# add sorted data to new sheet
with pd.ExcelWriter(inFileName, engine = 'openpyxl') as writer:
writer.book = book
numdf.to_excel(writer, sheet_name = 'JNo')
writer.save()
writer.close()
return 'reformatting complete'
# run function
run_funct = reformat_number_table('jobnames.xlsx')
print(run_funct)
|
7f40dfbac1224a4e52599c3aabd14813d2c2a093 | mohsindalvi87/bearsnacks | /computer-vision/anaglyphs/test.py | 2,847 | 3.515625 | 4 | #!/usr/bin/env python3
# https://en.wikipedia.org/wiki/Anaglyph_3D
# https://github.com/miguelgrinberg/anaglyph.py/blob/master/anaglyph.py
import numpy as np
import cv2
# declare various color blending algorithms to mix te pixels
# from different perspectives so that red/blue lens glasses
# make the image look 3D
mixMatrices = {
'true': [ [ 0.299, 0.587, 0.114, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0.299, 0.587, 0.114 ] ],
'mono': [ [ 0.299, 0.587, 0.114, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0.299, 0.587, 0.114, 0.299, 0.587, 0.114 ] ],
'color': [ [ 1, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 1, 0, 0, 0, 1 ] ],
'halfcolor': [ [ 0.299, 0.587, 0.114, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 1, 0, 0, 0, 1 ] ],
'optimized': [ [ 0, 0.7, 0.3, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 1, 0, 0, 0, 1 ] ],
}
# blends two RGB image pairs into a single image that will be perceived as
# 3d when using red/blue glasses
# inputs:
# leftImage -- an image that corresponds to the left eye
# rightImage -- an image that corresponds to the right eye
# color -- a string that specifies a blending strategy by indexing into mixMatrices
# returns:
# anaglyph image
def anaglyphBGR(leftImage, rightImage, color):
# use the color argument to select a color separation formula from mixMatrices
if color in mixMatrices:
m = mixMatrices[color]
else:
print('invalid color mixMatrix: {}'.format(color))
return None
h,w = leftImage.shape[:2]
result = np.zeros((h,w,3), np.uint8)
# split the left and right images into separate blue, green and red images
lb,lg,lr = cv2.split(np.asarray(leftImage[:,:]))
rb,rg,rr = cv2.split(np.asarray(rightImage[:,:]))
resultArray = np.asarray(result[:,:])
resultArray[:,:,0] = lb*m[0][6] + lg*m[0][7] + lr*m[0][8] + rb*m[1][6] + rg*m[1][7] + rr*m[1][8]
resultArray[:,:,1] = lb*m[0][3] + lg*m[0][4] + lr*m[0][5] + rb*m[1][3] + rg*m[1][4] + rr*m[1][5]
resultArray[:,:,2] = lb*m[0][0] + lg*m[0][1] + lr*m[0][2] + rb*m[1][0] + rg*m[1][1] + rr*m[1][2]
return result
def main():
# read in the image and split out the left/right
img = cv2.imread('../imgs3/image-0.png')
if len(img.shape) > 2:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
h,w = img.shape[:2]
leftImage = img[:,:w//2]
rightImage = img[:,w//2:]
# make an anaglyph
anaglyphImage = anaglyphBGR(leftImage, rightImage, color='color')
if anaglyphImage is not None:
# display the anaglyph image
cv2.imshow("anaglyph",anaglyphImage)
print("Press:\n [s] to save\n [anykey] to exit")
char = cv2.waitKey()
if char == ord('s'):
# cv2.imwrite('anaglyph_sample.png', np.asarray(anaglyphImage[:,:]))
cv2.imwrite('anaglyph_sample.png', anaglyphImage)
if __name__=="__main__":
main()
|
755cf4ddb6a0afc054a3315426d379be36ec6e00 | kamalkkv/guvigithub | /1_2_5.py | 105 | 3.609375 | 4 | n=int(input())
q=int(input())
for i in range(n+1,q):
if(i%2==0):
print(i,end=" ")
|
6accd9183555385c76312f72135e1e8df9b91efc | PhoebeGarden/python-record | /廖雪峰 notes/recursive function.py | 800 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
def fact(n):
if n == 1:
return 1
return n * fact(n-1)
print(fact(1))
print(fact(5))
print(fact(100))
#为了防止递归栈溢出,需要通过尾递归优化
#尾递归是指,在函数返回的时候只调用自身本身,上面的函数不是,因为返回的是乘积
def fact(n):
return fact_iter(n,1)
def fact_iter(num, product):
if num == 1:
return product
return fact_iter(num-1, num*product)
#fact(1000) 大部分语言都没有针对为递归优化,因此还是不行。。。。所以这一点真是醉了
#exercise 汉诺塔
def move(n, a, b, c):
if n == 1:
print(a,'-->', c)
return
else:
move(n-1, a, c, b)
print(a, '-->', c)
move(n-1, b, a, c)
move(3, 'A', 'B', 'C') |
7345621eac423eef1b9962241828e9581ff0ea13 | mathildebrosseau/INF1007 | /TP2/exercice3.py | 736 | 3.875 | 4 | import math
constanteGravitationnelle = 9.81
def exercice3(hauteurInitiale, coefficientDeRebond):
#TODO: faites vos calculs et mettez le resultat dans la variable 'nombreDeRebonds'
V = math.sqrt(2 * constanteGravitationnelle * hauteurInitiale)
nombreDeRebonds = 0
while hauteurInitiale >= 0.01:
hauteurInitiale = V**2 / (2 * constanteGravitationnelle)
V *= coefficientDeRebond
nombreDeRebonds += 1
return nombreDeRebonds
if __name__ == '__main__':
hauteurInitiale = float(input("Quelle est la hauteur initiale: "))
coefficientDeRebond = float(input("Quel est le coefficient de rebond(entre 0 et 1 exclus [0:1[ ): "))
print(exercice3(hauteurInitiale, coefficientDeRebond))
|
f6a77df2c84b614f37b6b529e79760cd62b0b222 | ansarisaeem00/Mtech | /aac/expt4/bh5.py | 2,942 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 3 00:07:27 2019
@author: saeem
"""
class BinHeap:
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def percUp(self,i):
while i // 2 > 0:
if self.heapList[i] < self.heapList[i // 2]:
tmp = self.heapList[i // 2]
self.heapList[i // 2] = self.heapList[i]
self.heapList[i] = tmp
i = i // 2
def printHeap(self):
print("Heap is : " + str(self.heapList[1:]))
print("Degree is : " + str(self.currentSize))
def insert(self,k):
self.heapList.append(k)
self.currentSize = self.currentSize + 1
self.percUp(self.currentSize)
def percDown(self,i):
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
if self.heapList[i] > self.heapList[mc]:
tmp = self.heapList[i]
self.heapList[i] = self.heapList[mc]
self.heapList[mc] = tmp
i = mc
def minChild(self,i):
if i * 2 + 1 > self.currentSize:
return i * 2
else:
if self.heapList[i*2] < self.heapList[i*2+1]:
return i * 2
else:
return i * 2 + 1
def delMin(self):
retval = self.heapList[1]
self.heapList[1] = self.heapList[self.currentSize]
self.currentSize = self.currentSize - 1
self.heapList.pop()
self.percDown(1)
return retval
def delMax(self):
mx = self.heapList.index(max(self.heapList))
self.heapList.pop(mx)
self.currentSize = self.currentSize - 1
def buildHeap(self,alist):
i = len(alist) // 2
self.currentSize = len(alist)
self.heapList = [0] + alist[:]
while (i > 0):
self.percDown(i)
i = i - 1
bh = BinHeap()
while(True):
print("\n")
print("1.Build Heap")
print("2.Insert node in Heap")
print("3.Print Heap")
print("4.Delete minimum")
print("5.Delete maximum")
print("6.Quit")
print("\n")
choice = input("Enter your choice")
if(choice == "6"):
break
elif(choice == "2"):
data = int(input ("enter node to be insert"))
bh.insert(data)
elif(choice == "1"):
data =input ("enter nodes to build heap").split(",")
arr = [int(num) for num in data]
bh.buildHeap(arr)
elif(choice == "3"):
bh.printHeap()
elif(choice == "4"):
bh.delMin()
elif(choice == "5"):
bh.delMax()
else:
print("Invalid choice, Please select a valid input choice")
#bh.buildHeap([17, 9, 5, 2, 3,6,33])
#bh.printHeap()
#bh.insert(33)
#bh.printHeap()
#bh.insert(17)
#bh.printHeap()
#bh.insert(4)
#bh.printHeap()
#print(bh.minChild())
#print(bh.delMin())
#print(bh.delMin())
#print(bh.delMin())
#print(bh.delMin())
|
5038a386261870e4de436906781db9a5253eb9db | sanjsriv98/coding | /rai.py | 142 | 3.71875 | 4 | def isPalindrome(a):
if(len(a)==1):
return 1
elif len(a)==2:
return a[0]==a[1]
if a[0]==a[-1]:
return isPalindrome(a[1:-1])
|
bf048640dfe130b1eb6b844b68a6810909e14f2c | rifertv/-2-3 | /main.py | 413 | 4.15625 | 4 | def easy_unpack(elements: list) -> list:
"""
returns a tuple with 3 elements - first, third and second to the last
"""
i = [0, 2, -2]
elements = [elements[x] for x in i]
return elements
if __name__ == '__main__':
assert easy_unpack([1, 2, 3, 4, 5, 6, 7, 9]) == [1, 3, 7]
assert easy_unpack([1, 1, 1, 1]) == [1, 1, 1]
assert easy_unpack([6, 3, 7]) == [6, 7, 3]
print('Done! Go Check!') |
0674fd2e8bd686abf9b8e0be9b54388d720dcdba | ddp-danilo/ddp-pythonlearning1 | /sm7ex1.py | 251 | 4.1875 | 4 | #desenho que usa '#' para fazer quadrados
largura = int(input("digite a Largura: "))
altura = int(input("digite a altura: "))
while altura > 0:
ll = largura
while ll > 0:
print("#", end='')
ll -= 1
print()
altura -= 1
|
6ebe90e0d556e61ee99d5bfe61730974a54f8f9a | am1089/Python-Exercises | /ListOrganizer.py | 582 | 4.34375 | 4 | # Code to sort multiple lists
# input fields seperated by commas
allip = []
iplist = []
print("Input some names, ages, heights")
# Collect all inputs until an empty line is found.
while True:
ip = input()
if ip == "":
break
# Split into strings and then into integers
iplist = ip.split(',')
allip.append([iplist[0], int(iplist[1]), int(iplist[2])])
# lambda is creating a tuple which is given as a key then sorted.
# To sort it in descending order make the x's negative Ex: x[1] -> -x[1]
allip.sort(key=lambda x: (x[0], x[1], x[2]))
print(allip)
|
a1d35894e5fd1f997be8439a17cc3ed17d895e2c | rcvenky/hacktoberfest2020 | /Solution/Python/LinearSearch.py | 436 | 4.0625 | 4 | def linearsearch(arr,size,key):
for i in range(len(arr)):
if arr[i]==key:
return i
return -1
size=int(input("Enter size of array: "))
arr=[]
for i in range(size):
arr.append(int(input("Enter the element: ")))
key =int(input("Enter element to be searched: "))
ans=linearsearch(arr,size,key)
if ans==-1:
print("Element Not Found")
else:
print("Element found at ",ans+1," index")
|
8e4c710951518949e91577ff31d8a79dce045e6e | asishraz/banka_sir_notes | /ch_1/main.py | 106 | 4 | 4 | #1. wap to input two numbers and print their sum
a = int(input())
b = int(input())
print("Sum is: ", a+b) |
2e115fd623d6d7c98821aa58ed696d53ff57a8a7 | fdl9/fdl9python | /PaulTutorial/Lesson1/read_file.py | 338 | 3.59375 | 4 | import os
import sys
#open file to read
to_read_file_pointer = open("to read.txt", 'r')
a=0
for line in to_read_file_pointer:
a = a + 1
#print("Line:{0}".format(line))
#print("index value is {1}, Line value is {0}".format(line,a))
print("Line value is {0}, index value is {1}".format(line,a))
to_read_file_pointer.close() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.