blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
697e60d969dbd76294777f36eeb39c469f164800 | knitinjaideep/Python | /fileRecursion.py | 503 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 3 09:13:25 2019
@author: nitinkotcherlakota
"""
def threeNumberSum(array, targetSum):
final_array = []
for i in range(len(array)-2):
a = array[i]
for j in range(i+1,len(array)-1):
b = array[j]
for k in (i+2,len(array)):
c = array[k]
if a+b+c == targetSum:
final_array.append(sorted[a,b,c])
if len(final_array) == 0:
return []
else:
final_array
array = [1,2,3,4,5,6]
targetSum = 10 |
06ca7f1662023ecb7bd2e5eedef72bac1128683d | chablis8/ECON611_HW5_GrpProject | /hw5.py | 375 | 4.15625 | 4 |
# use recursion to find factorial
def find_factori(x):
try:
if x == 1 :
return 1
elif x<1 or not (isinstance(x, int)):
return 'no flaot & negatives'
else:
return x*find_factori(x-1)
except Exception:
return ('invalid input')
# test function
print(find_factori(-1))
|
558a3748b51b3624d46493f8e9c13340069cfb7d | fionnmcguire1/LanguageLearning | /PythonTraining/Python27/PalendromicSubstrings_medium.py | 1,669 | 4.1875 | 4 | '''
Author: Fionn Mcguire
Date: 25-11-2017
Description: Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
'''
'''
Requirements:
Traverse through string
Add length of string to answer
Get substring
Test if a substring is a pallindrome
create hash function to store a list of indexs of letters
any sublist with more than one entry test for pallindome
'''
InputString = raw_input("Please enter a string: ")
dictOfIndexes = {}
ListOfOrganisedChars = []
def hash_function(ListOfOrganisedChars, dictOfIndexes,char,index):
if char in dictOfIndexes:
ListOfOrganisedChars[dictOfIndexes[char]].append(index)
else:
dictOfIndexes[char] = len(ListOfOrganisedChars)
ListOfOrganisedChars.append([index])
return dictOfIndexes,ListOfOrganisedChars
for index,value in enumerate(InputString):
dictOfIndexes,ListOfOrganisedChars = hash_function(ListOfOrganisedChars, dictOfIndexes,value,index)
totalPsubs = len(InputString)
Length = len(ListOfOrganisedChars)
for i in xrange(Length):
if len(ListOfOrganisedChars[i]) > 1:
for j in xrange(len(ListOfOrganisedChars[i])-1):
k = 1
while k+j < len(ListOfOrganisedChars[i]):
str1 = InputString[ListOfOrganisedChars[i][j]:(ListOfOrganisedChars[i][j+k]+1)]
if str1 == str1[::-1]:
totalPsubs+=1
k+=1
print "Total Palindromic Substrings: ",; print totalPsubs
#print(ListOfOrganisedChars)
|
261e4d8a6eaa4ecdbed16093110be47c5dc0fed1 | praveengadiyaram369/geeksforgeeks_submissions | /geeksforgeeks_SumOfDigitsNumber.py | 143 | 3.625 | 4 | # _Sum of Digits of a Number
def sumOfDigits(n):
if n > 0:
return ((n % 10) + sumOfDigits(int(n/10)))
else:
return 0
|
b5087a93226c431ec34de00bc02957c4aa6f23dc | daniloaugusto0212/EstudoPython | /python_dankicode/listas/strings_range.py | 94 | 3.6875 | 4 | # 0123456
nome = "chicago"
print(nome[1]) #letra h
for x in nome:
print(x, end='') |
647450b99c9a43248f7af8599c8d8420b0a74c15 | htmathl/exerciciosPython | /python_types.py | 284 | 3.609375 | 4 | str = input('digite algo: ')
print('Alpha: ', str.isalpha())
print('Alfanum: ', str.isalnum())
print('Numeric: ', str.isnumeric())
print('Uppercase: ', str.isupper())
print('Lowercase: ', str.islower())
print('Capitalize: ', str.istitle())
print('Only with spaces: ', str.isspace())
|
b80198383d69433f99adbef91c44495cf4831087 | rohangiriraj/classic-problems-in-cs | /nth_fib.py | 687 | 4.40625 | 4 | # Program to find the Nth Fibonacci number.
# Example: If n=5 then the fibonacci number is 5.
# This program is done using loops, recursive solution seems needlessly complicated.
def nthfib(n):
if n == 0:
print(f"The {n}th Fibonacci number is 0")
elif n == 1:
print(f"The {n}st Fibonacci number is 1")
elif n == 2:
print(f"The {n}nd Fibonacci number is 1")
else:
a = 0
b = 1
c = 0
counter = 2
while counter <= n:
c = a + b
a = b
b = c
counter += 1
print(f"The {n} [th] Fibonacci number is {c}")
n = int(input("Enter the value of n \n"))
nthfib(n)
|
097aba00cac3e135fe3fd9b469773d89bf79390a | syurskyi/Algorithms_and_Data_Structure | /Linked List Data Structure using Python/exercise/Section 5 Singly Linked List/SLL-Easy.py | 1,228 | 4.21875 | 4 | # # Print the middle node of a Singly Linked List
#
# c_ Node
# ___ - data
# ? ?
# next _ N..
#
# c_ LinkedList
# ___ -
# head _ N..
#
# ___ insertEnd newNode
# __ h.. __ N..
# h.. _ ?
# r_
# lastNode _ h..
# w__ ?.ne.. __ no. N..
# ? _ ?.ne..
# ?.ne.. _ ?
#
# ___ listLength
# length _ 0
# currentNode _ h..
# w__ cN.. __ no. N..
# l.. +_ 1
# cN__ _ cN__.ne..
# r_ ?
#
# ___ printMiddle
# length _ lL..
# __ ? !_ 0
# if ? __ 1
# print("Middle Node: ",head.data)
# r_
# middlePosition _ ? // 2
# middleNode _ h..
# w__ mP.. !_ 0:
# mN.. _ mN__.ne..
# mP.. -_ 1
# print("Middle Node: " mN__.d..
#
# nodeOne = Node(1)
# nodeTwo = Node(5)
# nodeThree = Node(3)
# nodeFour = Node(10)
# nodeFive = Node(6)
# linkedList = LinkedList()
# linkedList.insertEnd(nodeOne)
# linkedList.insertEnd(nodeTwo)
# linkedList.insertEnd(nodeThree)
# linkedList.insertEnd(nodeFour)
# linkedList.insertEnd(nodeFive)
# linkedList.printMiddle()
|
ed43992b3b349fff219c2d92381820877dcdc8b2 | PrestonSo4/PythonChallenges | /Triangle Trig/triangleFunctions.py | 2,222 | 4.21875 | 4 | #https://www.101computing.net/triangle-geometry-functions/
from math import sqrt
def getPerimeter(a,b,c):
perimeter = a+b+c
print("The perimeter of a triangle with sidelengths: " + str(a) + ", "+ str(b) + ", "+ str(c) + ", will have a perimeter of:", perimeter)
def getArea(b, h):
area = b*h/2
print("The area of a triangle with a baselegth of:", b, "and a height of:", h, "will be:", area)
def getAngles(a1, a2):
if a1 + a2 > 180:
print("Those are invalid angles for a triangle")
else:
a3 = 180 - a1 - a2
print("The final angle of a triangle with angles:", a1, "and", a2, "will be:", a3)
def isEquilateral(a,b,c):
if a == b and a == c:
print("The triangle with all sidelengths of:", a, "is an equilateral triangle.")
else:
print("Your triangle with the specified information is not an equilateral tirangle")
def isIsoscles(a,b,c):
if a == b or a == c or b == c:
print("A triangle with the sideslengths of:",str(a) + ",",str(b) + ",",str(c) + ", is an Isoscles triangle.")
else:
print("Your triangle with the specified information is not an isoscles tirangle")
def pythagTheorem():
q = input("Are you solving for c (the hypotenuse)?(y/n) ").lower()
if q == "y":
a = float(input("What is the value for sidelength a? "))
b = float(input("What is the value for sidelength b? "))
c = sqrt(a**2+b**2)
print("The length of side C is:", c)
else:
q2 = str(input("What side are you solving for? (a/b): ")).lower()
if q2 == "a":
c = float(input("What is the length of the hypotonuse? "))
b = float(input("What is the length of side b? "))
a = sqrt(c**2-b**2)
print("The length of side A is:",a)
if q2 == "b":
c = float(input("What is the length of the hypotonuse? "))
a = float(input("What is the length of side b? "))
b = sqrt(c**2-a**2)
print("The length of side A is:",a)
def heronForm(a,b,c):
s = (a+b+c)/2
area = sqrt(s*(s-a)*(s-b)*(s-c))
print("The area of a triangle with sidelenghts: "+str(a)+", "+str(b)+", "+str(c)+", is:", area)
|
32e0c1fbdfe0e257e70dd7e932dea5ca38ab4f31 | gberger/euler | /27.py | 1,076 | 3.9375 | 4 | A = range(-1000,1001)
B = range(-1000,1001)
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
def qqtyprimes(a, b):
formula = lambda x: x**2 + a*x + b
foundprime = True
n=0
while foundprime:
foundprime = isprime(formula(n))
if foundprime:
n += 1
return n
maxp = 0
for b in B:
if isprime(b):
for a in A:
p = qqtyprimes(a, b)
if p > maxp:
maxp = p
maxa = a
maxb = b
print maxp, maxa, maxb |
fab7be18661fc5a820021fd84d2e3f5d466dc73a | KodianKodes/holbertonschool-sysadmin_devops | /0x17-api/0-gather_data_from_an_API.py | 964 | 3.703125 | 4 | #!/usr/bin/python3
"""
Write a script that hits a REST api that has data on employees and tasks
and filters the data based on an argument passed to the script.
The argument is the employee ID, and the output should display the employee
name and the tasks the employee completed.
"""
import requests
import sys
if __name__ == "__main__":
eid = sys.argv[1]
name = requests.get("http://jsonplaceholder.typicode.com/users/{}"
.format(eid)).json().get("name")
total_tasks = 0
done_tasks = []
r = requests.get("http://jsonplaceholder.typicode.com/todos").json()
for task in r:
if (task.get("userId") == int(eid)):
total_tasks += 1
if (task.get("completed")):
done_tasks.append(task.get("title"))
print("Employee {} is done with tasks({:d}/{:d}):"
.format(name, len(done_tasks), total_tasks))
for item in done_tasks:
print("\t {}".format(item))
|
e9fcca5aa9af972c5d5a618bca330feedfdbcc43 | Sildinho/aprendaPython3DoJeitoCerto | /apy3JeitoCerto_Exerc_33.py | 407 | 4.1875 | 4 | # -- coding utf-8 --
""" Exercício 33 - loops while - pag: 119 - livro aprenda python 3 do jeito certo by zed shaw - https://learnpythonthehardway.org/"""
i = 0
numbers = []
while i < 6:
print(f"\nNo inicio: {i}")
numbers.append(i)
i = i + 1
print("O numero agora: ", numbers)
print(f"é atribuito para i: {i}")
print("O numero: ")
for num in numbers:
print(num)
|
2874ee80f58097ce6e3fc19c040210d8837855b8 | diocelinas561/programacion-python | /programas 1 diocelina/ejercicio 2 dioce.py | 331 | 3.625 | 4 | #Diocelina Sierra martinez
#22/11/16
#ejercicio 2
interes=input("ingresar el saldo al final del ano:")
pirmer=interes*.4
segundo=interes*.8
tercero=interes*.12
1resultado=interes+primer
2resultado=interes+segundo
3resultado=interes+tercero
print "saldo 1 al final", 1resultado
print "saldo 2 al final", 2resultado
print "saldo3 al final", 3resultado
|
97d2432ae3d9310f09e7f6ebe838f9ec58e3c927 | yatish0492/PythonTutorial | /36_1_Duck_Typing.py | 631 | 4.03125 | 4 | '''
Duck Typing
-----------
We can pass/assign any class obj to a variable as we don't specify the type of variable any class object can be
assigned to it.
'''
class StartCar:
def start(self, someCar): # We are passing 'Cruze' and 'Ritz' class objects to same parameter 'someCar'
print("Starting car " + someCar.name)
class Cruze:
name = "Cruze"
class Ritz:
name = "Ritz"
cruzeObj = Cruze()
ritzObj = Ritz()
startCarObj = StartCar()
startCarObj.start(cruzeObj) # We are passing 'Cruze' class object
startCarObj.start(ritzObj) # We are passing 'Ritz' class object to the same method |
5a5d27d8b8b826d15fc5cf2349c2ef02c53cfae6 | wouterPardon/AI | /CodeAdvent/Day2/PartTwoMain.py | 793 | 3.515625 | 4 | #!/usr/bin/env python
inputFile = open('./input.txt')
words = []
def main():
for word in inputFile.readlines():
words.append(word.strip())
check(words)
def check(word_list):
done = False
for word in word_list:
for _word in word_list:
count = 0
all_same_chars = []
if not done:
for i in range(len(_word)):
if _word[i] == word[i]:
count += 1
all_same_chars.append(_word[i])
if count == 25:
print(word, _word, count, all_same_chars)
for char in all_same_chars:
print(char, end='')
done = True
if __name__ == '__main__':
main()
|
a4f58e013e1e776102968b840d51e4b9a553f83a | marciof2/PYTHON- | /desafio42.py | 532 | 4.15625 | 4 | n= int(input('Primeira Medida: '))
n2= int(input('Segunda Medida: '))
n3= int(input('Terceira Medida: '))
print('\n')
if n < n2 + n3 and n2 < n3 + n and n3< n + n2:
print('É um TRIANGULO !!')
if n==n2==n3:
print('Classificado como EQUILÁTERO.')
elif n != n2 and n!= n3 and n2!=n3:
print('Classificado como ESCALENO.')
elif n == n2 and n!= n3 or n2 == n3 and n2!=n or n3==n and n3!=n2:
print('Classificado como ISÓSCELES.')
else:
print('NÃO é um triangulo.')
print('\n') |
a7b0e055c133a9ac884a1ecf929d35604f95cd09 | AHecky3/Chapter_7 | /Solutions/challenge2.py | 4,077 | 4.40625 | 4 | """
2. Improve the Trivia Challenge game so that it maintains a highscores list in a file.
The program should record the player’s name and score if the player makes the list.
Store the high scores using a pickled object.
"""
#Challenge 2
#Andrew Hecky
#12/9/2014
import sys, pickle
def open_file(file_name, mode):
"""Open a file."""
try:
the_file = open(file_name, mode)
except IOError as e:
print("Unable to open the file", file_name, "Ending program.\n", e)
input("\n\nPress the enter key to exit.")
sys.exit()
else:
return the_file
def next_line(the_file):
"""Return next line from the trivia file, formatted."""
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
"""Return the next block of data from the trivia file."""
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct = correct[0]
points = next_line(the_file)
try:
points = int(points)
except ValueError:
print()
explanation = next_line(the_file)
return category, question, answers, correct, points, explanation
def welcome(title):
"""Welcome the player and get his/her name."""
print("\t\tWelcome to Trivia Challenge!\n")
print("\t\t", title, "\n")
def main():
global score
trivia_file = open_file("trivia.txt", "r")
title = next_line(trivia_file)
welcome(title)
score = 0
# get first block
category, question, answers, correct, points, explanation = next_block(trivia_file)
while category:
print()
# ask a question
print(category)
print("This question is worth " + str(points) + " points!\n")
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer
answer = input("What's your answer?: ")
# check answer
if answer == correct:
print("\nRight!", end=" ")
score += int(points)
else:
print("\nWrong.", end=" ")
print(explanation)
print("Score:", score, "\n\n")
# get next block
category, question, answers, correct, points, explanation = next_block(trivia_file)
trivia_file.close()
print("That was the last question!")
print("You're final score is", score)
def highscores(score):
###HIGHSCORES###
addscore = True
username = ""
try:
highscores = pickle.load(open('highscores2.txt', 'rb')) #Loading
except EOFError:
highscores = []
highscores = sorted(highscores, key=lambda tup: tup[1], reverse=True) #Sorting
try: #Checking to see if made highscore list
for i in highscores:
if score > i[1]:
addscore = True
else:
addscore = False
except UnboundLocalError:
addscore = True
if len(highscores) < 5: #Adding score if max score isnt reached
addscore = True
if addscore == True: #If made new highscore
print("\nYou've set a new highscore! ")
while username == "":
username = input("Enter Your Name: ") #Getting username
add = (username, int(score)) #Making tuple (User Name, User Score)
highscores.append(add) #Adding Tuple to highscore list
highscores = sorted(highscores, key=lambda tup: tup[1], reverse=True) #Sortign again
if len(highscores) > 5: #Deleting score if list limit (5) is reached
highscores.pop(5)
print("\n HIGHSCORES:") #printing highscores
num1 = 0
for i in highscores:
num1 += 1
num = i[1]
print("\t" + str(num1) + ") " + i[0] + ': ' + str(num))
pickle.dump(highscores,open('highscores2.txt','wb')) #Saving highscores=
###END HIGHSCORES###
main()
highscores(score)
input("\n\nPress the enter key to exit.")
|
bdec24f78ba76f08d4075a9ea6df9948d42aab53 | vikas0694/python_programs | /dictionaries in python/dic0.py | 499 | 3.53125 | 4 | # # dictionaries
# #
# # how to add data
#
# data
user_info = {
'name' : 'vikas' ,
'age' : '23',
'movie' : ['lagaan, coco'],
'song' : ['chalti ka naam gadi, music, gana'],
}
# add and delete data
#
# how to add data
user_info['fav_songs'] = ['song1', 'song2']
print(user_info)
#
# pop method
popped_item = user_info.pop('age')
print(type(popped_item))
print(user_info)
# add and delete data
# how to add data
# user_info['fav_songs'] = ['song1', 'song2']
# print(user_info) |
fce26a6371424e5802189a55edf529256f99772a | terralogic-QA/Python-Selenium | /sangeetha-k/commonInLists.py | 588 | 3.96875 | 4 | found = 0
# first list
size = int(input('Enter total number of elements in list 1: '))
list1 = []
for j in range(0, size):
num = int(input('Enter element of position {} '.format(j+1)))
list1.append(num)
# second list
size1 = int(input('Enter total number of elements in list 2: '))
list2 = []
for j in range(0, size1):
num = int(input('Enter element of position {} '.format(j+1)))
list2.append(num)
for num in list1:
if num in list2:
found = 1
print(num, 'is common in two lists')
if found == 0:
print('There are no common elements in the list')
|
5abc764836fa97b5b4ad689900ed02086ab818ca | lacra-oloeriu/learn-python | /ex7.py | 779 | 4.25 | 4 | print("Mary had a littlr lamb. ")#This is a comment
print("Its fleece was write as{}." . format('snow'))#that is a comment whit format that is means ...
print("and everywhere that Mary went.")#that is a comment
print(" ." * 10 ) # what'd that do ?#that's do 10points
end1 = "C"#this is a variablle
end2 ="h"#variable
end3 ="e"#variable
end4 ="e"#variable
end5 ="s"#variable
end6 ="e"#variable
end7 ="B"#variable
end8 ="u"#variable
end9 ="r"#variable
end10 ="g"#variable
end11 ="e"#variable
end12 ="r"#variable
# watch that comma at the end. try removing it to see what happens
print(end1 + end2 + end3 + end4 + end5 + end6 + end6, end=' ' ) #that is a part of the woed cheese burgeer
print(end7 + end8 + end9 + end10 + end11 + end12 )#that is a part of the word cheese burger
|
9de1f0d31f265accfc3835a311a160dc849e2344 | huangy10/LearningTensorFlow | /example6.py | 2,352 | 3.671875 | 4 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# This tutorial is about add_layer
layer_count = 1
def add_layer(inputs, in_size, out_size, activation_function=None):
global layer_count
with tf.name_scope("layer%s" % layer_count):
with tf.name_scope("weights"):
Weights = tf.Variable(tf.random_uniform([in_size, out_size]), name="W")
with tf.name_scope("bias"):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name="b")
with tf.name_scope("Wx_plus_b"):
Wx_plus_b = tf.matmul(inputs, Weights) + biases
# activate
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
layer_count += 1
return outputs
# Now we build the network
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise
with tf.name_scope("inputs"):
xs = tf.placeholder(tf.float32, [None, 1], name="x_input")
ys = tf.placeholder(tf.float32, [None, 1], name="y_input")
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
prediction = add_layer(l1, 10, 1, activation_function=None)
with tf.name_scope("loss"):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]), name="mean")
# loss = tf.reduce_mean(tf.square(ys - prediction))
with tf.name_scope("train"):
optimizer = tf.train.GradientDescentOptimizer(0.1)
train_step = optimizer.minimize(loss)
with tf.name_scope("www"):
init = tf.initialize_all_variables()
sess = tf.Session()
# writer = tf.train.SummaryWriter("logs/", sess.graph_def)
writer = tf.summary.FileWriter("logs/", sess.graph)
sess.run(init)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x_data, y_data)
plt.ion()
plt.show()
feed_data = {xs: x_data, ys: y_data}
lines = None
for i in range(1000):
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i % 10 == 0:
# print sess.run(loss, feed_dict={xs: x_data, ys: y_data})
try:
ax.lines.remove(lines[0])
except Exception:
pass
prediction_value = sess.run(prediction, feed_dict=feed_data)
lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
plt.pause(0.1)
|
2ff313726f1719bcdcd28b3ab1129079ce7b4e72 | ryojikaji/school | /NJPOII/Collections/kolekcja.py | 2,389 | 3.828125 | 4 | # zadanie 3: Stwórz kolekcję książek zawierającą takie pola jak tytuł, gatunek, autor, isbn. Napisz trzy funkcje, (i) zapisującą kolekcję, (ii) odczytującą kolekcję, (iii) obliczająca statystykę wg. gatunku i autora.
# File :: "books.txt"
# Funkcja odczytująca kolekcje z pliku || użycie readBooks()
def readBooks():
file = open("books.txt", "r")
content = file.readlines()
i = 1
for x in content:
print(i)
words = x.split()
print(" Title: ",words[0])
print(" Genre: ",words[1])
print(" Author: ",words[2])
print(" ISBN: ",words[3])
i += 1
print('\n\n')
# Funkcja zapisująca (dopisująca) kolekcję do pliku || użycie addBook("xyz","abc","ijk",123)
def addBook(title,genre,author,isbn):
file = open("books.txt", "r")
content = file.readlines()
stop = False
for x in content:
words = x.split()
if(int(words[3]) == int(isbn)):
stop = True
break
if not stop:
file = open("books.txt", "a")
file.write('\n')
file.write(title.replace(" ", "_"))
file.write(" ")
file.write(genre.replace(" ", "_"))
file.write(" ")
file.write(author.replace(" ", "_"))
file.write(" ")
file.write(str(isbn))
file.write(" ")
if stop:
print("Book with this ISBN already exists!")
# Funkcja wyświetlająca statystykę gatunków || użycie bookGenreStats()
def bookGenreStats():
from collections import Counter
deq = deque()
file = open("books.txt", "r")
content = file.readlines()
for x in content:
words = x.split()
deq.append(words[1])
counter = Counter(deq)
print(sorted(counter.items(), key=lambda x: x[1]))
print('\n\n')
# Funkcja wyświetlająca statystykę autorów || użycie bookAuthorStats()
def bookAuthorStats():
from collections import OrderedDict
d = {}
file = open("books.txt", "r")
content = file.readlines()
for x in content:
words = x.split()
if words[2] in d:
d[words[2]] += 1
else:
d[words[2]] = 1
od = OrderedDict(sorted(d.items(), key=lambda x: x[1]))
for i, (key, val) in enumerate(od.items()):
print(f'{i+1}. {key:8} ----- {val}')
print('\n\n')
readBooks()
bookGenreStats()
bookAuthorStats() |
7f17e64984e107f69b3ef35e9f83ed1381307e53 | RuningBird/pythonL | /day01/wordgame2.py | 355 | 3.78125 | 4 | import random as rd
print("-------------------")
guess = 0
rdnum = rd.randint(1, 10)
while guess != rdnum:
temp = input("心中数字:")
guess = int(temp)
if guess == rdnum:
print("right")
guess = rdnum
else:
if guess > rdnum:
print("big")
else:
print("little")
print('game over')
|
3a8fafb60e6c85e58c1f078f659b937263d1fe33 | dalq/python-cookbook | /cookbook/two/20OperationOnByteString.py | 412 | 3.578125 | 4 | # 在字节串上执行文本操作
# 几乎所有能再文本字符串上执行的操作同样也可以在字节串就上进行
data = b'Hello World'
print(data)
print(data[0:5])
d = bytearray(b'Hello World')
print(d)
print(d[0:5])
# 区别
a1 = 'Hello World'
print(a1[0])
a2 = b'Hello World'
print(a2[0])
#如果想对字节串做格式化操作,应该先转为普通的文本字符串然后再做编码
|
c49186e2b549c43849d0af572a522fca482a9593 | Nitindrdarker/datastructures-with-python | /stack.py | 1,230 | 4 | 4 | class node():
def __init__(self,d):
self.data = d
self.next = None
class Stack():
def __init__(self):
self.head = None
def push_stack(self,d):
new_node = node(d)
if(self.head == None):
self.head = new_node
else:
last = self.head
while(last.next != None):
last = last.next
last.next = new_node
def display_stack(self):
temp = self.head
while(temp != None):
print(temp.data)
temp = temp.next
def pop_stack(self):
if(self.head.next == None):
self.head = None
temp = self.head
while(temp.next.next !=None):
temp = temp.next
temp.next = None
def peek_stack(self):
temp = self.head
while(temp.next != None):
temp = temp.next
print(temp.data)
stk = Stack()
stk.push_stack(1)
stk.push_stack(2)
stk.push_stack(3)
stk.push_stack(4)
stk.display_stack()
stk.pop_stack()
stk.display_stack()
stk.push_stack(6)
stk.display_stack()
stk.pop_stack()
stk.display_stack()
stk.push_stack(10)
stk.peek_stack()
|
4138d1ae5975bf963934ad6937b1c6aee61597e0 | nueadkie/cs362-hw4 | /test_full_name.py | 593 | 3.59375 | 4 | import unittest
import full_name
class Tester(unittest.TestCase):
# Test for a case of a mix between integers/floats/complex numbers.
def test_name(self):
result = full_name.generate("Chris", "Miraflor")
self.assertEqual(result, "Chris Miraflor")
# Test for a case with non-string inputs.
def test_nums(self):
with self.assertRaises(TypeError):
full_name.generate(1234, 5678)
# Test for a case with too few inputs.
def test_few_inputs(self):
with self.assertRaises(TypeError):
full_name.generate("Full Name")
if __name__ == '__main__':
unittest.main() |
df0f515e92e8861dbeb77b8c59f965558494eb3c | evaseemefly/CasablancaPython_Pro | /myPy.py | 432 | 3.9375 | 4 | a = "123"
print(a)
# 有序集合
mylist = ['联系人1','联系人2','联系人3']
print(mylist)
len(mylist)
# 取出末尾的元素
a = mylist.pop()
print(a)
# 元组-tuple
mytuple=('测试1','测试2','测试3')
print(mytuple[0])
L=[
['Apple','Google','Microsoft'],
['Java','Python','Ruby','Php'],
['drno','Casablanca']
]
# 打印Apple
print(L[0][0])
# 打印Python
print(L[1][1])
# 打印Casablanca
print(L[2][1]) |
96f39aa2f1d58f4bde0b22ca5bb5f439abf2736f | imoren2x/biblab | /Python/02_Ejercicios/01_Basic/ProgrFun_3_generador.py | 1,240 | 4.5625 | 5 | #!/usr/bin/python
# -*- coding: latin-1 -*-
"""
Las expresiones generadoras funcionan de forma muy similar a la
comprensión de listas.
Su sintaxis es igual pero usan parentesis en lugar de corchetes.
Lo que devuelven son una funcion generadora.
El generador se puede utilizar en cualquier lugar donde se necesite un
objeto iterable. Por ejemplo en un for in
"""
def mi_generador(n, m, s):
while n <= m:
yield n
n += s
if __name__ == "__main__":
print "Funcion generador al cuadrado"
l = [1, 2, 3, 4, 5, 6]
print "Entrada: ", l
l2 = (n ** 2 for n in l)
print "Salida: ", l2
#l3 = [for n in l n ** 2 ] #NO VALIDO#
print "Usando la funcion generador"
for n in mi_generador(0, 5, 1):
print n
"""
Como no estamos creando una lista completa en memoria, sino
generando un solo valor cada vez que se necesita, en
situaciones en las que no sea necesario tener la lista
completa el uso de generadores puede suponer una gran
diferencia de memoria. En todo caso siempre es posible
crear una lista a partir de un generador mediante la función
list
"""
#lista = list(mi_generador)
#print lista
|
334823b7d3e9045a58f2b73d07b9ee2c9850ac77 | aditiav/python-projects | /Guess-Number.py | 1,466 | 3.875 | 4 | import random
randnum = random.randint(1,100)
inputnum=input('Guess your number between 0 and 100 : ')
num=int(inputnum)
print(randnum)
myguess=[0]
len(myguess)
while num !=randnum:
if num < 1 or num >100:
print ('\nNumber out of bounds')
inputnum=input('Guess the number between 0 and 100 : ')
num=int(inputnum)
continue
elif abs(randnum - num)>10 and len(myguess) == 1:
myguess.append(num)
print ('cold')
inputnum=input('Guess the number : ')
num=int(inputnum)
continue
elif abs(randnum - num)<10 and len(myguess) == 1:
myguess.append(num)
print ('warm')
inputnum=input('Guess the number : ')
num=int(inputnum)
continue
elif abs(randnum - num) < abs(randnum - myguess[-1]):
myguess.append(num)
print ('warmer')
inputnum=input('Guess the number : ')
num=int(inputnum)
continue
elif abs(randnum - num) > abs(randnum- myguess[-1]):
myguess.append(num)
print ('colder')
inputnum=input('Guess the number : ')
num=int(inputnum)
continue
elif num==randnum:
print ('You guessed the number in % guesses'.format(len(myguess)+2) )
break
print ('You guessed the number in {} guesses'.format(len(myguess)) )
|
b02ae3dabdee904b6c4e614cb52cf1101399bb51 | aasgreen/Quantum-Hall-Effect | /Code/ocupBose.py | 20,610 | 3.5625 | 4 | import sys
import os
from numpy import *
import math
'''Program: Temp_Plot
This is a new program that I will be using to test my code. It will calculate the hall conductivity, for
the case of bosons for the case of finite temperature. The major change to this program, is that instead of interating over temperature.
'''
'''JOBS:
1) Find the bose condensate temperature
2) Iterate through the temperatures BEC-> END_TEMP and find the
chemical potential that fixes the number of particles at that
specific temperature to a user defined value
3) Calculate the bose occupation factor using that chemical potential
and the temperature
4) Calculate the kubo contribution and sum up over all contributions
5) Output this as a file
'''
'''FUNCTION LIST'''
def n_now(work, Mu, t):
N = 0.0
for energy in work:
#Making energy a float makes sure to cast it from a complex
#The reason for this is because a complex will overflow too quickly
#So the exponential will overflow.
energy = float(energy)
#BOSON PREFAC##########
if math.isinf(exp((energy-Mu)/float(t) )):
n_x = 0.
else:
n_x = 1.0/(exp( (energy-Mu)/float(t))-1.0)
#print "f", 1/exp(1/t*(energy-Mu))
#END BOSON PREFAC
N = N + n_x
#FERMI PREFAC#####################
#if energy <= t:
# n_x = 1.
#elif energy > t:
# n_x = 0.
#END FERMI PREFAC
return N
def bisection_t(UP, BOTTOM, n_now, energy_a, Num_Part, Mu):
'''The purpose of this function is to calculate the bose_temperature. Which is where the temperature iteration will
start. Mu is set to the lowest energy level. The bose temperature will be the smallest temperature where the particle number is conserved.'''
#Num_part is the number of particles
t1 = BOTTOM
# print t1
t2 = UP
c = (t1+t2)/2.
# print 'c', c
#The tolerance has to be low for this to converge.
tolerance = .00001
for i in range(0,LARGE_NUMBER):
fc = n_now(energy_a, Mu, c)-Num_Part
f1 = n_now(energy_a, Mu, t1) -Num_Part
f2 = n_now(energy_a, Mu, t2) - Num_Part
# print f1, fc, f2
if (fc*f2 < 0):
t1 = c
elif (fc*f1 < 0):
t2 = c
else:
print 'f1',f1,'f2',f2,'fc',fc
print 'bisect error'
sys.exit()
# print 'f1',f1,'f2',f2,'fc',fc
c = (t1+t2)/2.
# print 'The BEC TEMP is:', t1, 'N = ', n_now(energy_a, Mu, t1),'c',c, Mu,
print n_now(energy_a, Mu, t1)-Num_Part, tolerance
if (abs(f1) < tolerance):
print i
break
if i == LARGE_NUMBER:
print "BISECTION FAILURE"
return(t1)
def bisection_Mu(UP, BOTTOM, n_now, energy_a, Num_Part, temp):
'''This is to find the right chemical potential at a specific temperature that ensures that as the temperature is
increased, the number of particles remains conserved'''
mu1 = BOTTOM
# print t1
mu2 = UP
c = (mu1+mu2)/2
# print 'c', c
tolerance = .0001
for i in range(0,LARGE_NUMBER):
fc = n_now(energy_a, c, temp)-Num_Part
f1 = n_now(energy_a, mu1, temp) -Num_Part
f2 = n_now(energy_a, mu2, temp) - Num_Part
#print fc
if (abs(f1) < tolerance):
return mu1
if (abs(f2) < tolerance):
return mu2
if (abs(fc) < tolerance):
return c
# print f1, fc, f2
if (fc*f2 < 0):
mu1 = c
elif (fc*f1 < 0):
mu2 = c
else:
print 'bisect error'
sys.exit()
#print 'f1',f1,'f2',f2,'fc',fc
c = (mu1+mu2)/2
#print 'The MU is:', mu1, 'N = ', n_now(energy_a, mu1, temp),'c',c, temp,
#N = n_now(energy_a, mu1, temp)
#print N,N-Num_Part, tolerance, mu1, mu2
print "BISECTION FAILURE"
sys.exit()
def readin_files(eigenName, jName):
#The first task is to read in all the data and preserve the block structure of the matrices
#READ-IN CURRENT OPERATOR:
tmp1 = loadtxt(jName+'_yRE.dat', unpack=True)
tmp2=loadtxt(jName+'_yIM.dat', unpack=True)
tmp3 = loadtxt(jName+'_xRE.dat',unpack=True )
tmp4=loadtxt(jName+'_xIM.dat',unpack=True )
tpo1 = array([tmp3[0],tmp3[1]])
jmatrix_x = vstack( (tpo1,tmp3[2::]+multiply(1j,tmp4[2::]) ))
print jmatrix_x[1]
tpo2 = array([tmp2[0],tmp2[1] ])
jmatrix_y = vstack( (tpo2,tmp1[2::]+multiply(1j,tmp2[2::])) )
jmatrix_x = jmatrix_x.transpose()
jmatrix_y = jmatrix_y.transpose()
#jmatrix will contain the current matrix, seperated into blocks
#data should be [ky][kx][ENERGY]{[E][I][G][N][E][V][E][C][T][O][R]}
#jmatrix should be [ky,kx, m,a,t,r,i,x}
#END READIN CURRENT OPERATOR######################
#READ-IN HAMILTONIAN AND ENERGY#####################
data_real = loadtxt(eigenName+'real.dat', unpack=True)
data_imag = loadtxt(eigenName+'imag.dat', unpack=True)
data =vstack( (data_real[:4], data_real[4:]+multiply(1j,data_imag[4:])) )
#END READ_IN HAMILTONIAN#####################
return data, jmatrix_x, jmatrix_y
def kubo_cal(alphaVec,betaVec,alphaEnergy, betaEnergy, j_x, j_y):
kubotop = vdot(alphaVec,dot(j_x,betaVec))*vdot(betaVec,dot(j_y,alphaVec))-vdot(alphaVec,dot(j_y, betaVec))*vdot(betaVec,dot(j_x,alphaVec))
kubobottom = (alphaEnergy-betaEnergy+1j*1e-15)*(alphaEnergy-betaEnergy-1j*1e-15)
return kubotop/kubobottom
def kubo_subband(kxList, kyList, jMatrix_x, jMatrix_y, eigMatrix ):
#ARGS: kx is a set of kx values
# ky is a set of ky values
# jMatrix_ are Q*(Num of k values)**2 matrices
# eigMatrix is a matrix of vectors, each row contains the kx,ky, the eigenenergy and the eigenvector
# Initialize the kubo value
kubo=0.0
for kx in kxList:
for ky in kyList:#now we are in a regime where we have isolated our block. Need to test
# Define the block as those rows which share the same kx,ky.
bloc = [j[3::] for i,j in enumerate(data_trans) if data_trans[i][0] == kx and data_trans[i][1]==ky]
bloc_jx = array([j[2::] for i,j in enumerate(jmatrix_x) if jmatrix_x[i][0] == kx and jmatrix_x[i][1] == ky])
bloc_jy = array([j[2::] for i,j in enumerate(jmatrix_y) if jmatrix_y[i][0] == kx and jmatrix_y[i][1] == ky])
#Now, calculate the number of points in K-space (assume Lx == Ly)
L = float(len(jmatrix_y))
kubo = kubo+kubo_single_energ(bloc, bloc_jx,bloc_jy,L)
return kubo
def kubo_single_alpha(Hblock, bloc_jx, bloc_jy,alpha):
'''This function will calculate the kubo contribution from a single energy level of a subband. Ie. given a kx and a ky.
it is called by a function that will calculate the kubo contribution from an entire subband'''
kubo = 0.
for beta in Hblock:
# Ensure duplicates aren't called
if all(alpha==beta):
continue
#print bloc_jx.size,
#print (len(alpha[1::])*len(beta[1::]) == bloc_jx.size)
#print (len(alpha[1::])*len(beta[1::]) ==bloc_jy.size), b, ky, kx
#print occup[alpha[0]]
#print occup[alpha[0]]
#prefac =-1j*occup[alpha[0]][-1][1]
# test to see if the energy level is occupied on the fly ( t is the fermi energy, NOT temperature)
alphaVec = alpha[1:]
betaVec = beta[1:]
alphaEn = alpha[0]
betaEn = beta[0]
kubo = kubo+kubo_cal(alphaVec, betaVec, alphaEn, betaEn, bloc_jx, bloc_jy)
#print kubo_cal(alphaVec, betaVec, alphaEn, betaEn, bloc_jx, bloc_jy), alphaEn, betaEn, 'kubo_single_alpha'
return kubo
def occupation(record,energyVec,t,mu,n_now):
'''Calculate the occupation and probability of a specific energy level'''
'''ARGS: record is the ongoing record of the ocuppation as a function of t. It has
type dictionary, and must be initialized before this function is called!
energyVec is a vector containing all the energy states possible
t is the temperature
mu is the chemical potential
n_now is a function that calculates how many particles there are.
'''
testN = 0.
testP = 0.
for energy in energyVec:
energy = energy.astype(float)
if math.isinf(exp( (energy-float(mu))/float(t) )):
ocup = 0.
print 'inf', exp( (energy-mu)/t), math.isinf( exp( (energy-mu)/t) )
else:
ocup = 1./(exp( (energy-float(mu))/float(t) )-1.)
N = n_now(energyVec, mu, t)
prob = ocup/N
#Check for degeneracies
if record[energy] != []:
if record[energy][-1] == [t,ocup,prob]:
record[energy][-1] = [t,record[energy][-1][1]+ocup, record[energy][-1][2]+prob]
print record[energy][-1]
else:
record[energy].extend([[t,ocup, prob]])
else:
record[energy].extend([[t,ocup,prob]])
testN = testN+ocup
testP = testP +prob
#print testN, N, testP
assert( testN == N)
return record
def basis_states(N, SIZEOFLATTICE, FLUX):
#We need to run the process basis generator, to find out how
#many ways needed to distribute N particles amongst the number of states
#available.
#Calculate the number of states avaiable to the system.
N = int(N)
nStates = SIZEOFLATTICE**2*FLUX
nStates = int(nStates)
#Run the process basis_gen.sh, which takes as arguments: Number of particles, Number of states
#and will generate a file called inff1.dat, which can be read in, this will contain the enumerate
#different combos/perms of N particles in nStates.
run_cmd = './basis_gen.sh '+str(N)+' '+str(nStates)
os.system(run_cmd)
#Now read in the resulting file:
bStates = loadtxt('inff1.dat')
os.system('rm inff1.dat')
#be a good citizen
return bStates
def main_kubo(bState,data,jmatrix_x, jmatrix_y, SIZEOFLATTICE, FLUX,mu,t):
kubo = 0.
for basis in bState: #this sums over the 'alphas' in the kubo formula
#basis will give way to combine block eigenvectors to get the alpha
alphaEnergy ={}
kubo_state = {}
#Split the basis into blocks, each Q long, knowing total length = Q*SIZEOFLATTICE**2
basisBlocks = hsplit(basis, SIZEOFLATTICE**2)
for startIndex,block in enumerate(basisBlocks):
#Each block is isolated from the others, so we can find the contribution from each
#of these.
numberParticlesInBloc = sum(block)
#print numberParticlesInBloc
if numberParticlesInBloc != 0:
#Then this block will contribute to kubo
sizeOfBand = len(data[numberParticlesInBloc][0])/SIZEOFLATTICE**2
Hblock = data[numberParticlesInBloc][3:].T[startIndex*sizeOfBand:(startIndex+1.)*sizeOfBand]
jxBlock = jmatrix_x[numberParticlesInBloc].T[2:].T[startIndex*sizeOfBand:(startIndex+1.)*sizeOfBand]
jyBlock = jmatrix_y[numberParticlesInBloc].T[2:].T[startIndex*sizeOfBand:(startIndex+1.)*sizeOfBand]
#Find the unique basis state vector associated with the energy
alphaEnergy[startIndex] = 0.
for blockIndex,stateValue in enumerate(block):
alphaEnergy[startIndex] = alphaEnergy[startIndex]+stateValue*float(data[1][3][startIndex*FLUX+blockIndex])
# print data[1][3][startIndex*FLUX+blockIndex], 'single particle energy', stateValue
# print alphaEnergy[startIndex], 'total energy of block'
alphaVec = [i for i in Hblock if round(i[0].astype(float)-alphaEnergy[startIndex],12) == 0]
# print alphaVec, 'alphaVec'
# print Hblock[-1].astype(float), 'Hblock'
# print alphaEnergy[startIndex],Hblock[-1][0].astype(float)
# print alphaEnergy[startIndex] == Hblock[-1][0].astype(float)
# print alphaEnergy[startIndex]- Hblock[-1][0].astype(float)
assert size(alphaVec) == size(Hblock[0])
#if this fails, then we have degeneracies and this is no longer a
alphaVec = array(alphaVec).squeeze()
#way to uniquely identify the eigenstates
# print jyBlock.T[1:].T, 'jy'
kubo_state[startIndex] = kubo_single_alpha(Hblock, jxBlock, jyBlock, alphaVec)
# print kubo_state[startIndex],'kubo_state[startIndex]'
#end for basisblocks
#Each basisblock gave a kubo contribution.
#Should now have a list of kubo states. These will be addeded together and then
#the entire term will be weighted by the total energy
total_energy = sum([alphaEnergy[i] for i in alphaEnergy.keys()])
#print total_energy, 'total energy'
total_particle = sum(basis)
prefac = -1.j/(exp( (total_energy-mu)/t )-1)
#print prefac, 'prefac', exp( (total_energy -mu)/t), mu, t, exp( (total_energy-mu*total_particle)/t)-1, total_particle
#This 'big alpha' is the summation of specific combination of eigenstates of blocks. Now
#iterate through them and add up the contributions from each block to the kubo. Then weight
#by the total energy of the alpha state.
for contribution in kubo_state.keys():
kubo = kubo + prefac*kubo_state[contribution]/SIZEOFLATTICE**2
print kubo, 'this is the kubo', kubo/prefac*SIZEOFLATTICE**2
#Iterate onto the next alpha value...
return kubo
def subband_grouper(energyVec, FLUX, SIZEOFLATTICE):
#The energyVec needs to be pasesd as type array
energyVecSorted = sort(energyVec)
numberOfSubbands = len(energyVecSorted)/SIZEOFLATTICE**2
subbands = hsplit(energyVecSorted, numberOfSubbands)
return subbands
#COMMAND LINE ARGS
if __name__ == '__main__':
END_TEMP = float(sys.argv[1])
FLUX = sys.argv[2]
SIZEOFLATTICE = sys.argv[3]
INTERACT = sys.argv[4]
Num_Part = sys.argv[5]
LARGE_NUMBER=1000000
#INITIALIZE LIST VALUES##################
NAMEBASE = 'N'+str(Num_Part)+'_Q'+str(FLUX)+'_G'+str(INTERACT)+'_Sz'+str(SIZEOFLATTICE)
INNAME2 = 'Res/current_'+NAMEBASE
INNAME = 'Res/eig_'+NAMEBASE+'_'
Num_Part = float(Num_Part)
SIZEOFLATTICE=float(SIZEOFLATTICE)
FLUX = float(FLUX)
#CALCULATE BASIS STATE OF ENTIRE SYSTEM:
bState = basis_states(Num_Part, SIZEOFLATTICE, FLUX)
#READIN all data associated with the different particle states.
data = {}
jmatrix_x = {}
jmatrix_y = {}
for number in range(1,int(Num_Part+1)):
numPartFileName = 'N'+str(number)+'_Q'+str(int(FLUX))+'_G'+str(INTERACT)+'_Sz'+str(int(SIZEOFLATTICE))
INNAME2number = 'Res/current_'+numPartFileName
INNAMEnumber = 'Res/eig_'+numPartFileName+'_'
data[number], jmatrix_x[number], jmatrix_y[number] = readin_files(INNAMEnumber, INNAME2number)
#Calculate the full spectrum of the system by matrix multiplying the big basis states with the single particle energy
fullSpectrum = dot(bState, data[1][3])
#INIT. OCCUPTATION DICTIONARY
occup={}
for energy in fullSpectrum:
occup[energy] = []
#INIT. KUBO LIST [t,kubo]
kubo_list = [ ]
#find the range of fermi energy, starting with the smallest energy level.
lowestEnergy = fullSpectrum.min()
print 'The lowest energy is', lowestEnergy
#Group subbands together for the purpose of calculating occupation factors:
subbands = subband_grouper(fullSpectrum, FLUX, SIZEOFLATTICE)
#Define the iteration based on the number of data points wanted
itr = END_TEMP/40.
t = lowestEnergy
#SOLVE FOR BOSE TEMPERATURE###############
Mu_UPBOUND = float(lowestEnergy)-.00001
#So, the problem is finding the value of t that will give the
#proper N == Num_Part at a Mu= MU_UPBOUND
#We know that when MU == MU_UPBOUND, we are at the beginning of
#a bose einstien condesate. The number of particles should still
#be equal to Num_part, as any temp lower than T_BEC, the chemical
#potential will have to be fixed at MU_UPBOUND, so the particle
#number will have to start decresing.
#We can just use the bisection method, as we know that the temperature
#will be very small. Just choose an arbitrarily large number as one
#bound and zero as another
UP = 10.0
BOTTOM = -1.0
t_begin = bisection_t(UP, BOTTOM, n_now, fullSpectrum, Num_Part, Mu_UPBOUND)
#Now, perturb from this, to avoid rounding errors
t = t_begin+float(t_begin)/1000.
#END SOLVE BOSE TEMPERATURE###########
#To speed up the bisection, I can calculate the maximum possible mu, this will give a slightly
#smaller area to work with.
MAX_MU = bisection_Mu(-10E22, Mu_UPBOUND, n_now, fullSpectrum, Num_Part, END_TEMP+1)
#END INITIALIZE##############
#Begin MAIN LOOP OVER TEMPERATURE##################################
while t < END_TEMP:
#First, calculate the mu, fixing the number of bosons present
mu = bisection_Mu(MAX_MU, Mu_UPBOUND, n_now, fullSpectrum, Num_Part, t)
Mu_UPBOUND = mu
# kubo = main_kubo(bState, data, jmatrix_x, jmatrix_y, SIZEOFLATTICE, float(FLUX),mu,t)
# kubo_list.append( (t,kubo) )
occup = occupation(occup, fullSpectrum, t, mu, n_now)
#print kubo,t ,'kubo/temp'
t = t+itr
dirname= 'PYBOSONTemp_'+str(END_TEMP)+'_'+NAMEBASE
os.system('mkdir %s' %(dirname))
os.system('cd ./%s' %dirname)
os.system('pwd')
#Now preform group the occupation into subbands
subband_file = {}
i = 0
for k,band in enumerate(subbands):
band= list(set(band.astype(float)))
subband_file[k] = [ zip(*occup[occup.keys()[1]])[0]
, [0.]*len(occup[occup.keys()[0]]), [0.]*len(occup[occup.keys()[0]])]
for level in band:
subband_file[k] = [subband_file[k][0], subband_file[k][1]+array(occup[level]).T[1], subband_file[k][2]+array(occup[level]).T[2]]
padPrefac = str(i).zfill(len(str(len(fullSpectrum))))
name = 'F'+padPrefac+'_'+str(level)+'eLevel.dat'
savetxt('%s' %dirname+'/'+name, array(occup[level]).squeeze())
if k ==0:
print subband_file[k][1]
i = i+1
padPrefacS = str(k).zfill(len(str(len(subbands))))
savetxt('%s' %dirname+'/'+'S'+padPrefacS+'_'+str(round(band[0],3))+'subband.dat', array(subband_file[k]).T)
print 'subband'
'''
chaff
bloc = [j[3::] for i,j in enumerate(data_trans) if data_trans[i][1] == kx and data_trans[i][2]==ky]
bloc_jx = array([j[2::] for i,j in enumerate(jmatrix_x) if jmatrix_x[i][0] == kx and jmatrix_x[i][1] == ky])
bloc_jy = array([j[2::] for i,j in enumerate(jmatrix_y) if jmatrix_y[i][0] == kx and jmatrix_y[i][1] == ky])
for alpha in block[m]:
for beta in block[m]:
kubo=0.0
if all(alpha==beta):
continue
kubotop=(vdot(alpha[1::], dot(bloc_jx,beta[1::]))*vdot(beta[1::], dot(bloc_jy,alpha[1::]))-vdot(alpha[1::], dot(bloc_jy,beta[1::]))*vdot(beta[1::], dot(bloc_jx,alpha[1::])))
kubobottom=((alpha[0]-beta[0]+complex(0,1E-14))*(alpha[0]-beta[0]-complex(0,1E-14)))
kubo_state[m] =kubo_state[m]+prefac*kubotop/kubobottom/float(SIZEOFLATTICE**2)
if round(prefac*kubotop/kubobottom/float(SIZEOFLATTICE**2), 4) != 0:
contrib = contrib +1
contrib1 = contrib1+1
out_line = (float(kubo),alpha[0], beta[0], contrib1, prefac,kubotop/kubobottom/float(SIZEOFLATTICE**2),t)
print str(out_line)
out_line = str(out_line)+'\n'
contrib_file.write(out_line)
b= b+1
'''
|
1af3dfa853e350728b8ff2fef69cbb30f807d030 | haldous2/coding-practice | /ctci_16.22_langtons_ant.py | 7,403 | 4.59375 | 5 | """
An ant is sitting on an infinite grid of white and black squares.
It initially faces right.
At each step, it does the following:
(1) At a white square,
flip the color of the square,
turn 90 degrees right (clockwise), and move forward one unit.
(2) At a black square,
flip the color of the square,
turn 90 degrees left (counter-clockwise), and move forward one unit.
Question: which square does the ant start on?
Only input is k moves, therefore - programmers selection of
the start square?
Answer: For this program, ant starts on white square
first move will flip a black square.
Queston: Is this board a checker board, or all white board? The instructions
say board with white and black squares - so I'm assuming a checker board
Answer: I've implemented both, commenting out code in get_point_original_color
will switch the boards
For fun, run the program k = 10,500 with an all white board
"""
def print_k_moves(k):
# points[(x, y)] = BL, WH <- current color
points = {}
minmax = [None, None, None, None] # min_x, max_x, min_y, max_y
def ant_moves(ant, k):
# test_get_point_original_color()
for move in range(k):
# Track
track_point(ant.location)
# prev_location = ant.location
# Move
ant.direction, ant.location = ant_move_next(ant.direction, ant.location)
# print "moving from:", prev_location, "to:", ant.location, ant.direction
# print "-----"
print_board()
def ant_move_next(direction, point):
"""
1. Flip current color (save current color for next step)
2. From current color & direction, find new point
WHITE: new point -> 90 degree turn clockwise
BLACK: new point -> 90 degree turn counter-clockwise
"""
point_x = point[0]
point_y = point[1]
new_point = None
new_direction = None
current_color = get_point_current_color(point)
# print "current color", current_color, "for", point
# Flip color
switch_point_current_color(point)
# Direction and Point
if direction == "N":
if current_color == "WH":
# turn clockwise
# from north, go east
point_x += 1
new_direction = "E"
else:
# turn counter-clockwise
# from north, go west
point_x -= 1
new_direction = "W"
elif direction == "E":
if current_color == "WH":
# turn clockwise
# from east, go south
# Note: y + when going down
point_y += 1
new_direction = "S"
else:
# turn counter-clockwise
# from east, go north
# Note: y - when going up
point_y -= 1
new_direction = "N"
elif direction == "S":
if current_color == "WH":
# turn clockwise
# from south, go west
point_x -= 1
new_direction = "W"
else:
# turn counter-clockwise
# from south, go east
point_x += 1
new_direction = "E"
elif direction == "W":
if current_color == "WH":
# turn clockwise
# from west, go north
point_y -= 1
new_direction = "N"
else:
# turn counter-clockwise
# from west, go south
point_y += 1
new_direction = "S"
return (new_direction, (point_x, point_y))
def get_point_original_color(point):
"""
Every point from (0,0) has a predetermined base color
(0,0) is WHite, calculate out from center to determine
the color of the point in question
"""
point_x = point[0]
point_y = point[1]
# All white board
return "WH"
# B&W checker board
# if point_x % 2 == point_y % 2:
# return "WH"
# else:
# return "BL"
def test_get_point_original_color():
print "test get point original color"
print get_point_original_color((0,0)) # WH
print get_point_original_color((0,1)) # BL
print get_point_original_color((0,2)) # WH
print get_point_original_color((0,3)) # BL
print
print get_point_original_color((1,0)) # BL
print get_point_original_color((1,1)) # WH
print get_point_original_color((1,2)) # BL
print get_point_original_color((1,3)) # WH - error BL
print
print get_point_original_color((2,0)) # WH
print get_point_original_color((2,1)) # BL
print get_point_original_color((2,2)) # WH
print get_point_original_color((2,3)) # BL
def get_point_current_color(point):
"""
Returns the current color of a point
Note: point should already be in points hash table
"""
return points[point]
def switch_point_current_color(point):
"""
Switch point color from WHite to BLack and vice versa
Note: point should already be in points hash table
"""
# print "switching color for point", point
if points[point] == "WH":
points[point] = "BL"
else:
points[point] = "WH"
def track_point(point):
"""
Track each visited point color
"""
if point not in points:
points[point] = get_point_original_color(point)
point_x = point[0]
point_y = point[1]
# Min and max x, y for printing
if minmax[0] is None or minmax[0] > point_x: # min_x
minmax[0] = point_x
if minmax[1] is None or minmax[1] < point_x: # max_x
minmax[1] = point_x
if minmax[2] is None or minmax[2] > point_y: # min_y
minmax[2] = point_y
if minmax[3] is None or minmax[3] < point_y: # max_y
minmax[3] = point_y
def print_board():
min_x = minmax[0]
max_x = minmax[1]
min_y = minmax[2]
max_y = minmax[3]
for y in range(min_y, max_y - min_y): # row
for x in range(min_x, max_x - min_x): # col
if x == 0 and y == 0:
print "0",
elif (x, y) in points:
if get_point_current_color((x,y)) == "BL":
print unichr(0x2588),
# print "X",
else:
# print "_",
print " ",
else:
if get_point_original_color((x,y)) == "BL":
print unichr(0x2588),
# print "X",
else:
# print "_",
print " ",
print ""
class Ant(object):
# Note, point (0,0) is a white square
# Note, starting out facing right -> "E"
location = (0,0)
direction = "E"
ant = Ant()
ant_moves(ant, k)
print_k_moves(10500)
|
08e2bc98a31900c697b6d5f537d9dc610b2a5651 | miamirobin/2015Fall_ComputerProgramming | /hw6/hw6.py | 4,750 | 3.65625 | 4 | import math
from visual import *
# Data in units according to the International System of Units
G = 6.67 * math.pow(10,-11)
# Mass of the Earth
ME = 5.974 * math.pow(10,24)
# Mass of the Mars
MM = 6.418 * math.pow(10,23)
# Mass of the Sun
MS = 1.989 * math.pow(10,30)
MH = 2.2 * math.pow(10,14)
# Radius Earth-Moon
REM = 384400000
# Radius Sun-Earth
RSE = 147100000000
# Radius Sun-Mars
RSM = 206600000000
RSH = 87.66E9
# Force Earth-Moon
FEM = G*(ME*MM)/math.pow(REM,2)
# Force Earth-Sun
FES = G*(MS*ME)/math.pow(RSE,2)
# Force Mars-Sun
FMS = G*(MS*MM)/math.pow(RSM,2)
FSH = G*(MS*MH)/math.pow(RSH,2)
# Angular velocity of the Mars with respect to the Sun (rad/s)
wM = math.sqrt(FMS/(MM * RSM))
# Velocity v of the Mars (m/s)
vM = wM*RSM
wH = wM/76
# Velocity v of the Mars (m/s)
#vH = wH*RSH
# Angular velocity of the Earth with respect to the Sun(rad/s)
wE = math.sqrt(FES/(ME * RSE))
# Velocity v of the Earth (m/s)
vE = wE*RSE
# Initial angular position
theta0 = 0
# Position at each time
def positionMars(t):
theta = theta0 + wM * t
return theta
def positionEarth(t):
theta = theta0 + wE * t
return theta
def positionHalley(t):
theta = math.pi + wH * t
return theta
def fromDaysToS(d):
s = d*24*60*60
return s
def fromStoDays(s):
d = s/60/60/24
return d
def fromDaysToh(d):
h = d * 24
return h
days = 365
seconds = fromDaysToS(days)
scene = display(width=10000, height=10000, center=(40, 0, 0), background=(0.5,0.5,0)) # open window
print ('theoretical period for Earth=: '),seconds,' s'
print ('theoretical period for Mars =: '),1.88*seconds,' s'
print ' '
colors = [color.yellow, color.green, color.blue, color.orange]
material=[materials.earth]
v = vector(0.5,0,0)
E = sphere(pos=vector(4.2,0,0),color=color.cyan,material=materials.earth,radius=0.35,make_trail=True)
S = sphere(pos=vector(0,0,0),color=color.orange,radius=1)
M= sphere(pos=vector(5.045,0,0),color=color.red,radius=0.22,make_trail=True)
H= sphere(pos=vector(-1.83,0,0),color=color.green,radius=0.15,make_trail=True)
T = 0
t=0
n=0
thetaTerra1 = 0
dt = 86400
a=54
b=13.77
c=52.17
dthetaE = positionEarth(t+dt)- positionEarth(t)
dthetaM = positionMars(t+dt) - positionMars(t)
dthetaH = positionHalley(t+dt) - positionHalley(t)
l=1.83 * 54.55E3
R=math.hypot(a*math.cos(positionHalley(n))+c,b*math.sin(positionHalley(n)))
vH=l/R
def potential(n):
R=math.hypot(a*math.cos(positionHalley(n))+c,b*math.sin(positionHalley(n)))
return -1*G*MS*MH/(R*47.9E9)
def ek(n):
R=math.hypot(a*math.cos(positionHalley(n))+c,b*math.sin(positionHalley(n)))
vH=l/R
return 0.5*MH*abs(vH)**2
a=54
b=13.77
c=52.17
theta=0
q=0
w=0
z=0
x=0
k=0
while True:
rate(500)
thetaEarth = positionEarth(t+dt)- positionEarth(t)
thetaMars = positionMars(t+dt) - positionMars(t)
thetaHalley = positionHalley(t+dt) - positionHalley(t)
# Rotation only around z axis (0,0,1)
E.pos = rotate(E.pos,angle=thetaEarth,axis=(0,0,1))
M.pos = rotate(M.pos,angle=thetaMars,axis=(0,0,1))
H.pos = vector(a*math.cos(positionHalley(n))+c,b*math.sin(positionHalley(n)),0)
T += dt
t+=dt
n+=dt
if T>=2*math.pi/wE and q==0:
print ("for Earth: T= "),T ,' seconds , T^2/r^3 = ',float(T)**2/RSE**3,' s^2/m^3'
q=1
T=0
if t>=2*math.pi/wM and w==0:
print ("for Mars: T= "),t ,' seconds , T^2/r^3 = ',float(t)**2/RSM**3,' s^2/m^3'
print''
w=1
t=0
if positionHalley(n)>=2*math.pi and z==0:
print 'at aphelion : '
print 'potential energy = ',potential(n),' J'
print 'kinetic energy = ',ek(n),' J'
print 'total energy = ',potential(n)+ek(n),' J'
print 'the connecting line between Halley and the Sun sweeps ',0.5*54.55E3*87.66E9*86400,' m^2'
print ''
z=1
if positionHalley(n)>=1.5*math.pi and x==0:
print 'at half-way point :'
print 'potential energy = ',potential(n),' J'
print 'kinetic energy = ',14.66*ek(n),' J'
print 'total energy = ',potential(n)+14.9*ek(n),' J'
print 'the connecting line between Halley and the Sun sweeps ',0.5*54.55E3*87.66E9*86400,' m^2'
print ''
x=1
if positionHalley(n)>=3*math.pi and k==0:
print 'at perihelion :'
print 'potential energy = ',potential(n),' J'
print 'kinetic energy = ',ek(n),' J'
print 'total energy = ',potential(n)+ek(n),' J'
print 'the connecting line between Halley and the Sun sweeps ',0.5*54.55E3*87.66E9*86400,' m^2'
print ''
k=1
|
21edc0e6fb3cd7f4f8639d7d415483babfc841f0 | ishaansharma/ProblemSolving_Python | /7. Most booked hotel room.py | 1,369 | 3.921875 | 4 | """Given a hotel which has 10 floors [0-9] and each floor has 26 rooms [A-Z].
You are given a sequence of rooms, where + suggests room is booked, - room is freed. You have to find which room is booked maximum number of times.
You may assume that the list describe a correct sequence of bookings in chronological order;
that is, only free rooms can be booked and only booked rooms can be freeed. All rooms are initially free. Note that this does not mean that all rooms have to be free at the end. In case, 2 rooms have been booked the same number of times, return the lexographically smaller room.
You may assume:
N (length of input) is an integer within the range [1, 600]
each element of array A is a string consisting of three characters: "+" or "-"; a digit "0"-"9"; and uppercase English letter "A" - "Z"
the sequence is correct. That is every booked room was previously free and every freed room was previously booked.
Example:
Input: ["+1A", "+3E", "-1A", "+4F", "+1A", "-3E"]
Output: "1A"
Explanation: 1A as it has been booked 2 times."""
import collections
def mostBookedHotelRoom(arr):
myC=collections.Counter(arr)
print(myC)
maxBooking=0
for k,v in myC.items():
if v>maxBooking:
room=k
maxBooking=v
return room[1:]
assert (mostBookedHotelRoom(["+1A", "+3E", "-1A", "+4F", "+1A", "-3E"])=="1A") |
9ac9c0a2eef880a5499130deec9ec07b98db123f | kishorebolt03/learn-python-the-hard-way | /ITVAC/problem_solving/printDIAMOND.py | 362 | 3.5625 | 4 | n=int(input())
a=input()
for i in range(n):
for j in range(1,n+i+1):
if j<n-i:
print(end=' ')
else:
print(a,end="")
print()
k=1
f=1
for i in range(1,n):
for j in range(1,k+i):
print(end=' ')
k+1
while f<=(2*(n-i)-1):
print(a,end='')
f+=1
f=1
print()
|
a84fa834437df9559724e565e85437842c7afb1c | hofernandes/python3-mundo-1 | /ex023.py | 419 | 4 | 4 | # Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados.
# num=str(input('Digite um número: '))
# print(f'Unidade: {num[3]}\nDezena: {num[2]}\nCentena: {num[1]}\nMilhar: {num[0]}')
num2=int(input('Digite um número: '))
print(f'Unidade: {((num2%1000)%100)%10}')
print(f'Dezena: {((num2%1000)%100)//10}')
print(f'Centena: {(num2%1000)//100}')
print(f'Milhar: {num2//1000}')
|
62c1c0466403de99a24551d8ef64c40398133e8b | wchen02/python-leetcode | /Questions/33-SearchInRotatedSortedArray.py | 1,345 | 3.703125 | 4 | from typing import List
# See details here https://wenshengchen.com/2020/01/10/33-search-in-rotated-sorted-array.html
class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums: return -1
lo = 0
hi = len(nums) - 1
while lo <= hi:
mid = lo + (hi-lo) // 2
if nums[mid] == target:
return mid
elif nums[lo] <= nums[mid]:
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else:
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1
## TEST CASES
test = Solution()
answer = test.search([4,5,6,7,0,1,2], 0)
assert answer == 4, answer
assert test.search([4,5,6,7,0,1,2], 3) == -1
assert test.search([4,5,6,7,0,1,2], 4) == 0
assert test.search([4,5,6,7,0,1,2], 5) == 1
assert test.search([4,5,6,7,0,1,2], 6) == 2
assert test.search([4,5,6,7,0,1,2], 7) == 3
assert test.search([4,5,6,7,0,1,2], 0) == 4
assert test.search([4,5,6,7,0,1,2], 1) == 5
assert test.search([4,5,6,7,0,1,2], 2) == 6
assert test.search([1,3,5], 1) == 0
assert test.search([1,3,5], 5) == 2
assert test.search([], 3) == -1
print('All Passed!')
|
cbd904e06bb7b1912a25f541ac0ce210a7983f78 | boknowswiki/mytraning | /lintcode/python/0262_heir_tree.py | 1,254 | 3.796875 | 4 | #!/usr/bin/python -t
# dfs and multiple tree.
class MyTreeNode:
"""
@param val: the node's val
@return: a MyTreeNode object
"""
def __init__(self, val):
# write your code here
self.val = val
self.children = []
self.parent = None
self.is_deleted = False
"""
@param root: the root treenode
@return: get the traverse of the treenode
"""
def traverse(self, root):
# write your code here
ret = []
self.helper(ret, root)
return ret
def helper(self, ret, root):
if root.is_deleted == False:
ret.append(root.val)
for child in root.children:
self.helper(ret, child)
return
"""
@param root: the node where added
@param value: the added node's value
@return: add a node, return the node
"""
def addNode(self, root, value):
# write your code here
newNode = MyTreeNode(value)
newNode.parent = root
root.children.append(newNode)
return newNode
"""
@param root: the deleted node
@return: nothing
"""
def deleteNode(self, root):
# write your code here
root.is_deleted = True
return
|
f6ec1195df42651f56bb184fa71d1aaf911582ec | gyx2110/algorithm-book | /mycode-python/step-2/day06/Problem380_RandomizedSet.py | 1,632 | 3.875 | 4 | # class RandomizedSet(object):
# def __init__(self):
# self.element = set()
# self.map = {}
# self.size = 0
# def insert(self, val):
# if val in self.map:
# return False
# self.map[val] = self.size
# self.element.add(val)
# self.size+=1
# return True
# def remove(self, val):
# if val not in self.map or size==0:
# return False
# self.map.pop(val)
# self.element.remove(val)
# self.size-=1
# return True
# def getRandom(self):
# import random
# return sele.map.keys()[random.randint(0,self.size-1)]
class RandomizedSet(object):
def __init__(self):
self.element = []
self.map = {}
self.size = 0
def insert(self, val):
if self.map.has_key(val):
return False
self.element.append(val)
self.map[val] = self.size
self.size+=1
return True
def remove(self, val):
if not self.map.has_key(val) or self.size==0:
return False
#将最后一个元素交换到val所在的位置
tail = self.element[self.size-1]
self.element[self.map.get(val)] = tail
self.map[tail] = self.map.get(val)
#删除最后一个元素
self.element.pop()
self.map.pop(val)
self.size -=1
return True
def getRandom(self):
import random
return self.element[random.randint(0,self.size-1)]
if __name__ == "__main__":
s = RandomizedSet()
print s.insert(1)
print s.getRandom() |
4b4621e03046e60fbc3e587fc6864a9008e397f4 | omakasekim/python_algorithm | /04_프로그래머스/lev2_전화번호목록.py | 733 | 3.671875 | 4 | # my solution
def solution(phone_book):
if len(phone_book) == 1:
return False
for i, num1 in enumerate(phone_book):
for num2 in phone_book[i+1:]:
if num1 == num2 or num1 == num2[:len(num1)] or num2 == num1[:len(num2)]:
return False
return True
# Status: Accepted
# Algorithm: Brute Force
# Time Complexity: O(n^2)
# 다른 사람의 코드
def solution(phone_book):
phone_book = sorted(phone_book)
for i, j in zip(phone_book, phone_book[1:]):
if j.startswith(i):
return False
return True
# 이게 더 직관적인데 시간이 훨씬 많이 소요된다 왜지?
# sorted는 아마 O(n lg(n))일테니 startswith 함수가 오래걸리나보다. |
1cb040ca20e149a390562fe8e23554ef150d6550 | GloriaWing/wncg | /输出指定范围内的素数.py | 240 | 3.578125 | 4 | min = int(input("min:"))
max = int(input("max:"))
sushu = []
for i in range(min,max+1):
fg = 0
for j in range(2,i):
if (i % j) == 0:
fg = 1
break
if (fg == 0):
sushu.append(i)
print(sushu)
|
8546bbfe99f5ca39bc0a3879c2773e62ed6e4ef3 | taiannlai/Pythonlearn | /CH4/CH4_L6.py | 117 | 3.96875 | 4 | x = 3.305
y = input("請輸入房屋坪數:")
z = float(x) * float(y)
print("房屋總平方公尺為:%2.1f" % z) |
bffbdba4ee075bd10d61c3d4427882faf8cabf62 | wooseong-dev/python | /algorithm/module/reverse.py | 600 | 3.71875 | 4 | #mutable(변환가능자료형) 원소를 역순 정렬
from typing import Any, MutableSequence
def reverse_arr(a: MutableSequence) -> None:
#mutable 시퀀스 a의 원소 역순 정렬
n = len(a)
for i in range(n//2):
a[i],a[n-i-1]=a[n-i-1],a[i]
if __name__ == '__main__':
nx = int(input('원소의 개수를 입력하시오 >> '))
x = [None]*nx #원소수 nx개의 list 생성
for i in range(nx):
x[i] = int(input(f'x[{i}]의 값을 입력하시오 >> '))
reverse_arr(x)
for i in range(nx):
print(f'x[{i}] = {x[i]}') |
307c596ae9f62366859eca2ff690937423cf4610 | tburette/leetcode | /problems/11ContainerWithMostWater.py | 4,253 | 3.640625 | 4 | import unittest
from typing import List, Dict, Tuple
# Bruteforce-ish solution : start at the leftmost and rightmost edges,
# check all the potentials solutions with smaller width
# (left more to the right and/or right more to the left)
# skip a 'smaller' solution if height of the new left/right is not higher.
# Could optimize further by determining that it's worth reducing the width by x
# only if the height gain is at least y?
class Solution:
def maxArea(self, height: List[int]) -> int:
# Contains the biggest possible volume within a left-right range
# (aka a candidate).
# could be the volume of a sub-candidate :
# left and/or right closer to the middle.
# NOT simply the volume of left-right
# avoids computing multiple time the same things
# key : tuple of the left and right index
# value : biggest possible volume
seen: Dict[(int, int), int] = dict()
def compute_volume(left: int, right: int) -> int:
return min(height[left], height[right]) * (right - left)
def indexedMaxArea(left: int, right: int) \
-> Tuple[Tuple[int, int], int]:
""" Returns the candidate with the biggest volume within left-right.
:param left: left limit (an index of height)
:param right: right limit (an index of height)
:return: best candidate + its volume
"""
candidate_range = (height[left], height[right])
if candidate_range in seen:
# already evaluated this candidate, skip.
return (candidate_range, seen[candidate_range])
candidate_volume = compute_volume(left, right)
# search for next left candidate (if any)
next_candidate_left = next(
(candidate_left
for candidate_left in range(left + 1, right)
if height[candidate_left] > height[left]),
None)
if next_candidate_left:
(best_candidate_left, best_left_volume) = \
indexedMaxArea(next_candidate_left, right)
if best_left_volume > candidate_volume:
candidate_range = best_candidate_left
candidate_volume = best_left_volume
# search for next right candidate (if any)
next_candidate_right = next(
(candidate_right
for candidate_right in range(right - 1, left, -1)
if height[candidate_right] > height[right]),
None)
if next_candidate_right:
(best_candidate_right, best_right_volume) = \
indexedMaxArea(left, next_candidate_right)
if best_right_volume > candidate_volume:
candidate_range = best_candidate_right
candidate_volume = best_right_volume
seen[left, right] = candidate_volume
return (candidate_range, candidate_volume)
return indexedMaxArea(0, len(height) - 1)[1]
# Much simpler solution (looked at the discussion forum)
class Solution:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
water = -1
while left < right:
water = max(water, min(height[left], height[right]) * (right - left))
if height[left] < height[right]:
# can skip all the solutions left and right-1, right-2, ...
left += 1
else:
right -= 1
return water
class TestSolution(unittest.TestCase):
def setUp(self):
self.s = Solution()
def assertMaxArea(self, expected: int, height: List[int]):
self.assertEqual(expected, self.s.maxArea(height))
def test_examples(self):
self.assertMaxArea(49, [1, 8, 6, 2, 5, 4, 8, 3, 7])
self.assertMaxArea(1, [1, 1])
self.assertMaxArea(16, [4, 3, 2, 1, 4])
self.assertMaxArea(2, [1, 2, 1])
#@unittest.skip("potential slow execution")
def test_extremes(self):
self.assertMaxArea(0, [0, 0])
self.assertMaxArea(10 ** 4, [10 ** 4, 10 ** 4])
self.assertMaxArea(10 ** 5 - 1, [1] * 10 ** 5)
|
90eabf22a8feae6871b0f318d6b896b78446d90f | CodeAlpha7/WebDevCode | /Google-Work-Sample/python/src/video_player.py | 8,580 | 3.875 | 4 | """A video player class."""
from .video_library import VideoLibrary
import random
playlist_name_list = []
class VideoPlayer:
"""A class used to represent a Video Player."""
def __init__(self):
self._video_library = VideoLibrary()
self.prev = ""
self.flag = 0
def number_of_videos(self):
num_videos = len(self._video_library.get_all_videos())
print(f"{num_videos} videos in the library")
def show_all_videos(self):
print("Here's a list of all available videos:")
all_videos = self._video_library.get_all_videos()
sort_video_list = []
for i in all_videos:
sort_video_list.append([i.title, i.video_id, i.tags])
sort_video_list.sort()
for i in range(len(sort_video_list)):
print(sort_video_list[i][0] + " (" + sort_video_list[i][1] + ") [", end="")
for index in range(len(sort_video_list[i][2])):
if index == len(sort_video_list[i][2]) - 1:
print(sort_video_list[i][2][index], end="")
else:
print(sort_video_list[i][2][index], end=" ")
print("]")
def play_video(self, video_id):
object = self._video_library.get_video(video_id)
all_videos = self._video_library.get_all_videos()
if object == None:
print("Cannot play video: Video does not exist")
else:
if self.prev == "":
print("Playing video: " + object.title)
self.prev = object.title
self.flag = 0
else:
# if self.flag == 0:
print("Stopping video: " + self.prev)
print("Playing video: " + object.title)
self.prev = object.title
self.flag = 0
# else:
# if self.flag == 1:
# if self.prev == object.title:
# print("Playing video: " + object.title)
# self.prev = object.title
# self.flag = 0
# else:
# print("Stopping video: " + self.prev)
# print("Playing video: " + object.title)
# self.prev = object.title
# self.flag = 0
def stop_video(self):
if self.prev == "":
print("Cannot stop video: No video is currently playing")
else:
print("Stopping video: " + self.prev)
self.prev = ""
self.flag = 0
def play_random_video(self):
all_videos = self._video_library.get_all_videos()
random_video_list = []
for i in all_videos:
random_video_list.append(i.title)
selected = random.choice(random_video_list)
if self.prev == "":
print("Playing video: " + selected)
self.prev = selected
self.flag = 0
else:
print("Stopping video: "+ self.prev)
print("Playing video: " + selected)
self.prev = selected
self.flag = 0
def pause_video(self):
if self.prev == "":
print("Cannot pause video: No video is currently playing")
else:
if self.flag == 0:
print("Pausing video: " + self.prev)
self.flag = 1
else:
if self.flag == 1:
print("Video already paused: " + self.prev)
def continue_video(self):
if self.flag == 1:
print("Continuing video: " + self.prev)
self.flag = 0
else:
if self.prev == "":
print("Cannot continue video: No video is currently playing")
else:
print("Cannot continue video: Video is not paused")
def show_playing(self):
all_videos = self._video_library.get_all_videos()
sort_video_list = []
for i in all_videos:
sort_video_list.append([i.title, i.video_id, i.tags])
if self.prev == "":
print("No video is currently playing")
else:
if self.flag == 0:
for i in all_videos:
if i.title == self.prev:
print("Currently playing: " + i.title + " (" + i.video_id + ") [", end="")
for index in range(len(i.tags)):
if index == len(i.tags) - 1:
print(i.tags[index], end="")
else:
print(i.tags[index], end=" ")
print("]")
else:
for i in all_videos:
if i.title == self.prev:
print("Currently playing: " + i.title + " (" + i.video_id + ") [", end="")
for index in range(len(i.tags)):
if index == len(i.tags) - 1:
print(i.tags[index], end="")
else:
print(i.tags[index], end=" ")
print("]", end="")
print(" - PAUSED")
def create_playlist(self, playlist_name):
global playlist_name_list
for i in playlist_name_list:
if i == playlist_name:
print("Cannot create playlist: A playlist with the same name already exits")
playlist_name_list.append(playlist_name)
print("Successfully created new playlist: " + playlist_name)
def add_to_playlist(self, playlist_name, video_id):
"""Adds a video to a playlist with a given name.
Args:
playlist_name: The playlist name.
video_id: The video_id to be added.
"""
print("add_to_playlist needs implementation")
def show_all_playlists(self):
"""Display all playlists."""
print("show_all_playlists needs implementation")
def show_playlist(self, playlist_name):
"""Display all videos in a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
print("show_playlist needs implementation")
def remove_from_playlist(self, playlist_name, video_id):
"""Removes a video to a playlist with a given name.
Args:
playlist_name: The playlist name.
video_id: The video_id to be removed.
"""
print("remove_from_playlist needs implementation")
def clear_playlist(self, playlist_name):
"""Removes all videos from a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
print("clears_playlist needs implementation")
def delete_playlist(self, playlist_name):
"""Deletes a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
print("deletes_playlist needs implementation")
def search_videos(self, search_term):
"""Display all the videos whose titles contain the search_term.
Args:
search_term: The query to be used in search.
"""
print("search_videos needs implementation")
def search_videos_tag(self, video_tag):
"""Display all videos whose tags contains the provided tag.
Args:
video_tag: The video tag to be used in search.
"""
print("search_videos_tag needs implementation")
def flag_video(self, video_id, flag_reason=""):
"""Mark a video as self.flagged.
Args:
video_id: The video_id to be self.flagged.
self.flag_reason: Reason for self.flagging the video.
"""
print("self.flag_video needs implementation")
def allow_video(self, video_id):
"""Removes a self.flag from a video.
Args:
video_id: The video_id to be allowed again.
"""
print("allow_video needs implementation")
|
48c3b2ec26afc16de8a847faa1e4da33d6098383 | jacobwin/MH8811-G1901740C | /02/02-2.py | 121 | 4.0625 | 4 | C = float (input('Enter the temperature in degree celsius: '))
F = C*1.8+32
print ('The temperature in Fahrenheit is', F) |
df991bac479dacac6d2d16020255bcf4c7a0b0d7 | ivenpoker/Python-Projects | /Projects/Online Workouts/w3resource/Collections/program-2.py | 1,357 | 4.15625 | 4 | #!/usr/bin/env python3
############################################################################################
# #
# Program purpose: Finds the most common elements and their counts of a specified #
# text. #
# Program Author : Happi Yvan <ivensteinpoker@gmail.com> #
# Creation Date : December 27, 2019 #
# #
############################################################################################
from collections import Counter
def obtain_user_input(input_mess: str) -> str:
user_data, valid = '', False
while not valid:
try:
user_data = input(input_mess)
if len(user_data) == 0:
raise ValueError('Oops, data needed!')
valid = True
except ValueError as ve:
print(f'[ERROR]: {ve}')
return user_data
if __name__ == "__main__":
new_data = obtain_user_input(input_mess='Enter some text: ')
top_common = Counter(new_data).most_common(3)
print(f'Most common three characters of said text: {top_common}')
|
0ff010ce691aedb4c6f79d3d7c59ba6628ac57a5 | scottmaccarone2/Udacity-Intro-Programming-Projects | /order_breakfast.py | 16,048 | 4.40625 | 4 | # The first program to write is a breakfast bot that allows us to place a breakfast order (based on only two items). Before launching into code, there are some crucial pieces of the program we need to build:
# 1. Get input and use it to determine what happens next
# 2. Handle bad input without crashing
# 3. Be flexible with the input the user can enter
# 4. Print messages to the console, whith a short pause after each one
# 5. Allow the player to order again if they like
# import time
# def breakfast_bot():
# order = (input("Please place your order. Would you like waffles or pancakes?\n"))
# order = order.lower()
# if order == 'waffles':
# print('Waffles it is!')
# elif order == 'pancakes':
# print('Pancakes it is!')
# else:
# print("Sorry, I don't understand")
# breakfast_bot()
#---------------------------------------------------------------------------
# There needs to be a while loop so that if the user enters an invalid input, the program will not crash and will re-ask the question. There are two ways to do this (NOTE: I DID NOT COME UP WITH THESE - THESE WERE GIVE BY UDACITY INSTRUCTORS. I SHOULD HAVE BEEN ABLE TO COME UP WITH THESE SOLUTIONS ON MY OWN BUT I DID NOT):
# Method 1:
# def breakfast_bot1():
# while True:
# order = (input("Please place your order. Would you like waffles or pancakes?\n")).lower()
# if order == 'waffles':
# print('Waffles it is!')
# break
# elif order == 'pancakes':
# print('Pancakes it is!')
# break
# else:
# print("Sorry, that's not on our menu.")
#
# breakfast_bot1()
# Method 2:
# def breakfast_bot2():
# order = ""
# while order != 'waffles' and order != 'pancakes':
# order = (input("Please place your order. Would you like waffles or pancakes?\n")).lower()
# if order == 'waffles':
# print('Waffles it is!')
# elif order == 'pancakes':
# print('Pancakes it is!')
# else:
# print("Sorry, I don't understand")
#
# breakfast_bot2()
#---------------------------------------------------------------------------
# Now modify the code so we can be flexible with a user input of something like:
# "I'd like waffles, please!"
# We need to use the `in` operator to check whether or not the string contains the 'waffles' or 'pancakes' keywords.
# def breakfast_bot1():
# while True:
# order = (input("Please place your order. Would you like waffles or pancakes?\n")).lower()
# if 'waffles' in order:
# print('Waffles it is!')
# break
# elif 'pancakes' in order:
# print('Pancakes it is!')
# break
# else:
# print("Sorry, that's not on our menu.")
#
# breakfast_bot1()
#---------------------------------------------------------------------------
# Now we will add messages to welcome the guest - but only the FIRST time the guest starts the bot(not with every order/re-order):
# NOTE: With SO many `time.sleep(2)` calls, we may want to rethink the structure of the program!
# def breakfast_bot1():
# greeting = ["Hello, I am Bob, the Breakfast Bot.",
# "Today we have two breakfasts available.",
# "The first is waffles with strawberries and whipped cream.",
# "The second is sweet potato pancakes with butter and maple syrup."]
# for item in greeting:
# print(item)
# time.sleep(2)
#
# while True:
# order = (input("Please place your order. Would you like waffles or pancakes?\n")).lower()
# if 'waffles' in order:
# print('Waffles it is!')
# time.sleep(2)
# break
# elif 'pancakes' in order:
# print('Pancakes it is!')
# time.sleep(2)
# break
# else:
# print("Sorry, that's not on our menu.")
# time.sleep(2)
#
# time.sleep(2)
# print("Your order will be ready shortly.")
#
# breakfast_bot1()
#---------------------------------------------------------------------------
# We now need to allow the user to place additional orders. First, we must prompt the user and ask if they would like to order again. Depending on their response (yes or no), we write code for either scenario. If they say 'yes', we write code ask them to place the order; if they say 'no', the program should print a goodbye message and exit.
# Maybe use a nest while loop?
# def breakfast_bot1():
# greeting = ["Hello, I am Bob, the Breakfast Bot.",
# "Today we have two breakfasts available.",
# "The first is waffles with strawberries and whipped cream.",
# "The second is sweet potato pancakes with butter and maple syrup."]
# for item in greeting:
# print(item)
# time.sleep(2)
#
# order_again = "yes"
# while "yes" in order_again:
# while True:
# order = (input("Please place your order. Would you like waffles or pancakes?\n")).lower()
# if 'waffles' in order:
# print('Waffles it is!')
# time.sleep(2)
# break
# elif 'pancakes' in order:
# print('Pancakes it is!')
# time.sleep(2)
# break
# else:
# print("Sorry, that's not on our menu.")
# time.sleep(2)
#
# time.sleep(2)
# print("Your order will be ready shortly.")
# time.sleep(2)
#
# while True:
# order_again = (input("Would you like to place another order? Please say 'yes' or 'no'.\n")).lower()
# time.sleep(2)
# if 'yes' in order_again:
# print("Very good, I'm happy to take another order.")
# time.sleep(2)
# break
# elif 'no' in order_again:
# print("OK, goodbye!")
# break
# else:
# print("Sorry, I don't understand.")
#
# breakfast_bot1()
#---------------------------------------------------------------------------
# Write a print_pause() function that prints the given string/statement to the user, and then pauses for two seconds. Use this function to clean up the code above:
# def print_pause(s):
# print(s)
# time.sleep(2)
#
#
# def breakfast_bot1():
# greeting = ["Hello, I am Bob, the Breakfast Bot.",
# "Today we have two breakfasts available.",
# "The first is waffles with strawberries and whipped cream.",
# "The second is sweet potato pancakes with butter and maple syrup."]
# for item in greeting:
# print_puase(item)
#
# order_again = "yes"
# while "yes" in order_again:
# while True:
# order = (input("Please place your order. Would you like waffles or pancakes?\n")).lower()
# if 'waffles' in order:
# print_pause('Waffles it is!')
# break
# elif 'pancakes' in order:
# print_pause('Pancakes it is!')
# break
# else:
# print_pause("Sorry, that's not on our menu.")
#
# print_pause("Your order will be ready shortly.")
#
# while True:
# order_again = (input("Would you like to place another order? Please say 'yes' or 'no'.\n")).lower()
# time.sleep(2)
# if 'yes' in order_again:
# print_pause("Very good, I'm happy to take another order.")
# break
# elif 'no' in order_again:
# print_pause("OK, goodbye!")
# break
# else:
# print_pause("Sorry, I don't understand.")
#
# breakfast_bot1()
#--------------------------------------------------------------------------
# Write a `valid_input()` function to simplify the code above:
# import time
#
# def print_pause(s):
# print(s)
# time.sleep(2)
# The goal of this function is to build on the `input()` function. Yes, we still want input from the user, but then we want to check if that input contains particular keywords. In the first case, we need to see if the users input contain "waffles" or "pancakes"; and in the second case, we want to check if the users input contains "yes" or "no".
# def valid_input(prompt, option1, option2):
# while True:
# user_response = input(prompt).lower()
# if option1 in user_response:
# return user_response
# elif option2 in user_response:
# return user_response
# else:
# print_pause("Sorry, I don't understand.")
#
# def breakfast_bot1():
# greeting = ["Hello, I am Bob, the Breakfast Bot.",
# "Today we have two breakfasts available.",
# "The first is waffles with strawberries and whipped cream.",
# "The second is sweet potato pancakes with butter and maple syrup."]
# for item in greeting:
# print_pause(item)
#
# order_again = "yes"
# while "yes" in order_again:
# order = (valid_input("Please place your order. Would you like waffles or pancakes?\n", "waffles", "pancakes"))
# if 'waffles' in order:
# print_pause('Waffles it is!')
# elif 'pancakes' in order:
# print_pause('Pancakes it is!')
#
# print_pause("Your order will be ready shortly.")
#
# order_again = (valid_input("Would you like to place another order? Please say 'yes' or 'no'.\n", "yes", "no"))
# if 'yes' in order_again:
# print_pause("Very good, I'm happy to take another order.")
# elif 'no' in order_again:
# print_pause("OK, goodbye!")
#
# breakfast_bot1()
#--------------------------------------------------------------------------
# Now let's modify the `valid_input()` function so it can accept any number of options, not just two. That way, we can begin to build our menu to include bacon, eggs, crepes, etc. To do this, use a list that contains all the possible options. Then use a `for` loop to iterate over each item/option, and check that the option is in the user's input.
# import time
#
# def print_pause(s):
# print(s)
# time.sleep(2)
#
# def valid_input(prompt, option_list):
# while True:
# user_response = input(prompt).lower()
# for item in option_list:
# if item in user_response:
# return user_response
# print_pause("Sorry, I don't understand.")
#
# def breakfast_bot1():
# greeting = ["Hello, I am Bob, the Breakfast Bot.",
# "Today we have three breakfasts available.",
# "The first is waffles with strawberries and whipped cream.",
# "The second is sweet potato pancakes with butter and maple syrup.",
# "The third is nutella crepes with fresh strawberries."]
# for item in greeting:
# print_pause(item)
#
# order_again = "yes"
# while "yes" in order_again:
# order = (valid_input("Please place your order. Would you like waffles, pancakes, or crepes?\n", ["waffles", "pancakes", "crepes"]))
# if 'waffles' in order:
# print_pause('Waffles it is!')
# elif 'pancakes' in order:
# print_pause('Pancakes it is!')
# elif 'crepes' in order:
# print_pause('Crepes it is!')
#
# print_pause("Your order will be ready shortly.")
#
# order_again = (valid_input("Would you like to place another order? Please say 'yes' or 'no'.\n", ["yes", "no"]))
# if 'yes' in order_again:
# print_pause("Very good, I'm happy to take another order.")
# elif 'no' in order_again:
# print_pause("OK, goodbye!")
#
# breakfast_bot1()
#--------------------------------------------------------------------------
# Now, let's use functions even more to define `intro()` and `get_order()` functions to more cleanly wrap our program up. Both functions do NOT take in variables/parameters, and both functions return nothing!
# import time
#
#
# def print_pause(s):
# print(s)
# time.sleep(2)
#
#
# def valid_input(prompt, option_list):
# while True:
# user_response = input(prompt).lower()
# for item in option_list:
# if item in user_response:
# return user_response
# print_pause("Sorry, I don't understand.")
#
#
# def intro():
# greeting = ["Hello, I am Bob, the Breakfast Bot.",
# "Today we have three breakfasts available.",
# "The first is waffles with strawberries and whipped cream.",
# "The second is sweet potato pancakes with butter and maple syrup.",
# "The third is nutella crepes with fresh strawberries."]
# for item in greeting:
# print_pause(item)
#
#
# def get_order():
# response = (valid_input("Please place your order. Would you like waffles, pancakes, or crepes?\n", ["waffles", "pancakes", "crepes"]))
# if 'waffles' in response:
# print_pause('Waffles it is!')
# elif 'pancakes' in response:
# print_pause('Pancakes it is!')
# elif 'crepes' in response:
# print_pause('Crepes it is!')
# print_pause("Your order will be ready shortly.")
#
#
#
# def order_again():
# response = (valid_input("Would you like to place another order? Please say 'yes' or 'no'.\n", ["yes", "no"]))
# if 'yes' in response:
# print_pause("Very good, I'm happy to take another order.")
# return response
# elif 'no' in response:
# print_pause("OK, goodbye!")
# return response
#
#
# def breakfast_bot1():
# intro()
# another_order = "yes"
# while "yes" in another_order:
# get_order()
# another_order = order_again()
#
#
# breakfast_bot1()
#--------------------------------------------------------------------------
# Can I simplify the remaining `breakfast_bot1()` code even further to remove the `while` loop, and call the `order_again()` function only when the user wishes to place another order? We need to include the `order_again()` function in the `get_order()` function AND we need to include the `get_order()` function within the `order_again()` function! This solution actually seems a little confusing to me, but I suppose it works in Python....
import time
def print_pause(s):
print(s)
time.sleep(2)
def valid_input(prompt, option_list):
while True:
user_response = input(prompt).lower()
for item in option_list:
if item in user_response:
return user_response
print_pause("Sorry, I don't understand.")
def intro():
greeting = ["Hello, I am Bob, the Breakfast Bot.",
"Today we have three breakfasts available.",
"The first is waffles with strawberries and whipped cream.",
"The second is sweet potato pancakes with butter and maple syrup.",
"The third is nutella crepes with fresh strawberries."]
for item in greeting:
print_pause(item)
def get_order():
response = (valid_input("Please place your order. Would you like waffles, pancakes, or crepes?\n", ["waffles", "pancakes", "crepes"]))
if 'waffles' in response:
print_pause('Waffles it is!')
elif 'pancakes' in response:
print_pause('Pancakes it is!')
elif 'crepes' in response:
print_pause('Crepes it is!')
print_pause("Your order will be ready shortly.")
order_again()
def order_again():
response = (valid_input("Would you like to place another order? Please say 'yes' or 'no'.\n", ["yes", "no"]))
if 'yes' in response:
print_pause("Very good, I'm happy to take another order.")
get_order()
elif 'no' in response:
print_pause("OK, goodbye!")
def breakfast_bot():
intro()
get_order()
breakfast_bot()
|
60bf5cb1dbba62c4f151da25daac9e8826aa5cc2 | AurelioLMF/PersonalProject | /ex059.py | 1,274 | 4.21875 | 4 | '''Crie um programa que leia dois valores e mostre um menu como apresentado abaixo. Seu programa deverá realizar a
operação solicitada em cada caso:
[ 1 ] somar
[ 2 ] multiplicador
[ 3 ] maior
[ 4 ] novos números
[ 5 ] sair do programa'''
from time import sleep
n1 = int(input('Primeiro valor: '))
n2 = int(input('Segundo valor: '))
escolha = 0
while escolha != 5:
escolha = int(input('''O que deseja fazer?
[ 1 ] somar
[ 2 ] multiplicar
[ 3 ] maior
[ 4 ] novos números
[ 5 ] sair do programa
Sua escolha: '''))
if escolha == 1:
soma = n1+n2
print(f'A soma entre os valores {n1} e {n2} = {soma}')
elif escolha == 2:
mult = n1*n2
print(f'A multiplicação entre os valores {n1} e {n2} = {mult}')
elif escolha == 3:
if n1 < n2:
maior = n2
else:
maior = n1
print(f'Entre {n1} e {n2}, o maior é {maior}')
elif escolha == 4:
n1 = int(input('Informe os números novamente. \nPrimeiro valor: '))
n2 = int(input('Segundo valor: '))
elif escolha == 5:
print('Finalizando...')
sleep(1)
else:
print('Opção inválida. Tente novamente.')
print('+=' * 10)
print(f'Fim do programa!') |
f410976a9a5dbe250c22d29422c10be8e3b9681c | GosiaZalecka/kalendarz | /kalendarz2.py | 1,603 | 3.953125 | 4 | import calendar
#podanie roku
print("Czy to rok przestępny?")
year = input("podaj rok: ")
#sprawdzenie czy to rok przestępny
czy_przestępny = calendar.isleap(int(year))
if czy_przestępny == True:
print("Tak, rok " + year + " to rok przestępny")
else:
print("Nie, rok " + year + " to nie rok przestępny")
print("")
#podanie daty do sprawdzenia jaki to dzień tygodnia
print("Znasz datę i zastanawiasz się jaki dzień tygodnia to był?")
data_rok = int(input("wpisz rok: "))
data_miesiąc = int(input("wpisz miesiąc: "))
while data_miesiąc < 1 or data_miesiąc > 12:
print("Przypominam, że rok ma 12 miesięcy")
data_miesiąc = int(input("wpisz miesiąc: "))
krótkie_miesiące = (2, 4, 6, 9, 11)
data_dzień = int(input("wpisz dzień: "))
while data_dzień < 1 or data_dzień > 31:
print("Miesiąc ma do 31 dni")
data_dzień = int(input("wpisz dzień: "))
while data_miesiąc in krótkie_miesiące and data_dzień > 30:
print("miesiąc " + str(data_miesiąc) + " ma mniej dni")
data_dzień = int(input("wpisz dzień: "))
print("Data to: " + str(data_rok) + "." + str(data_miesiąc) + "." + str(data_dzień))
dzień_tygodnia = calendar.weekday(data_rok, data_miesiąc, data_dzień)
#prezentacja wyniku w postaci dnia tygodnia
if dzień_tygodnia == 0:
print("Poniedziałek")
if dzień_tygodnia == 1:
print("Wtorek")
if dzień_tygodnia == 2:
print("Środa")
if dzień_tygodnia == 3:
print("Czwartek")
if dzień_tygodnia == 4:
print("Piątek")
if dzień_tygodnia == 5:
print("Sobota")
if dzień_tygodnia == 6:
print("Niedziela") |
1d011bf2e03deb98ac9f58f49121a20f47ae374e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2845/61048/315118.py | 308 | 3.640625 | 4 | def arr22():
n=int(input())
set=[]
for i in range(n):
set.append([int(x) for x in input().split(' ')])
set.sort(key=lambda x:x[0])
tmp=set.copy()
tmp.sort(key=lambda x:x[1])
if(tmp==set):
print("Poor Alex")
else:
print("Happy Alex")
return
arr22() |
1b31aaa5c52a5a76374c178a642c804ec09d27c1 | ClaudioCarvalhoo/you-can-accomplish-anything-with-just-enough-determination-and-a-little-bit-of-luck | /problems/LC1457.py | 926 | 3.765625 | 4 | # O(n)
# n = numberOfNodes(root)
# 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 pseudoPalindromicPaths(self, root: TreeNode) -> int:
return self.explore(root, {}, 0)
def explore(self, node, soFar, over):
if not node:
return 0
if node.val in soFar:
soFar[node.val] += 1
else:
soFar[node.val] = 1
if soFar[node.val] % 2 == 0:
over -= 1
else:
over += 1
if not node.left and not node.right:
if over > 1:
return 0
else:
return 1
temp = soFar.copy()
left = self.explore(node.left, soFar, over)
right = self.explore(node.right, temp, over)
return left + right |
1d3b6431db645dd16742f3f88d0ccff41c02564c | MAPLE-Robot-Subgoaling/IPT | /data/HW4/hw4_157.py | 441 | 4.125 | 4 | def main():
heightList = []
height = int(input("Please enter the starting height of the hailstone: "))
while height !=1:
heightList.append(height)
if height/2 == float:
ans= height * 3 + 1
print("Hail is currently at heaight", ans)
if height/2 == int:
ans1 = height/2
print("Hail is currently at height", ans1)
print("Hail stopped at height 1")
main()
|
fa9975296c033d22eb76f35a9e560fd5890af6ed | abahmer/music-classification | /spotify.py | 2,466 | 3.546875 | 4 | import requests
import base64
class Connection:
"""
Class' object instantiates a connection with spotify. When the connection is alive, queries are made with the query_get
method.
"""
def __init__(self, client_id=None, secret=None):
if client_id is None:
client_id = open("./ignore/id.txt").read()
if secret is None:
secret = open("./ignore/secret.txt").read()
# First header and parameters needed to require an access token.
param = {"grant_type": "client_credentials"}
header = {"Authorization": "Basic {}".format(
base64.b64encode("{}:{}".format(client_id, secret).encode("ascii")).decode("ascii")),
'Content-Type': 'application/x-www-form-urlencoded'}
self.token = requests.post("https://accounts.spotify.com/api/token", param, headers=header).json()[
"access_token"]
self.header = {"Authorization": "Bearer {}".format(self.token)}
self.base_url = "https://api.spotify.com"
def query_get(self, query, params=None):
"""
:param query: (str) URL coming after example.com
:param params: (dict)
:return: (json)
"""
return requests.get(self.base_url + query, params, headers=self.header).json()
def query_track(self, track):
"""
Query a track name.
:param track: (str)
:return: (dict)
"""
return self.query_get("/v1/search/",
{'q': "{}".format(track.replace(' ', '+')), "type": ("track", "artist")})
def track_preview(self, track, index=0):
"""
Get a preview url of a track query.
:param track: (str)
:return: (str)
"""
return self.query_track(track)["tracks"]["items"][index]["preview_url"]
def artist_track_preview(self, artist, track):
"""
Get a preview url of a track query
:param artist: (str)
:param track: (str)
:return: (str)
"""
artist = artist.lower()
q = self.query_track("{} - {}".format(artist, track))["tracks"]["items"]
for d in q:
if d["artists"][0]["name"].lower() == artist and d["preview_url"]:
return d["preview_url"]
# try again for partial match
for d in q:
if artist in d["artists"][0]["name"].lower() and d["preview_url"]:
return d["preview_url"]
|
46e404b392aacaaa835e568279e5dcb9c00c50ea | YongKhyeShern/DPL5211Tri2110 | /Lab 2.4.py | 644 | 3.640625 | 4 | #Student ID: 1201201010
#Student Name: Yong Khye Shern
BC=1.5 #constant value, the value doesn't change, name in Capital letters
GC=5.6
print("Invoice for Fruits Purchase")
print("---------------------------------")
bananas=int (input("\nEnter the quantity (comb) of bananas bought: "))
grapes=int (input("Enter the amount (kg) of grapes bought: "))
tbanana=bananas*BC
tgrapes=grapes*GC
total=tbanana+tgrapes
print("\nItem\t\tQty\tPrice\tTotal")
print("Banana (combs)\t",bananas,"\tRM1.50\tRM {:.2f}".format(tbanana))
print("Grapes (kg)\t",grapes,"\tRM5.60\tRM {:.2f}".format(tgrapes))
print("\nTotal: RM {:.2f}".format(total))
|
edbf1ee31fc6a69f9ae6b6d7d97f342d3671b64c | MHM18/hm18 | /hmpro/zhangxiyang/list/list5.py | 247 | 3.546875 | 4 | a = [66.25,333,333,1,1234.5]
print(a.count(333),a.count(66.25),a.count('x'))
a.insert(2,-1)#插入
a.append(333)
print(a)
a.index(333)#索引
a.remove(333)#删掉第一个333
print(a)
a.reverse#倒序排
print(a)
a.sort()#从小到大排
print(a)
|
c4d734b5a307ffbb1ec79bea3780ae93a61d3ea4 | ADWright18/Learning | /LeetCode/Hash Table/Problems/groupAnagrams.py | 957 | 4.15625 | 4 | """
Problem Description: Given an array of strings, group anagrams together
Example:
Input:
["eat", "tea", "tan", "ate", "nat", "bat"]
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Solution:
1. Initialize a dictionary to store {sorted_char : [list of anagrams]} pairs
2. Iterate through the list of words
- If sorted(word) is already in the dictionary, d[sorted_char].append(word)
- Otherwise, add {sorted(word) : word} to the dictionary
3. Return d.values()
"""
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
d = {} # Store {sorted(word) : [list of anagrams]} pairs
for word in strs:
sorted_word = ''.join(sorted(word))
if (sorted_word in d):
d[sorted_word].append(word)
else:
d[sorted_word] = [word]
v = list(d.values())
return v
|
931e20a0ed557a8b904b4ae0580a58e6aaf0c969 | bgoonz/UsefulResourceRepo2.0 | /GIT-USERS/amitness/leetcode/387-first-unique-char.py | 335 | 3.609375 | 4 | # https://leetcode.com/problems/first-unique-character-in-a-string
def firstUniqChar(s):
"""
:type s: str
:rtype: int
"""
h = {}
for i, c in enumerate(s):
if c in h:
h[c] = -1
else:
h[c] = i
for c in s:
if h[c] != -1:
return h[c]
return -1
|
ae218ec695c553a345c567313238246d1a4db5c5 | BrunaNayara/ppca | /eda/lista1/13.py | 226 | 4.0625 | 4 | n = int(input())
c = int(input())
while(c != n):
if c < n:
print("O número correto é maior.")
elif c > n:
print("O número correto é menor.")
c = int(input())
print("Parabéns! Você acertou.")
|
d80f6c7bfdf80c7cbbd5bf3e6651250afc2bdd6c | shichao-an/ctci | /chapter5/question5.5.py | 660 | 3.84375 | 4 | from __future__ import print_function
def num_bit_swap(a, b):
count = 0
c = a ^ b # Bits that are different are 1s
while c != 0:
count += c & 1 # `count` increments upon a different bit
c >>= 1 # Right shift `c` by one bit so that LSB can be got
return count
def num_bit_swap2(a, b):
count = 0
c = a ^ b
while c != 0:
count += 1
c &= c - 1 # Clear the rightmost 1 bit
return count
def _test():
pass
def _print():
a = int('1001101', 2)
b = int('1110110', 2)
print(num_bit_swap(a, b))
print(num_bit_swap2(a, b))
if __name__ == '__main__':
_test()
_print()
|
fb26320a5614ef723fee554c71a58289690a3de4 | ptrgags/affine-font-indeed | /font.py | 1,975 | 3.515625 | 4 | from future.utils import iteritems
import numpy
import yaml
class Font(object):
"""
a Font holds the geometry for every letter and the corresponding
strokes.
"""
def __init__(self, fname='font.yaml'):
"""
Initialize the font from a YAML file
"""
self.font_data = self.parse_font(fname)
def __getitem__(self, key):
"""
Allow subscript access to the underlying font data.
"""
return self.font_data[key]
def __len__(self):
"""
How many letters are in this font?
"""
return len(self.font_data)
@property
def alphabet(self):
"""
See what symbols are supported in this font file.
"""
return set(self.font_data.keys())
@classmethod
def parse_font(cls, fname):
"""
Parse the font from a YAML file.
This produces a dictionary of the form
letter -> list of strokes
A "Stroke" is a triangle in object space that
defines one of the strokes of the letter.
Each stroke is a 2x3 matrix that defines the
origin, and two legs of the triangle. See the following
diagram for the data format for a single stroke
Y
|
|
|
O------X
[O_x, X_x, Y_x]
[O_y, X_y, Y_y]
This method calls Font.process_font() which
converts these nested lists into NumPy arrays
for later calculations.
"""
with open(fname, 'r') as yaml_file:
raw_font = yaml.safe_load(yaml_file)
return dict(cls.process_font(raw_font))
@classmethod
def process_font(cls, raw_font):
"""
Go through the font dictionary
and make the strokes into
"""
for letter, strokes in iteritems(raw_font):
stroke_arrays = [numpy.array(stroke) for stroke in strokes]
yield letter, stroke_arrays
|
5d0e99f7e604778d72531f5a4b5655b0efc958d9 | sahilsehgal81/python3 | /listcopy.py | 388 | 3.890625 | 4 | #!/usr/bin/python
def list_copy(lst):
result = []
for list in lst:
result += [list]
return result
def main():
a = [10, 20, 30, 40]
b = list_copy(a)
print("a = ", a, " b = ", b)
print("Is", a, "equals to ", b, "?", sep="", end=" ")
print(a == b)
print("Is", a, "an alias of", b, "?", sep="", end=" ")
print(a is b)
b[2] = 35
print("a = ", a, "and b = ", b)
main()
|
2145f92973e4c5d7bd6afca1a5ab10c332c9ea83 | DSmathers/Blackjack.py | /Blackjack.py | 6,303 | 3.734375 | 4 | import random
print('****************************************')
print("* Welcome to Daniel's Casino game v1.0 *")
print('* started on 11/18/2020 using Python *')
print ('****************************************')
print ('')
def new_deck():
'''creates a new 52 card deck
'''
deck = []
for suit in ('H', 'D', 'C', 'S'):
for rank in ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'):
deck.append(suit + rank)
return deck
def shuffle(deck):
random.shuffle(deck)
return deck
def card_values():
"""Generates Values of all cards, giving aces 11
"""
deck = new_deck()
values = {}
for card in deck:
## print card
for i in range(13):
for rank in card:
if rank == '1':
values[card] = 10
elif rank == str(i) and rank != '1' and rank != '0':
values[card] = i
elif rank == 'J' or rank == 'Q' or rank == 'K':
values[card] = 10
elif rank == 'A':
values[card] = 11
return values
def new_hand(deck):
"""Deals hand to player and dealer and lets player take turn
"""
player_hand = []
dealer_hand = []
for i in range(2):
player_hand.append(deck[0])
deck.remove(deck[0])
dealer_hand.append(deck[0])
deck.remove(deck[0])
user_input = ''
print('__________________________')
print ('The Dealer has:', dealer_hand[0], '|', '??', '(',values[dealer_hand[0]], '+ ?? )')
print ('')
print ('Your hand is: ', player_hand, '(', hand_value(player_hand), ')')
print ('')
while True:
if hand_value(player_hand) == 21:
print ('B L A C K J A C K ')
break
elif hand_value(player_hand) > 21:
print ('You bust!')
break
else:
print ('Select From The Following....')
print ('(H) Hit ')
print ('(S) Stand ')
user_input = input('What is your selection? ')
if user_input == 'H' or user_input =='h':
print ('')
print ('You recieve: ', deck[0])
player_hand.append(deck[0])
deck.remove(deck[0])
print ('Your Hand is', player_hand, hand_value(player_hand))
print ('')
else:
print ('You end your turn with: ', hand_value(player_hand))
break
return player_hand, dealer_hand
def dealer_plays(dealer_hand, deck):
"""Dealer plays hand according to rules of blackjack
"""
print ('')
print ("The Dealer's Cards Are: ", dealer_hand, hand_value(dealer_hand))
while hand_value(dealer_hand) < 17:
## print 'The dealer ends its turn with: ', hand_value(dealer_hand)
print ('The Dealer hits')
print ('')
print ('The Dealer gets', deck[0])
dealer_hand.append(deck[0])
deck.remove(deck[0])
print ("The Dealer's Cards Are: ", dealer_hand, hand_value(dealer_hand))
if hand_value(dealer_hand) > 21:
print ('The Dealer Busts.')
return
print ('The Dealer ends its turn with:', hand_value(dealer_hand))
def hand_value(hand):
""" calculates value of a given hand and returns that value
"""
hand_value = 0
for card in hand:
hand_value = hand_value + values[card]
for card in hand:
if values[card] == 11 and hand_value > 21:
hand_value = hand_value - 10
return hand_value
def blackjack():
print ('Welcome to Blackjack')
print ('')
deck = shuffle(new_deck())
while True:
if len(deck) < 20:
deck = shuffle(new_deck())
print ('Reshuffling Deck...')
print ('')
else:
print ("Enter Y to play a game or E to exit")
answer = input('')
if answer == 'Y' or answer == 'y':
player_hand, dealer_hand = new_hand(deck)
if hand_value(player_hand)> 21:
print ("Dealer Wins")
## If player bust, asks if you want to play another hand. Otherwise dealer plays
else:
dealer_plays(dealer_hand, deck)
if hand_value(dealer_hand) > 21:
print ('You Win')
elif hand_value(dealer_hand) == hand_value(player_hand):
print ("Push") #If tie with no bust)
print ('You get your wager back')
elif hand_value(player_hand) > hand_value(dealer_hand):
print ('Player Wins') # Since loop resets if player busts, its safe to say
# that Player wins if player score > dealer score
else:
print ('Dealer Wins') # If Player Didn't win.....
elif answer == 'E' or answer == 'e':
print ('Thanks for playing.')
break;
else:
print ('Invalid input, please try again' )
values = card_values()
blackjack()
##game_selection = ''
##while game_selection == '':
## print 'Please choose between the following options;'
## print ' (B) | Play Blackjack '
## print ''
## print ' (C) | Check your balance '
## print ' (E) | Exit the Casino'
##
## game_selection = raw_input('What is your selection?')
## if game_selection == 'B' or game_selection == 'b':
## blackjack()
## elif game_selection == 'E' or game_selection == 'e':
## print 'Thanks for playing'
## elif game_selection == 'C' or game_selection == 'c':
## print 'Feature coming soon...'
## else:
## print ''
## print 'Invalid Selection, Please Try Again '
## print ''
## game_selection = ''
|
718c1106eccb9afffbb8d52346526116b177ba68 | imiu/studydocs | /books/pyalg/ch2.py | 2,274 | 3.875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
return self.head is None
def add(self, *args):
for data in args:
current = Node(data)
current.next = self.head
self.head = current
if self.tail is None:
self.tail = current
def clear(self):
self.head = None
self.tail = None
def append_head(self, *args):
current = self.head
if self.head is not None:
while current.next is not None:
current = current.next
for data in args:
node = Node(data)
if self.head is None:
self.head = node
else:
current.next = node
current = node
def append(self, *args):
for data in args:
node = Node(data)
if self.head is None:
self.head = node
else:
self.tail.next = node
self.tail = node
def length(self):
length = 0
current = self.head
while current is not None:
length += 1
current = current.next
return length
def search(self, data):
current = self.head
while current is not None:
if current.data == data:
return True
current = current.next
return False
def remove(self, data):
if self.search(data) is not True:
return False
current = self.head
prev = None
while current.data != data:
prev = current
current = current.next
if prev is None:
self.head = current.next
else:
prev.next = current.next
if current.next is None:
self.tail = prev
return True
def as_list(self):
current = self.head
l = []
while current is not None:
l.append(current.data)
current = current.next
return l
|
42b25c5a0b5d332c6ae9d329784439cbe8a4a4a8 | JonesCD/LPtHW | /ex15.py | 685 | 4.25 | 4 | # initiate argv module from sys library?
from sys import argv
# run the script and incorporate the filename in the python run command
script, filename = argv
# define string txt and fill it with file
txt = open(filename)
# show back name of file from python run command
# show contents of txt file with .read modifier
print "Here's your file %r:" % filename
print txt.read()
txt.close()
# ask via prompt for file name a second time
print "Type the filename again:"
file_again = raw_input("> ")
# open the filename defined in the user prompt
txt_again = open(file_again)
# show contents of txt file from prompt, again suing .read modifier
print txt_again.read()
txt_again.close() |
40734cdc4ddcbff931b8a85867f834cc01101c40 | holothuria/python_study | /基礎編/数値/モジュール/数値01_四則演算.py | 219 | 3.765625 | 4 |
test_integer = 100
print(test_integer + 10) # 加算(足し算)
print(test_integer - 10) # 減算(引き算)
print(test_integer * 10) # 乗算(掛け算)
print(test_integer / 10) # 除算(割り算)
|
b3f1ed249fe8a901bf48e65e40c536248bd2dd8c | priyancbr/PythonProjects | /StringIndexing.py | 462 | 4.375 | 4 | MyString = 'abcdefghij'
print(MyString)
print(MyString[-1])
print(f"Last letter is {MyString[-1]}")
print("Printing below using the other format method")
print("Last letter is {}".format(MyString[-1]))
print("First three characters {}".format(MyString[:3]))
print("Four characters from 'b' are {}".format(MyString[1:5]))
print("Characters until 'h' are {}".format(MyString[:8]))
print("Characters between b and e including b and e are {}".format(MyString[1:5]))
|
dc35049acbe82cf3fd10545fd8795745c08f817c | b2utyyomi/Network_data_acquisition | /use_14.py | 236 | 3.53125 | 4 | from product import Product
prod1 = Product('carrot', 1.25, 10)
print(prod1)
print('Buying 4 carrots...')
prod1.buy_Product(4)
print(prod1)
print('Changing the price to $1.50...')
#prod1.price = 1.50
prod1.set_price(1.50)
print(prod1)
|
8aff91fb29b51a83d870777445eedcc80d735f86 | a-ruzin/python-base | /lesson_3/_2_try_except.py | 283 | 3.953125 | 4 | """
Исключения
"""
i = int(input('целое'))
b = 3
a = 'Отрицательное' if i < 0 else 'не отрицательное'
if i < 0:
a = 'Отрицательное'
elif i > 0:
a = 'Положительное'
else:
a = 'равно 0'
print(a)
|
3243979dd198f446d2ddb4bd6c99666580128f48 | YunzeZhao/EnglishSubtitlesForSubs2srs | /srtIntoSubs2srs.py | 4,284 | 3.5 | 4 | #!python3
# -*- coding:utf8 -*-
# Author: Rundeepin
# Contact: alicecui.ac@gmail.com
from typing import List
from tkinter import filedialog
import os
import re
import ntpath
# 选择时间轴和字幕正文
def select_subtitle(raw_data):
data = []
for line in raw_data:
data.append(line.strip())
subtitle = []
index = 0
while index < len(data):
if '-->' in data[index]:
timeline = data[index].split(' --> ')
subtitle.append(timeline)
if any(c.isalpha() for c in data[index]):
subtitle.append(data[index])
index += 1
return subtitle
# 同一条时间轴内字幕拼成一行
def merge_line(subtitle):
index = 0
while index < len(subtitle) - 1:
if '{\an8}' in subtitle[index]:
subtitle[index] = re.sub('{\an8}','',subtitle[index])
if any(c.isalpha() for c in subtitle[index]):
if any(c.isalpha() for c in subtitle[index + 1]):
subtitle[index] += ' ' + subtitle[index + 1]
subtitle.pop(index + 1)
index += 1
# 判断是不是一条字幕一行
def is_1time_1line(subtitle):
index = 0
while index < len(subtitle):
if len(subtitle[index]) == 2:
index += 2
else:
return False
return True
# 以上三个函数合并使用得到初始字幕
def merge_subtitle(raw_data):
subtitle = select_subtitle(raw_data)
while True:
if is_1time_1line(subtitle):
break
else:
merge_line(subtitle)
return subtitle
# 删除只有括号说明文本的字幕,并把末尾的...替换成,
def del_useless(data):
index = 1
while index < len(data):
if '(' and ')' in data[index]:
data[index] = re.sub(r'\([^(]+\)', ' ', data[index])
if any(c.isalpha() for c in data[index]):
if data[index].endswith("..."):
data[index] = re.sub(r'\.{3}', ',', data[index])
index += 2
else:
del data[index]
del data[index - 1]
elif '[' and ']' in data[index]:
data[index] = re.sub(r'\[[^(]+\]', ' ', data[index])
if any(c.isalpha() for c in data[index]):
if data[index].endswith("..."):
data[index] = re.sub(r'\.{3}', ',', data[index])
index += 2
else:
del data[index]
del data[index - 1]
else:
if data[index].endswith("..."):
data[index] = re.sub(r'\.{3}', ',', data[index])
index += 2
return data
# 处理句首字母小写的句子
def start_merge(data):
index = 3
while index < len(data):
if data[index][0].islower():
data[index - 2] += ' ' + data[index]
del data[index - 3][1]
data[index - 3].append(data[index - 1][1])
del data[index]
del data[index - 1]
else:
index += 2
return data
# 处理句末是逗号或者小写字母无标点的句子
def end_merge(data):
index = 1
while index < len(data)-1:
if data[index][-1].islower() or data[index][-1] == ',':
data[index] += ' ' + data[index + 2]
del data[index - 1][1]
data[index - 1].append(data[index + 1][1])
del data[index + 2]
del data[index + 1]
else:
index += 2
return data
print("请选择utf-8格式的srt >>>")
TextPath = filedialog.askopenfilename(filetypes=[('srt file','*.srt')])
filename = os.path.basename(TextPath)
with open(TextPath, 'r', encoding='utf-8') as file:
raw_data = file.readlines()
# 拼合单条字幕并换掉...
data = del_useless(merge_subtitle(raw_data))
# 不同时间轴字幕拼合
subtitle = end_merge(start_merge(end_merge(start_merge(data))))
# 写出到结果
subtitleOutput = open(filename+'_Final.srt', 'w', encoding="utf-8")
list_num = 1
i = 0
while i < len(subtitle) - 1:
subtitleOutput.write(str(list_num) + '\n')
subtitleOutput.write(subtitle[i][0] + ' --> ' + subtitle[i][1] + '\n')
subtitleOutput.write(subtitle[i + 1] + '\n\n')
i += 2
list_num += 1
subtitleOutput.close()
print('finished')
|
ee362623c03cf0ba897c311c0c013c9bbeca9117 | peiyong-addwater/2018SM2 | /2018SM2Y1/COMP90038/assessments/Assignment1/problem2.py | 1,691 | 4.03125 | 4 | # Python3 program to count
# occurrences of an element
# if x is present in arr[] then
# returns the count of occurrences
# of x, otherwise returns -1.
def count(arr, x, n):
# get the index of first
# occurrence of x
i = first(arr, 0, n-1, x, n)
# If x doesn't exist in
# arr[] then return -1
if i == -1:
return i
# Else get the index of last occurrence
# of x. Note that we are only looking
# in the subarray after first occurrence
j = last(arr, i, n-1, x, n);
# return count
return j-i+1;
# if x is present in arr[] then return
# the index of FIRST occurrence of x in
# arr[0..n-1], otherwise returns -1
def first(arr, low, high, x, n):
if high >= low:
# low + (high - low)/2
mid = (low + high)//2
if (mid == 0 or x > arr[mid-1]) and arr[mid] == x:
return mid
elif x > arr[mid]:
return first(arr, (mid + 1), high, x, n)
else:
return first(arr, low, (mid -1), x, n)
return -1;
# if x is present in arr[] then return
# the index of LAST occurrence of x
# in arr[0..n-1], otherwise returns -1
def last(arr, low, high, x, n):
if high >= low:
# low + (high - low)/2
mid = (low + high)//2;
if(mid == n-1 or x < arr[mid+1]) and arr[mid] == x :
return mid
elif x < arr[mid]:
return last(arr, low, (mid -1), x, n)
else:
return last(arr, (mid + 1), high, x, n)
return -1
# driver program to test above functions
arr = [1, 2, 2, 3, 3, 3, 3]
x = 3 # Element to be counted in arr[]
n = len(arr)
c = count(arr, x, n)
print ("%d occurs %d times "%(x, c))
|
e0563a42905f029f9c5214e921a9147d2c4cdc7c | thu4nvd/ATBS-python | /book scripts/tablePrinter.py | 1,017 | 4.09375 | 4 | # tableData = [['apples', 'oranges', 'cherries', 'banana'],
# ['Alice', 'Bob', 'Carol', 'David'],
# ['dogs', 'cats', 'moose', 'goose']]
# Your printTable() function would print the following:
# apples Alice dogs
# oranges
# Bob cats
# cherries Carol moose
# banana David goose
def tprint(tableData):
# Tim so lon nhat max_row cua cac list con
max_row = len(max(tableData, key=lambda row: len(row)))
# print(max_row)
# Tinh max_len cua moi row
max_len = [ int(len(max(row, key=lambda i: len(i) ))) for row in tableData]
# print(max_len)
# In ra tung hang, hang thu i la phan tu thu i cua cac list con
for i in range(max_row):
for row in range(len(tableData)):
if i < len(tableData[row]):
# print(str(row[i].rjust(max_len[row] + 2)), end=" ")
str = tableData[row][i].rjust(max_len[row] + 2)
print(str, end=" ")
else:
print(" "*(max_len[row] + 2), end=" ")
print("\n")
|
bf8eaf08b4bb5b65ea2fc70a4be673af8cf427d0 | niluferbozkus/Odevler_EsraCakir | /dörtislemhesap.py | 760 | 3.90625 | 4 | islem = [ "+" , "-" , "*" , "/"]
count= 1
islemsayisi=int(input("Kaç işlem yapmak istiyorsunuz?: "))
while count <= islemsayisi:
sayi1 = int(input("İşlem yaapmak istediğiniz ilk sayıyı girin: "))
sayi2 = int(input("İşlem yaapmak istediğiniz ikinci sayıyı girin: "))
op = input("Yapmak istediğiniz işlem operatörünü girin(+,-,*,/):" )
count = count+1
if op in islem :
if op =="+" :
print(sayi1 + sayi2)
elif op== "-":
print(sayi1 - sayi2)
elif op=="*":
print(sayi1 * sayi2)
elif op=="/":
print(sayi1 / sayi2)
else:
print("Lütfen geçerli bir operatör girin!")
|
45d1116212e96e64cc261aa1c5941bd687f9d56e | lannyMa/s3 | /面向对象/08with-enter-exit.py | 3,046 | 3.96875 | 4 | #!/usr/bin/env python
# coding=utf-8
# 追踪信息+异常类+异常值
# raise AttributeError("hello world")
class Open:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
print("触发: __enter__")
def __exit__(self, exc_type, exc_val, exc_tb):
print("触发: __exit__")
# with Open('1.txt') as f:
# print("======>")
# 触发: __enter__
# ======>
# 触发: __exit__
class Open2:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
print("触发: __enter__")
def __exit__(self, exc_type, exc_val, exc_tb):
print("触发: __exit__")
print("exc_type:", exc_type)
print("exc_val:", exc_val)
print("exc_tb:", exc_tb)
# with Open2('1.txt') as f:
# print("=======>")
# 触发: __enter__
# =======>
# 触发: __exit__
# exc_type: None
# exc_val: None
# exc_tb: None
class Open3:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
print("触发: __enter__")
def __exit__(self, exc_type, exc_val, exc_tb):
print("触发: __exit__")
print("exc_type:", exc_type)
print("exc_val:", exc_val)
print("exc_tb:", exc_tb)
# with Open3('1.txt') as f:
# print("=======>")
# raise AttributeError("属性不存在")
# 触发: __enter__
# =======>
# 触发: __exit__
# exc_type: <class 'AttributeError'>
# exc_val: 属性不存在
# exc_tb: <traceback object at 0x00000000021DBF08>
# Traceback (most recent call last):
# File "C:/Users/Administrator/PycharmProjects/s3/面向对象/08with-enter-exit.py", line 67, in <module>
# raise AttributeError("属性不存在")
# AttributeError: 属性不存在
class Open4:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
print("触发: __enter__")
def __exit__(self, exc_type, exc_val, exc_tb):
print("触发: __exit__")
print("exc_type:", exc_type)
# with Open4('1.txt') as f:
# print("=======>")
# raise AttributeError("属性不存在")
#
# print("执行跟with语句无关的代码..")
# 触发: __enter__
# Traceback (most recent call last):
# =======>
# File "C:/Users/Administrator/PycharmProjects/s3/面向对象/08with-enter-exit.py", line 95, in <module>
# 触发: __exit__
# raise AttributeError("属性不存在")
# AttributeError: 属性不存在
# exc_type: <class 'AttributeError'>
class Open5:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
print("触发: __enter__")
def __exit__(self, exc_type, exc_val, exc_tb):
print("触发: __exit__")
print("exc_type:", exc_type)
return True
# with Open5('1.txt') as f:
# print("=======>")
# raise AttributeError("属性不存在")
#
# print("执行跟with语句无关的代码..")
# 触发: __enter__
# =======>
# 触发: __exit__
# exc_type: <class 'AttributeError'>
# 执行跟with语句无关的代码.. |
d47a63d434018aa774834e56b7270be73253661e | panditdandgule/DataScience | /NLP/Projects/BirthdayApp.py | 1,094 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 13 09:10:41 2019
@author: pandit
#Birthday Reminder Application
"""
import time
#os module is used to notify user
#using default "Ubuntu" Notification bar
import os
#Birthday file is the one in which the actual birthdays
#and dates are present. This file can bem manually editied
#or can be automated.
#For simplicity, we will edit it manually.
#Birthdays should be written in this file in
#the format: "MonthDay Name Surname"(without Quotes)
birthdayFile='/home/pandit/Downloads/NLP/Projects/BirthdayFile'
def checkTodayBirthdays():
fileName=open(birthdayFile,'r')
today=time.strftime('%m%d')
flag=0
for line in fileName:
if today in line:
line=line.split(' ')
flag=1
# line[1] contains Name and line[2] contains Surname
os.system('notify-send "Birthdays Today: ' + line[1]
+ ' ' + line[2] + '"')
if flag==0:
os.system('notify-send "No Birthday Today"')
if __name__=="__main__":
checkTodayBirthdays()
|
ada0e1719a920175a7c216eaa31a4b580b3eea0d | AlexisFil/Solved_Problems_With_Python | /datetime_lib_testscript.py | 840 | 4.5 | 4 | """
A simple code demonstrating the use of datetime library
for calendar dates manipulation
"""
from datetime import datetime,timedelta
#Current date
currentDate = datetime.now()
print("Today the date is \n> {}\n".format(currentDate))
#Print date in past/future
aWeek = timedelta(days=7)
aWeekAgo = (currentDate - aWeek)
print("A week ago it was \n> {}\n".format(aWeekAgo))
#Specific information on a date
#There is also selection for hours,minutes,seconds
print(f'''A week ago was:
Day:{aWeekAgo.day}
Month:{aWeekAgo.month}
Year:{aWeekAgo.year}
''')
#Input a date
birthday = input("When were you born?(Day/Month/Year)\n>")
birthDate=datetime.strptime(birthday,'%d/%m/%Y')
print(f'''\n+++++Birthday+++++
Day :{birthDate.day}
Month :{birthDate.month}
''')
age = currentDate - birthDate
print(f'You are:\n{age.days} days old!')
|
706244d6701350d109509dfa3820ecd48c008330 | 821-N/holbertonschool-higher_level_programming | /0x05-python-exceptions/4-list_division.py | 459 | 3.890625 | 4 | #!/usr/bin/python3
def list_division(list_1, list_2, list_length):
result = [0] * list_length
try:
for i in range(0, list_length):
try:
result[i] = list_1[i] / list_2[i]
except ZeroDivisionError:
print("division by 0")
except (TypeError, ValueError):
print("wrong type")
except IndexError:
print("out of range")
finally:
return result
|
4f605451cff9a4d6c2cb619c6937a3c246ace2db | SagarKulk539/APS_Lib_2020 | /Codeforces/threePairs_656_A.py | 995 | 3.6875 | 4 | '''
APS-2020
Problem Description, Input, Output : https://codeforces.com/contest/1385/problem/A
Code by : Sagar Kulkarni
'''
for _ in range(int(input())):
x,y,z=map(int,input().split())
if x==y and x==z and y==z:
print("YES")
print(x,y,z)
else:
if x==y:
a=x
b=z
c=z
if max(a,b)==x and max(a,c)==y and max(b,c)==z:
print("YES")
print(a,b,c)
else:
print("NO")
elif x==z:
a=y
b=x
c=y
if max(a,b)==x and max(a,c)==y and max(b,c)==z:
print("YES")
print(a,b,c)
else:
print("NO")
elif y==z:
a=x
b=x
c=y
if max(a,b)==x and max(a,c)==y and max(b,c)==z:
print("YES")
print(a,b,c)
else:
print("NO")
else:
print("NO")
|
961430ff650850b757dceefe38f98213312e814a | SaretMagnoslove/Python_OOP_Tutorial-Corey_Schafer | /Python OOP Tutorial 5 Special (MagicDunder) Methods/Python OOP Tutorial 1 Classes and Instances/oop.py | 410 | 3.8125 | 4 | class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@compony.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('first', 'employee', 5000)
emp_2 = Employee('second', 'employee', 6000)
print(emp_1.fullname())
print(Employee.fullname(emp_1)) |
6dae8ea26026027d2169131e9bcfe3c8d57cc286 | zolxl/python | /python/m1.2EchoName.py | 319 | 3.828125 | 4 | name = input("请输入姓名:") #输入姓名
print("{}同学,学好python,前途无量!".format(name)) #输出整个字符
print("{}大侠,学好python,大展拳脚!".format(name[0])) #输出第0个字符
print("{}哥哥,学好python,人见人爱!".format(name[1:])) #输出第一个字符以后
|
822e171340e2eae615cb1b768205109236cca25b | byungjur96/Algorithm | /2822.py | 270 | 3.5625 | 4 | score = []
questions = []
final = 0
for i in range(8):
score.append((i+1, int(input())))
score.sort(key=lambda a: a[1])
for i in range(3,8):
questions.append(str(score[i][0]))
final += score[i][1]
questions.sort()
print(final)
print(" ".join(questions))
|
968cb730d2ed3829230059558b3ea358df6e1109 | fllsouto/py14 | /cap6/funcao-kwargs.py | 829 | 3.71875 | 4 | def teste_kwargs(**kwargs):
for key, value in kwargs.items():
print('{0} = {1}'.format(key, value))
print('-'*10)
# Passando apenas uma chave
teste_kwargs(nome='fellipe')
# Passando mais de uma chave
teste_kwargs(nome='fellipe', idade=28)
dados = {"nome" : 'fellipe', "idade" : 28}
# TypeError: teste_kwargs() takes 0 positional arguments but 1 was given
#teste_kwargs(dados)
print("imprimindo dados direto: ", dados)
# TypeError: teste_kwargs() takes 0 positional arguments but 2 were given
#teste_kwargs(*dados)
print(*dados)
print("imprimindo dados com um *: ", *dados)
teste_kwargs(**dados)
# O método print não tem um parâmetro nomeado como 'nome'
# TypeError: 'nome' is an invalid keyword argument for print()
#print("imprimindo dados com um *: ", **dados)
#
print("{nome} -- {idade} ".format(**dados))
|
4a486a8942d7558a434af3a1292042db2f873c9d | RodoDenDr0n/UCU_labs | /Lab 5/caesar.py | 1,385 | 3.953125 | 4 | """CAESAR ENCODE"""
def caesar_encode(message, key):
"""
>>> caesar_encode("hello", 1)
ifmmp
"""
message = message.lower()
message = list(message)
if key >= 26:
key = key % 26
for i in range(len(message)):
if message[i] == " ":
continue
if ord(message[i]) < 120:
if ord(message[i]) + key >= 123:
message[i] = chr(ord(message[i]) - 26 + key)
else:
message[i] = chr(ord(message[i]) + key)
else:
message[i] = chr(ord(message[i]) - 26 + key)
message = "".join(message)
return message
print(caesar_encode("hello", 1))
def caesar_decode(message, key):
"""
>>> caesar_decode("ifmmp", 1)
hello
"""
message = message.lower()
message = list(message)
if key >= 26:
key = key % 26
for i in range(len(message)):
if message[i] == " ":
continue
if ord(message[i]) > 99:
if ord(message[i]) - key < 96:
message[i] = chr(ord(message[i]) + 26 - key)
else:
message[i] = chr(ord(message[i]) - key)
else:
message[i] = chr(ord(message[i]) + 26 - key)
if message[i] == "{":
message[i] = "a"
message = "".join(message)
return message
print(caesar_decode("ifmmp", 1))
|
2968da6f10153ca7b4049ac5a71e23ef027bc6e3 | sweetysweets/makeSimple | /Dinic/Dinic.py | 1,626 | 3.546875 | 4 | #!/usr/bin/python
# c.durr - 2009 - max flow by Dinic in time O(n^2 m)
from queue import Queue
def dinic(graph, cap, s,t):
""" Find maximum flow from s to t.
returns value and matrix of flow.
graph is list of adjacency lists, G[u]=neighbors of u
cap is the capacity matrix
"""
assert s!=t
q = queue()
# -- start with empty flow
total = 0
flow = [[0 for _ in graph] for _ in graph]
while True: # repeat until no augment poss.
q.put(s)
lev = [-1]*n # construct levels, -1=unreach.
lev[s] = 0
while not q.empty():
u = q.get()
for v in graph[u]:
if lev[v]==-1 and cap[u][v] > flow[u][v]:
lev[v]=lev[u]+1
q.put(v)
if lev[t]==-1: # stop if target not reachable
return (total, flow)
upperBound = sum([cap[s][v] for v in graph[s]])
total += dinicStep(graph, lev, cap, flow, s,t,upperBound)
def dinicStep(graph, lev, cap, flow, u,t, limit):
""" tries to push at most limit flow from u to t. Returns how much could
be pushed.
"""
if limit<=0:
return 0
if u==t:
return limit
val=0
for v in graph[u]:
res = cap[u][v] - flow[u][v]
if lev[v]==lev[u]+1 and res>0:
av = dinic(graph,lev, cap,flow, v,t, min(limit-val, res))
flow[u][v] += av
flow[v][u] -= av
val += av
if val==0:
lev[u]=-1
return val
|
3b05bc5abc9adb1dc12c559e60f3945bfcd6c509 | MercyFlesh/associative_rules | /associative_rules/rules.py | 5,471 | 4.125 | 4 | """
Module for finding associative rules
"""
import itertools as it
def _get_keys_combinations(sequence):
"""Get pairs of item
Сreates unique combinations for rules
from the passed sequence
Args:
sequence (tuple): sequence to get pairs of combinations
Returns:
(map object): object from sequence of combinations
"""
return map(sorted, (set(x) for x in it.chain(*[it.combinations(sequence, i+1) for i in range(len(sequence)-1)])))
def _confidience(rules, sup_items_dict, min_conf=None):
"""Calculate confidience
and selection of rules by confidience
Args:
rules (dict): dict for write rules
sup_items_dict (dict): dict with support of items in wich keys are sequences, values - support
min_conf (float, optional): given minimum confidience for selection rules. Defaults to None.
"""
if min_conf and (min_conf < 0 or min_conf > 1):
raise ValueError('Mininmum confidience must be a positive number within the interval [0, 1]. '
f'You enter {min_conf}.')
for k, v in sup_items_dict.items():
if len(k) > 1:
# for rules need sequences of len > 1
probable_rules = list(_get_keys_combinations(k))
length = len(probable_rules)
for i in range(length):
item = (tuple(probable_rules[i]), tuple(probable_rules[length-1-i])) # make a rule from combinations
item_support_first = sup_items_dict[item[0]]
conf = round(v/item_support_first, 4) # confidience(a->b) = support(a->b)/support(a)
if min_conf:
if conf >= min_conf:
rules[item] = [
item_support_first, sup_items_dict[item[1]], v, conf
]
else:
rules[item] = [
item_support_first, sup_items_dict[item[1]], v, conf
]
def _lift(rules, min_lift=None):
"""Calculate lift
and selection of rules by lift
Args:
rules (dict): dict for write rules
min_lift (float, optional): given minimum lift. Defaults to None.
"""
if min_lift and min_lift < 0:
raise ValueError('Mininmum lift must be a positive number within the interval [0, inf). '
f'You enter {min_lift}.')
for item, coef in rules.items():
lift = round(coef[3]/coef[1], 4) # lift(a->b) = conf(a->b)/support(b)
if min_lift:
if lift >= min_lift:
coef.append(lift)
else:
coef.append(lift)
def _levarage(rules, min_levar=None):
"""Calculate levarage
and selection of rules by levarage
Args:
rules (dict): dict for write rules
min_lift (float, optional): given minimum levarage. Defaults to None.
"""
if min_levar and (min_levar < -1 or min_levar > 1):
raise ValueError('Mininmum levarage must be a number within the interval [-1, 1]. '
f'You enter {min_levar}.')
for item, coef in rules.items():
levar = round(coef[2] - coef[0]*coef[1], 4) # support(a->b) - support(a)*support(b)
if min_levar:
if levar >= min_levar:
coef.append(levar)
else:
coef.append(levar)
def _conviction(rules, min_conv=None):
"""Calculate conviction
and selection of rules by conviction
Args:
rules (dict): dict for write rules
min_lift (float, optional): given minimum conviction. Defaults to None.
"""
if min_conv and min_conv < 0:
raise ValueError('Mininmum conviction must be a positive number within the interval [0, inf). '
f'You enter {min_conv}.')
for item, coef in rules.items():
denom = 1 - coef[3]
if (denom > 0):
conv = round((1 - coef[1])/denom, 4) # conv(a->b) = (1 - support(b))/(1 - conf(a->c))
else:
conv = 'inf'
if min_conv:
if type(conv) == str or conv >= min_conv:
coef.append(conv)
else:
coef.append(conv)
def get_associative_rules(sup_items_dict, min_conf=None, min_lift=None, min_levar=None, min_conv=None):
"""Organization of calculation of rule coefficients
Args:
sup_items_dict (dict): dict of sequence with support {(item,): support, ...}
min_conf (float, optional): . Defaults to None.
min_lift (float, optional): . Defaults to None.
min_levar (float, optional): . Defaults to None.
min_conv (float, optional): . Defaults to None.
Returns:
(dict): rules - { ((first_items), (second_items)): [first_support, second_support,
item_support, confidience, lift,
levarage, conviction], ...}
"""
rules = dict()
_confidience(rules, sup_items_dict, min_conf)
_lift(rules, min_lift)
_levarage(rules, min_levar)
_conviction(rules, min_conv)
return rules
|
18db26889c87feda77e465990681a3d825e0a3b7 | jedi-the-code-warrior/python-applications | /geodesic_distance_between_two_addresses.py | 1,381 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 31 13:47:46 2019
@author: Anjani K Shiwakoti
Synopsis: Given starting address and destination address, calculate the geodesic
distance between the two locations. A geodesic line is the shortest path between
two points on a curved surface, like the Earth.
"""
from geopy.geocoders import Nominatim
from geopy.distance import geodesic
global location
global geolocator
geolocator = Nominatim(user_agent="my_geo_location_tracker")
def getCoordinates(address):
location = geolocator.geocode(address)
#print(location.raw)
#{'place_id': '9167009604', 'type': 'attraction', ...}
return (location.latitude, location.longitude)
def getAddress(address):
location = geolocator.geocode(address)
return location.address
def getDistance(pointA, pointB):
starting_coords = getCoordinates(pointA)
destination_coords = getCoordinates(pointB)
return (geodesic(starting_coords, destination_coords).miles)
starting_address = input("Enter Your Starting Address: ")
destination_address = input("Enter Your Destination Address: ")
print ("Your total geodesic distance between: ",
getAddress(starting_address), " and ",
getAddress(destination_address), " is: ",
getDistance(starting_address, destination_address), "miles")
|
6e51f874011fc0c980fd507ff6b7c820201942ce | dibery/UVa | /vol111/11108.py | 746 | 3.515625 | 4 | import sys
def test(S, p, q, r, s, t):
S = S.replace('p', p).replace('q', q).replace('r', r).replace('s', s).replace('t', t)[::-1]
stack = []
for i in S:
if i in 'TF':
stack.append(i)
elif i == 'N':
stack[-1] = 'T' if stack[-1] == 'F' else 'F'
else:
a, b = stack.pop(), stack.pop()
if i == 'K':
stack.append('T' if a == b == 'T' else 'F')
elif i == 'A':
stack.append('F' if a == b == 'F' else 'T')
elif i == 'C':
stack.append('F' if a > b else 'T')
else:
stack.append('T' if a == b else 'F')
return stack[0] == 'T'
c = ['T', 'F']
for S in sys.stdin:
S = S.strip()
if S != '0':
print('tautology' if all(test(S, p, q, r, s, t) for p in c for q in c for r in c for s in c for t in c) else 'not')
|
3db9359bc0c38db69fc44918960ad0a5461d8826 | thomas-liao/leetcode_lintcode | /Python/leetcode_python/92_reverse_linked_list_ii-medium.py | 2,068 | 3.578125 | 4 | # solution 1, mine, not exactly one pass...
# class Solution:
# def reverseBetween(self, head, m: int, n: int):
# if not head or not head.next or m == n:
# return head
# dummy = ListNode(0)
# dummy.next = head
# runner1 = dummy
# counter = 0
# assert m < n
# while counter < m - 1:
# runner1 = runner1.next
# counter += 1
# runner2 = runner1
# while counter < n:
# runner2 = runner2.next
# counter += 1
# temp1 = runner1.next # starting head of list need to be reversed
# temp2 = runner2.next # next position of tail of reversed linkedlist
# # cut
# runner1.next = runner2.next = None
# new_head, new_tail = self.reverseAll(temp1)
# # splice together
# runner1.next = new_head
# new_tail.next = temp2
# return dummy.next
# def reverseAll(self, head):
# tail = head
# prev, cur = None, head
# while cur:
# ne = cur.next
# cur.next = prev
# prev = cur
# cur = ne
# return prev, tail # new head, new tail
# solution 2, one pass
# class Solution:
# def reverseBetween(self, head, m: int, n: int):
# if not head or not head.next or m == n:
# return head
# dummy = ListNode(0)
# dummy.next = head
# counter = 0
# runner = dummy
# for i in range(m-1):
# runner = runner.next
# new_tail = runner.next
# prev, cur = None, runner.next
# ne = None # important
# # for i in range(n - m): # wrong... reverse time = n - m + 1, miss-counted new_tail - > None
# for i in range(n - m + 1):
# ne = cur.next
# cur.next = prev
# prev = cur
# cur = ne
# new_head = prev
# new_tail.next = ne # important
# runner.next = new_head
# return dummy.next
|
7a0164a2b62eb121d3b6bcca547da09e9ad6259d | yooshinK/Python_Study | /Algorithm_py_Input_Num_Find_Max_Num.py | 704 | 4.09375 | 4 | import math
#-------------------------------------
def find_max_num_for(array_values):
n = len(array_values)
s = array_values[0]
max_idx = 0
for i in range(1, n):
if s <= array_values[i]:
s = array_values[i]
max_idx = i
print("Max Id is " + max_idx.__str__())
print("Max Number is ", s)
#-------------------------------------
num_list = []
num = int(input("Enter how many elements you want"))
print('Enter numbers in array: ')
for i in range(0,num):
# a = int(input("num :"))
num_list.append(int(input("num :")))
find_max_num_for(num_list)
print('ARRAY: ', num_list)
#-------------------------------------
# # Result
|
c7cc156d5a91f5afb2600045e9d6527c77c74e70 | LiangZZZ123/algorithm_python | /1/18_graph.py | 2,429 | 3.65625 | 4 | from collections import deque
GRAPH = {
'A': ['B', 'F'],
'B': ['C', 'I', 'G'],
'C': ['B', 'I', 'D'],
'D': ['C', 'I', 'G', 'H', 'E'],
'E': ['D', 'H', 'F'],
'F': ['A', 'G', 'E'],
'G': ['B', 'F', 'H', 'D'],
'H': ['G', 'D', 'E'],
'I': ['B', 'C', 'D'],
}
# FIFO
class Queue(object):
def __init__(self):
self._deque = deque()
def push(self, value):
return self._deque.append(value)
def pop(self):
return self._deque.popleft()
def __len__(self):
return len(self._deque)
bfs_list = []
def bfs(graph, start):
q1 = Queue()
q1.push(start)
searched = set()
while q1:
cur_node = q1.pop()
if cur_node not in searched:
bfs_list.append(cur_node)
searched.add(cur_node)
for node in graph[cur_node]:
q1.push(node)
print('bfs:')
bfs(GRAPH, 'A')
print(bfs_list)
# DFS_SEARCHED = set()
# def dfs(graph, start):
# if start not in DFS_SEARCHED:
# print(start)
# DFS_SEARCHED.add(start)
# for node in graph[start]:
# if node not in DFS_SEARCHED:
# dfs(graph, node)
def dfs(graph, start):
DFS_SEARCHED = set()
dfs_list = []
def inner(graph, start):
nonlocal DFS_SEARCHED, dfs_list
if start not in DFS_SEARCHED:
# print(start)
dfs_list.append(start)
DFS_SEARCHED.add(start)
for node in graph[start]:
if node not in DFS_SEARCHED:
inner(graph, node)
inner(graph, start)
return dfs_list
print('dfs:')
print(dfs(GRAPH, 'A'))
# Achieve dfs using customized Stack built from deque
# LIFO
class Stack():
def __init__(self):
self._deque = deque()
def push(self, value):
return self._deque.append(value)
def pop(self):
return self._deque.pop()
def __len__(self):
return len(self._deque)
def dfs_use_stack(graph, start):
dfs_list = []
stack = Stack()
stack.push(start)
searched = set()
while stack:
cur_node = stack.pop()
if cur_node not in searched:
dfs_list.append(cur_node)
searched.add(cur_node)
# why add reversed here?
for node in reversed(graph[cur_node]):
stack.push(node)
return dfs_list
print('dfs_use_stack:')
print(dfs_use_stack(GRAPH, 'A'))
|
3a85d51ba6071903a05633a03478d118d18bccd4 | mpellittieri/hear-me-code | /pbjloop.py | 460 | 4.09375 | 4 | bread = input("How many slices of bread do you have?")
peanutbutter = input("How much peanut butter do you have?")
jelly = input ("How much jelly do you have?")
sandwich = 1
while bread >= 2 and peanutbutter >=1 and jelly >=1:
print "I'm making sandwich #{0}".format(sandwich)
bread = bread - 2
peanutbutter = peanutbutter - 1
jelly = jelly - 1
sandwich = sandwich + 1
print "All done; only had enough bread for {0} sandwiches.".format(sandwich - 1)
|
1895f3c5fd2ab17e9c4b3ac935800adb2af55d8d | samuelreboucas07/Challenges-Project-Euller | /problem-2.py | 719 | 3.703125 | 4 | # Even Fibonacci numbers
limit_upper = 4000000
number_fibonacci = 1
sequence_fibonacci = [1]
sum_even_fibonacci = 0
while (number_fibonacci < limit_upper):
if(len(sequence_fibonacci) == 1):
number_fibonacci = sequence_fibonacci[0] + 1
else:
size_sequence = len(sequence_fibonacci)
number_fibonacci = sequence_fibonacci[size_sequence - 1] + sequence_fibonacci[size_sequence - 2]
if(number_fibonacci <= limit_upper):
sequence_fibonacci.append(number_fibonacci)
for element in sequence_fibonacci:
if(element % 2 == 0):
sum_even_fibonacci += element
print('A soma dos números pares da sequência de fibonacci menores que 4000000 é: ' +str(sum_even_fibonacci)) |
dc70644bd22c7623f9191d448f02b4dfa372348e | tykennedy13/python-work | /week_1_todo/bath_math_todo.py | 1,116 | 3.9375 | 4 | """
Lets do a basic math problem
"""
# TODO: perform all of the following mathematical operations and print the results in between
# TODO: set a constant tax rate of 20%
# TODO: ask a user what their revenue was for the quarter
# TODO: deduct the tax rate from the revenue and print the profit as well as the tax amount
# TODO: split that profit evenly amongst 7 share holders
# TODO: print out what each shareholder will receive from the profit
add, subtract, multi, divid, exp, remain = 2 + 2, 4 - 3, 4 * 5, 6 / 3, 4 ** 2, 120 % 5
print(add, subtract, multi, divid, exp, remain)
tax_rate= .2
revenue_quarter = int(input("What was your revenue last quarter?: "))
tax = revenue_quarter * tax_rate
profit = revenue_quarter - (revenue_quarter * tax_rate)
print("We made this much last quarter", str(profit), "and we paid this much in taxes", str(tax))
shareholders = profit / 7
print("We made this much last quarter", str(profit), "and we paid this much in taxes", str(tax), ", and each shareholder made", str(round(shareholders, 2)), ".")
# !! extra credit: print the remainder of the total profit divided by 6
|
79b055568de551296bfa426b04183f501db6b63f | Rubyroobinibu/pythonpractice | /python 15.09.19/abstraction.py | 448 | 3.609375 | 4 | class Mobile:
def __init__(self):
# self.__maxPrice=897
self.maxPrice=897
mob=Mobile()
print(mob.maxPrice)
class Mobile:
def __init__(self):
self.__maxPrice=897
def getPrice(self):
print(self.__maxPrice)
def setPrice(self,price):
self.__maxPrice=price
mob=Mobile()
# print(mob.maxPrice)
mob.getPrice()
mob.setPrice(688990)
mob.getPrice()
|
14c18561c0795efb27dbc0e09b49a7fbe709c375 | TyrannousHail03/PythonProjects | /Physics_VADT Calculator/vadtformulas.py | 1,637 | 4.09375 | 4 | import math
class vadtformulas:
def __init__(self):
self.vinit = None
self.vfinal = None
self.time = None
self.distance = None
self.acceleration = None
def ift_distance(self):
self.vinit = int(input("\n What is the Initial Velocity? "))
self.vfinal = int(input("What is the Final Velocity? "))
self.time = int(input("What is the Time? "))
self.distance = 0.5 * (self.vinit + self.vfinal) * self.time
print("Distance: " + str(self.distance) + "m" + "\n")
def iat_distance(self):
self.vinit = int(input("\nWhat is the Initial Velocity? "))
self.acceleration = int(input("What is the Acceleration? "))
self.time = int(input("What is the Time? "))
self.distance = (self.vinit * self.time) + (0.5 * self.acceleration * (self.time**2))
print("Distance: " + str(self.distance) + "m" + "\n")
def iad_fv(self):
self.vinit = int(input("What is the Initial Velocity? "))
self.acceleration = int(input("What is the Acceleration? "))
self.distance = int(input("What is the Distance? "))
self.vfinal = math.sqrt((self.vinit ** 2) + (2 * (self.acceleration * self.distance)))
print("Final Velocity: " + str(self.vfinal) + "m/s" + "\n")
def iat_fv(self):
self.vinit = int(input("What is the Initial Velocity? "))
self.acceleration = int(input("What is Acceleration? "))
self.time = int(input("What is the Time? "))
self.vfinal = self.vinit + (self.acceleration * self.time)
print("Final Velocity: " + str(self.vfinal) + "m/s" + "\n") |
8372ecd3e78c88144ab306e05a537e9d7e4b15e9 | mkonate/python-fun | /string-fun.py | 280 | 4.21875 | 4 | message = 'This is a basic string in single quotes'
message_2 = "This is another basic string; this time, in double quotes"
print(message)
print(message_2)
print('The lenght of the string "{}" is {}.'.format(message, len(message)))
print('All Caps: {}'.format(message.upper()))
|
6c2c2ec42521d23dffed9b0f3bea1908a5ee6230 | chelseahouston/Year-100 | /main.py | 592 | 3.984375 | 4 | def form():
name = input("What is your name? ")
age = input("What is your age? ")
try:
age = int(age)
except ValueError:
print("Incorrect value. Please enter a number. Restarting...")
form()
difference = 100 - age
year100 = 2020 + difference
print("Hello, " + name + ".")
print(f"You will turn 100 years old in the year { year100 } !")
def run():
runagain = input("Run again? (Y/N): ")
if runagain == "Y":
form()
run()
elif runagain == "N":
print("Goodbye. Have a good day.")
else:
print("Error: Incorrect Value.")
run()
form()
run()
|
23591873e5a1f7dcec0d2640dd504384716e5e35 | neverlish/Learned | /data/ebs-ai-basic/3/5/02.py | 503 | 3.703125 | 4 | import numpy as np
import pandas as pd
df_train = pd.read_csv('fashion-mnist_train.csv')
df_test = pd.read_csv('fashion-mnist_test.csv')
# step1 각 데이터 프레임의 값을 배열에 저장하기
data_train = np.array(df_train, dtype=np.float32)
x_train = data_train[:, 1:]
y_train = data_train[:, 0]
data_test = np.array(df_test, dtype=np.float32)
x_test = data_test[:, 1:]
y_test = data_test[:, 0]
# step2 훈련 데이터와 테스트 데이터 출력하기
print(df_test)
print(df_train)
|
ad5944b9daf89b13c3f151f6a37109fc83bee824 | geomsb/KalHomework | /Homework 3/3_4.py | 1,177 | 3.90625 | 4 | import turtle
turtle.pensize (5)
def drawChessboard(startx, endx, starty, endy):
turtle.penup ()
turtle.goto (startx,starty)
turtle.pendown ()
for row in range (0,8):
for column in range (0,8):
if row % 2 == 0:
if column % 2 >0:
turtle.color("black")
else:
turtle.color ("black","white")
turtle.begin_fill()
else:
if column % 2 ==0:
turtle.color("black")
else:
turtle.color ("black","white")
turtle.begin_fill()
for square in range (0,4):
turtle.forward ((endx - startx) / 8)
turtle.right (90)
turtle.end_fill ()
turtle.forward ((endx - startx) / 8)
turtle.penup()
turtle.right (90)
turtle.forward ((endx - startx) / 8)
turtle.right (90)
turtle.forward (endx - startx)
turtle.left (180)
turtle.pendown ()
drawChessboard(-100, 100, 100, -100)
drawChessboard (140, 340, 100, -100)
|
74cda87619ad120f32f4c43a6e2e95060835acec | jwayneroth/mpd-touch | /pygameui/label.py | 7,289 | 3.625 | 4 | import re
import view
CENTER = 0
LEFT = 1
RIGHT = 2
TOP = 3
BOTTOM = 4
WORD_WRAP = 0
CLIP = 1
class Label(view.View):
"""Multi-line, word-wrappable, uneditable text view.
Attributes:
halign
CENTER, LEFT, or RIGHT. Horizontal alignment of
text.
valign
CENTER, TOP, or BOTTOM. Vertical alignment of text.
wrap_mode
WORD_WRAP or CLIP. Determines how text is wrapped to
fit within the label's frame width-wise. Text that
is wrapped to multiple rendered lines is clipped at
the bottom of the frame. After setting the text
attribute, the text_size attribute may be used to
resize the label's frame; also see shrink_wrap.
Changing wrap_mode forces a redraw of the label.
text
The text to render.
Changing the text forces a redraw of the label.
Style attributes:
Changing a style attribute does not automatically redraw
text in the new style given that you will likely change
a number of style attributes. Call 'layout' when you
have finished changing style attributes.
Using a new theme automatically restylizes and thus redraws
the text using the new theme's style attributes.
text_color
The color of the text.
text_shadow_color
The color of the fake text-shadow.
text_shadow_offset
The offset of the fake text-shadow in the form
(dx, dy).
font
The font used for rendering the text.
padding
Horizontal and vertical spacing from the label's
interior edges where text is rendered.
"""
def __init__(self, frame, text,
halign=CENTER, valign=CENTER,
wrap=CLIP):
view.View.__init__(self, frame)
self.halign = halign
self.valign = valign
self._wrap_mode = wrap
self._text = text
self._enabled = False
@property
def text(self):
return self._text
@text.setter
def text(self, text):
self._text = text
self.render()
@property
def wrap_mode(self):
return self._wrap_mode
@property
def wrap_mode(self, mode):
self._wrap_mode = mode
self.render()
def layout(self):
self.render()
view.View.layout(self)
def render(self):
"""Force (re)draw the text to cached surfaces.
"""
self._render(self._text)
def _render(self, text):
self.text_surfaces, self.text_shadow_surfaces = [], []
if text is None or len(text) == 0:
self._text = None
self.text_size = (0, 0)
return
text = text.replace("\r\n", "\n").replace("\r", "\n")
wants_shadows = (self.text_shadow_color is not None and
self.text_shadow_offset is not None)
if self._wrap_mode == CLIP:
self._text = re.sub(r'[\n\t]{2, }', ' ', text)
self.text_size = self._render_line(self._text, wants_shadows)
elif self._wrap_mode == WORD_WRAP:
self._render_word_wrapped(text, wants_shadows)
def _render_line(self, line_text, wants_shadows):
line_text = line_text.strip()
text_surface = self.font.render(line_text, True, self.text_color)
self.text_surfaces.append(text_surface)
if wants_shadows:
text_shadow_surface = self.font.render(
line_text, True, self.text_shadow_color)
self.text_shadow_surfaces.append(text_shadow_surface)
return text_surface.get_size()
def _render_word_wrapped(self, text, wants_shadows):
self._text = text
self.text_size = [0, 0]
line_width = 0
max_line_width = self.frame.w - self.padding[0] * 2
line_tokens = []
tokens = re.split(r'(\s)', self._text)
token_widths = {}
for token in tokens:
if len(token) == 0:
continue
token_width, _ = token_widths.setdefault(token,
self.font.size(token))
if token == '\n' or token_width + line_width >= max_line_width:
line_size = self._render_line(''.join(line_tokens),
wants_shadows)
self.text_size[0] = max(self.text_size[0], line_size[0])
self.text_size[1] += line_size[1]
if token == '\n':
line_tokens, line_width = [], 0
else:
line_tokens, line_width = [token], token_width
else:
line_width += token_width
line_tokens.append(token)
if len(line_tokens) > 0:
line_size = self._render_line(''.join(line_tokens),
wants_shadows)
self.text_size[0] = max(self.text_size[0], line_size[0])
self.text_size[1] += line_size[1]
def shrink_wrap(self):
"""Tightly bound the current text respecting current padding."""
self.frame.size = (self.text_size[0] + self.padding[0] * 2,
self.text_size[1] + self.padding[1] * 2)
print 'Label::shrink_wrap \t size: ' + str(self.frame.size)
def _determine_top(self):
if self.valign == TOP:
y = self.padding[1]
elif self.valign == CENTER:
y = self.frame.h // 2 - self.text_size[1] // 2
elif self.valign == BOTTOM:
y = self.frame.h - self.padding[1] - self.text_size[1]
return y
def _determine_left(self, text_surface):
w = text_surface.get_size()[0]
if self.halign == LEFT:
x = self.padding[0]
elif self.halign == CENTER:
x = self.frame.w // 2 - w // 2
elif self.halign == RIGHT:
x = self.frame.w - 1 - self.padding[0] - w
return x
def draw(self, force=False):
if not view.View.draw(self, force) or not self._text:
return False
wants_shadows = (self.text_shadow_color is not None and self.text_shadow_offset is not None)
y = self._determine_top()
for index, text_surface in enumerate(self.text_surfaces):
x = self._determine_left(text_surface)
if wants_shadows:
text_shadow_surface = self.text_shadow_surfaces[index]
top_left = (x + self.text_shadow_offset[0],
y + self.text_shadow_offset[1])
self.surface.blit(text_shadow_surface, top_left)
self.surface.blit(text_surface, (x, y))
y += text_surface.get_size()[1]
return True
def __repr__(self):
if self._text is None:
return ''
return self._text
class HeadingOne(Label):
def __init__(self, frame, text, halign=CENTER, valign=CENTER, wrap=CLIP):
Label.__init__(self, frame, text, halign, valign, wrap)
class DialogLabel(Label):
def __init__(self, frame, text, halign=CENTER, valign=CENTER, wrap=CLIP):
Label.__init__(self, frame, text, halign, valign, wrap)
|
c9bbad78c99bcd525962805cec6bb22cce86f12f | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day04/exercise04.py | 698 | 3.921875 | 4 | """
根据成绩判断等级,如果录入空字符串,程序退出
如果录入成绩错误达到3次,则退出程序并显示成绩输入错误
"""
count = 0
while count < 3:
str_score = input("请输入一个成绩:")
if str(str_score) == "":
break
score = int(str_score)
if 90 <= score <= 100:
print("优秀")
elif 80 <= score < 90:
print("良好")
elif 70 <= score < 80:
print("中等")
elif 60 <= score < 70:
print("及格")
elif 0 <= score < 60:
print("不及格")
elif score > 100 or score <0:
print("录入错误")
count += 1
else:
print("输入次数过多,程序结束!")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.