blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
20dc08c13c398410c6f876b9ac2d517d496b6cc9 | AShoom85/MyPythonCode | /L8/8_2lambda.py | 2,408 | 3.78125 | 4 | # Exercise 3
# список представляет собой базу данных.
# каждый элемент содержит сведения:
# имя
# возраст
# рост
# вес
# Пользователь может заказать сортировку по любому полю:
# a = [['tom',2,13,3], ['basil',11,15,5],['kity',9,14,4],['soly',4,12,2]]
# n = input('Сортировать по имени (1), возрасту (2), росту (3), весу (4): ')
# пользователь вводит номер поля. Число приводится к типу integer, и из него
# вычитается единица, т. к. индексация списка начинается с нуля.
# n = int(n)-1
# Далее определяется функция sort_cats(). Ей передается аргумент i, а она
# возвращает n-ый элемент этого аргумента. если этой функции передать
# вложенный список, то она вернет его n-й элемент.
# def sort_cats(i):
# return i[n]
# a.sort(key=sort_cats)
# for i in a:
# print("%7s %3d %4d %3d" % (i[0],i[1],i[2],i[3]))
# В функции sort() указывается пользовательская функция. Когда sort() извлекает
# очередной элемент списка, в данном случае - вложенный список, то передает
# этой функции.
# Элемент списка подменяется на то, что возвращает пользовательская функция.
# Если пользователь заказывает сортировку по второму столбцу, вывод будет таким:
# Сортировать по имени (1), возрасту (2), росту (3), весу (4): 2
# tom 2 13 3
# soly 4 12 2
# kity 9 14 4
# basil 11 15 5
# Переписать программу с использованием lambda-функции
a = [['tom', 2, 13, 3],['basil', 11, 15, 5],['kity', 9, 14, 4],['soly', 4, 12, 2]]
n = int(input('Сортировать по имени (1), возрасту (2), росту (3), весу (4): '))
a.sort(key=lambda i: i[n-1])
for i in a:
print("%7s %3d %4d %3d" % (i[0], i[1], i[2], i[3]))
|
e0b23f083be55a84117e6d263bbe5f250d89b906 | Microshak/iotil-sawyer | /sawyer_demo/src/Old/Deleteme.py | 801 | 3.625 | 4 | import speech_recognition as sr
r = sr.Recognizer()
m = sr.Microphone()
#set threhold level
with m as source: r.adjust_for_ambient_noise(source)
print "Set minimum energy threshold to {}".format(r.energy_threshold)
# obtain audio from the microphone
with sr.Microphone() as source:
print "Say something!"
audio = r.listen(source)
# recognize speech using Microsoft Bing Voice Recognition
BING_KEY = "4b1323765f834841b16daee7894783c3"
print r.recognize_sphinx(audio)
#try:
print "Microsoft Bing Voice Recognition thinks you said " + r.recognize_bing(audio, key=BING_KEY)
#except sr.UnknownValueError:
# print "Microsoft Bing Voice Recognition could not understand audio"
#except sr.RequestError as e:
# print "Could not request results from Microsoft Bing Voice Recognition service; {0}".format(e)
#print 'e' |
4a455a43e0f61f6bdb41ed33d2c5840d29f078ed | Littlegaga666/VigenereCipher | /py/encrypt.py | 383 | 3.53125 | 4 | def encrypt(initial, key):
""" Use : encrypt("MESSAGEINCAPITALS", "keyword")
=> 'COWUUDNYXGCJFCQVW'
"""
initial = initial.upper()
key = key.lower()
lkey = len(key)
list1 = [ord(i) for i in key]
list2 = [ord(i) for i in initial]
output = ''
for i in range(len(list2)):
value = (list2[i] + list1[i % lkey]) % 26
output += chr(value + 65)
return output
|
385717a171ba5d6da57026ea455ddcaf121f98ce | chandana24shetty/mulesoft | /muleSoft.py | 1,821 | 4.375 | 4 | import sqlite3
#Creating a connectrion object for DB
dbname="Movies.db"
connect=sqlite3.connect(dbname)
cursor=connect.cursor()
def createTable():
stmt=" CREATE TABLE IF NOT EXISTS Movies (actor text, actress text, year integer, director text) "
cursor.execute(stmt)
connect.commit()
print("QUERY EXECUTED SUCCESSFULLY AND COMMITED TO MOVIES TABLE...")
def addMovie(actor,actress,year,director):
stmt=" INSERT INTO Movies (actor,actress,year,director) VALUES (?,?,?,?)"
args=actor,actress,year,director
cursor.execute(stmt,args)
connect.commit()
print("QUERY EXECUTED SUCCESSFULLY AND COMMITED TO MOVIES TABLE...")
def retrieveMovieDetails(query):
cursor.execute(query)
connect.commit()
print("QUERY EXECUTED SUCCESSFULLY AND COMMITED TO MOVIES TABLE...")
for row in cursor.execute(query):
print(row)
def main():
welcome="""
1. CREATE TABLE
2. ADD MOVIE
3. QUERYING
"""
print(welcome)
choice=int(input("ENTER 1, 2, 3 BASED ON YOUR NEED \n"))
if choice == 1 :
createTable()
elif choice == 2 :
actor=input("ENTER THE ACTOR NAME: ")
actress=input("ENTER THE ACTRESS NAME: ")
year=int(input("ENTER THE YEAR OF RELEASE: "))
director=input("ENTER THE DIRECTOR NAME: ")
addMovie(actor,actress,year,director)
elif choice == 3:
query=input("TYPE THE QUERY IN CORRECT SYNTAX: ")
retrieveMovieDetails(query)
else:
print("INVALID CHOICE")
if __name__ == "__main__":
flag="y"
while(flag == "y"):
main()
flag=input("Do you wish to continue Y/N:").lower()
print("EXITING...")
|
66515922902e95a76c8a40deeedece074127e2c1 | Rjt17/Python | /hackfest 2020 oct/cyclic_binary_string.0.4.py | 597 | 3.75 | 4 | binary_s = str(input())
temp_binary_list = list(binary_s)
temp_binary = binary_s
length = len(binary_s)
decimals = []
decimal = 0
greatest_pow = 0
powers = []
for x in range(len(binary_s)):
temp_binary = temp_binary[1:] + temp_binary[0]
decimals.append(int(temp_binary, 2))
decimals.sort()
print(len(decimals))
decimal = decimals[-1]
print(decimal)
if "1" not in binary_s:
print(-1)
elif temp_binary_list.count("1") == 1:
print(length - 1)
else:
for power in reversed(range(length)):
divisor = 2 ** power
if decimal % divisor == 0:
greatest_pow = power
break
print(greatest_pow) |
9023dd0c1287e10a55c2c52b370dbab3297060fa | brianchiang-tw/leetcode | /No_0336_Palindrome Pairs/palindrome_pairs_by_bipartite_partition.py | 3,197 | 4.03125 | 4 | '''
Description:
Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.
Example 1:
Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]
Example 2:
Input: ["bat","tab","cat"]
Output: [[0,1],[1,0]]
Explanation: The palindromes are ["battab","tabbat"]
'''
from typing import List
class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
# dictionary by comprehension
# key : word
# vluae : index of word
word_index_dict = { word:index for index, word in enumerate(words) }
# use set's property to avoid repeated pairs
index_of_palindrome_pair = set()
# check each word and its possible palindrome combination
for index, word in enumerate(words):
for i in range(0,len(word)+1, +1):
# Make a bipartite partition with index i
# word = left + right
left = word[:i]
right = word[i:]
# If left is palindrome, and revrse of right exists,
# then right[::-1] + left + right = right[::-1] + word is also a palindrome
if left == left[::-1] and word_index_dict.get( right[::-1], -1) not in (index, -1):
index_of_palindrome_pair.add( (word_index_dict[ right[::-1] ], index ) )
# If right is palindrome, and reverse of left exists,
# then left + right + left[::-1] = word + left[::-1] is also a palindrome.
if right == right[::-1] and word_index_dict.get( left[::-1], -1) not in (index, -1):
index_of_palindrome_pair.add( (index, word_index_dict[ left[::-1] ] ) )
# convert set of tuple to list of list as final result
result = list( map (list, index_of_palindrome_pair) )
return result
# n : the length of input string array, words.
# k : the average character length of each word in input array.
## Time Complexity: O( n * k^2 )
#
# The overhead in time is the outer for loop iterating on (index, word), which is of O( n ), and
# the inner for loop iterating on i, which is of O( k ), and
# the word slicing operation word[:i] as well as word[i:], which is of O( k ).
# It takes O( n * k^2 ) totally
## Space Complexity: O( n )
#
# The overhead in space is the storage to maintain dictionary, word_index_dict, which is of O( n)
def test_bench():
test_data = [
["abcd","dcba","lls","s","sssll"],
["bat","tab","cat"]
]
# expected output:
'''
[[0, 1], [1, 0], [3, 2], [2, 4]]
[[0, 1], [1, 0]]
'''
for string_array in test_data:
print( Solution().palindromePairs(string_array) )
return
if __name__ == '__main__':
test_bench()
|
91be8399f14f62ca28c6e9ff592ba473596a6759 | WilliamPalmtree/Cyphers | /VinegereCipher.py | 3,073 | 3.625 | 4 | def letterSub(letter, key):
if (ord(letter) < 123 and ord(letter) > 96):
#Lowercase
if (ord(letter) + key > 122):
letter = chr(ord(letter) + key - 26)
elif(ord(letter) + key < 97):
letter = chr(ord(letter) + key + 26)
else:
letter = chr(ord(letter) + key)
elif (ord(letter) > 64 and ord(letter) < 91):
# Uppercase
if (ord(letter) + key > 90):
letter = chr(ord(letter) + key - 26)
elif(ord(letter) + key < 65):
letter = chr(ord(letter) + key + 26)
else:
letter = chr(ord(letter) + key)
elif (ord(letter) < 65 and ord(letter) > 31):
# symbols and numbers
if (ord(letter) + key > 64):
letter = chr(ord(letter) + key - 32)
elif(ord(letter) + key < 32):
letter = chr(ord(letter) + key + 32)
else:
letter = chr(ord(letter) + key)
return letter
def encodeMessage(message, key):
encodedMessage = ""
vig = []
vigNum = 0
# this list will hold the ASCII values for the key
for ch in key:
if (ord(ch) < 123 and ord(ch) > 96):
vig.append(ord(ch) - 96) # append the ith ASCII value from the key into the list vig[]
elif (ord(ch) > 64 and ord(ch) < 91):
vig.append(ord(ch) - 64)
elif (ord(ch) < 65 and ord(ch) > 31):
vig.append(ord(ch) - 31)
for ch in message:
if (vigNum > len(key) - 1):
vigNum = vigNum - len(key)
newEncodeLetter = letterSub(ch, vig[vigNum])
print("1. SubKey: " + str(vig[vigNum]) + " Old: " + ch + " New: " + newEncodeLetter)
encodedMessage = encodedMessage + newEncodeLetter
vigNum = vigNum + 1
else:
newEncodeLetter = letterSub(ch, vig[vigNum])
print("2. SubKey: " + str(vig[vigNum]) + " Old: " + ch + " New: " + newEncodeLetter)
encodedMessage = encodedMessage + newEncodeLetter
vigNum = vigNum + 1
return(encodedMessage)
print(encodedMessage)
def decodeMessage(message, key):
decodedMessage = ""
vig = []
vigNum = 0
# this list will hold the ASCII values for the key
for ch in key:
if (ord(ch) < 123 and ord(ch) > 96):
vig.append(ord(ch) * -1 + 96) # append the ith ASCII value from the key into the list vig[]
elif (ord(ch) > 64 and ord(ch) < 91):
vig.append(ord(ch) * -1 + 64)
elif (ord(ch) < 65 and ord(ch) > 31):
vig.append(ord(ch) * -1 + 31)
for ch in message:
if (vigNum > len(key) - 1):
vigNum = vigNum - len(key)
newDecodeLetter = letterSub(ch, (vig[vigNum]))
print("1. SubKey: " + str(vig[vigNum]) + " Old: " + ch + " New: " + newDecodeLetter)
decodedMessage = decodedMessage + newDecodeLetter
vigNum = vigNum + 1
else:
newDecodeLetter = letterSub(ch, (vig[vigNum]))
print("2. SubKey: " + str(vig[vigNum]) + " Old: " + ch + " New: " + newDecodeLetter)
decodedMessage = decodedMessage + newDecodeLetter
vigNum = vigNum + 1
return(decodedMessage)
print(decodedMessage)
key = raw_input("Please input a word or phrase key: ")
print("Your key is " + str(key))
message = raw_input("Now please type your message: ")
ED = raw_input("Would you like to encode or decode? Please use E or D ")
if(ED == "E"):
print(encodeMessage(message, key))
if(ED == "D"):
print(decodeMessage(message, key)) |
0e32f323ea0f8ab8ecd70004d80b607ee318dbb7 | jaychsu/algorithm | /lintcode/668_ones_and_zeroes.py | 2,241 | 3.890625 | 4 | """
optimized space complexity
"""
class Solution:
"""
@param: strs: an array with strings include only 0 and 1
@param: m: An integer
@param: n: An integer
@return: find the maximum number of strings
"""
def findMaxForm(self, strs, m, n):
if not strs:
return 0
"""
`dp[j][k]` means the current str can be made up of
`j` 0s and `k` 1s
"""
dp = [[0] * (n + 1) for _ in range(m + 1)]
c0 = c1 = 0
for s in strs:
c0 = s.count('0')
c1 = len(s) - c0
for j in range(m, c0 - 1, -1):
for k in range(n, c1 - 1, -1):
"""
case 1: included current `strs[i - 1]`
case 2: not included current `strs[i - 1]`, same as previous
"""
dp[j][k] = max(
dp[j][k],
dp[j - c0][k - c1] + 1
)
return dp[m][n]
"""
origin
"""
class Solution:
"""
@param: strs: an array with strings include only 0 and 1
@param: m: An integer
@param: n: An integer
@return: find the maximum number of strings
"""
def findMaxForm(self, strs, m, n):
if not strs:
return 0
l = len(strs)
"""
`dp[i][j][k]` means the pre- `i`th strs can be made up of
`j` 0s and `k` 1s
dp[0][j][k] = 0
"""
dp = [[[0] * (n + 1) for _ in range(m + 1)] for _ in range(l + 1)]
c0 = c1 = 0
for i in range(1, l + 1):
c0 = strs[i - 1].count('0')
c1 = len(strs[i - 1]) - c0
for j in range(m + 1):
for k in range(n + 1):
"""
case 1: included current `strs[i - 1]`
"""
if j >= c0 and k >= c1:
dp[i][j][k] = dp[i - 1][j - c0][k - c1] + 1
"""
case 2: not included current `strs[i - 1]`, same as previous
"""
if dp[i - 1][j][k] > dp[i][j][k]:
dp[i][j][k] = dp[i - 1][j][k]
return dp[l][m][n]
|
cd32dba1fa6cd62bf144144981da4b544b7ea8d8 | AyeJayTwo/smsAnalyze | /dbCreate.py | 4,781 | 3.75 | 4 | from datetime import date # Needed to translate date to day of week
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import sms
import sqlite3
"""Set up the file to be read"""
with open("test_sms.xml", "r") as filetoberead:
sms_file = filetoberead.readlines()
"""Get rid of header information and read only text messages"""
# header = sms_file[0:2]
# end_xml_line = sms_file[-1]
body = sms_file[3:-1] # 1437 text messages total
del sms_file
database = []
for (index, text) in enumerate(body):
# Build outline for database, a giant list of lists
# each individual list would be a recap of each text sent
phone = sms.get_phone(text)
name = sms.get_name(text)
sent = sms.get_type(text)
(year, month, day, hour, minute, second) = sms.get_date(text)
database.append((index,
phone,
name,
sent,
year,
month,
day,
date(year, month, day).weekday(),
hour,
minute,
second,
date(year, month, day)))
# Create SQLITE3 Connection in memory. Not sure
con = sqlite3.connect(":memory:")
cursor = con.cursor()
# Create the table
cursor.execute("create table sms(id,phone,name,sent,year,month,day,weekday,hour,minute,second,date)")
# Fill the table
cursor.executemany("insert into sms(id,phone,name,sent,year,month,day,weekday,hour,minute,second,date) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)", database)
"""-----------------------------------------------
Draw bar graph based showing texts per person,
also demonstrating sent/receive proportion
------------------------------------------------"""
# Discriminate sent/received
sq4 = "SELECT name, COUNT(*) as TextSent FROM sms WHERE sent=? GROUP BY name"
x = cursor.execute(sq4,[(0)]).fetchall() #Received
y = cursor.execute(sq4,[(1)]).fetchall() #Sent
# Create intermediary tables
cursor.execute("create table smsR(name, received)")
cursor.executemany("insert into smsR(name,received) values (?, ?)", x)
cursor.execute("create table smsS(name, sent)")
cursor.executemany("insert into smsS(name,sent) values (?, ?)", y)
#Combine Tables
z = cursor.execute("SELECT * FROM smsR INNER JOIN smsS on smsR.name=smsS.name ORDER by received DESC").fetchall()
name = []
receive = []
sent = []
for each in z:
name.append(each[0])
receive.append(each[1])
sent.append(each[3])
plt.subplot2grid((2,2),(0,0))
ind = np.arange(len(z))
width = 0.9
p1 = plt.bar(ind, receive, width, color = 'r')
p2 = plt.bar(ind, sent, width, color = 'b', bottom = receive)
plt.xlabel('Unknown People')
plt.ylabel('Total Sent')
plt.legend( (p1[0], p2[0]), ('Received','Sent'))
"""-----------------------------------------------
Plot total texts sent on each day of the week
-----------------------------------------------"""
sq1 = "SELECT * FROM sms WHERE weekday=?"
dates = []
for i in range(0, 7):
cursor.execute(sq1, [(i)])
dates.append(len(cursor.fetchall()))
plt.subplot2grid((2,2),(0,1))
ind = np.arange(7)
width = .85
p1 = plt.bar(ind, dates, width, color='b')
plt.xticks(ind + width / 2., ('M', 'T', 'W', 'Th', 'F', 'S', 'S'))
plt.ylabel('Total Texts')
plt.title('Total Texts by Day')
"""-----------------------------------------------
Select based on month of the year; possibly more
useful if we had aggregate data or multiple years
-----------------------------------------------"""
sq2 = "SELECT * FROM sms WHERE month=?"
months = []
for i in range(1, 13):
cursor.execute(sq2, [(i)])
months.append(len(cursor.fetchall()))
plt.subplot(223)
ind = np.arange(len(months))
width = 0.85
#p2 = plt.bar(ind, months, width, color='r')
plt.xticks(ind + width / 2., ('J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'))
plt.ylabel('Total Texts')
plt.title('Total Texts by Month')
"""-----------------------------------------------
Create a time series demonstration of the
texts/day...also includes an option for a smoother
curve which does a sliding window against the
time series data
-----------------------------------------------"""
sq5 = "SELECT year,month,day,date, COUNT(*) as TextTotal FROM sms GROUP BY date"
x = cursor.execute(sq5).fetchall()
totals = []
ordinal_dates = []
for i in range(len(x)):
totals.append(x[i][4])
ordinal_dates.append(date(x[i][0],x[i][1],x[i][2]))
d = matplotlib.dates.date2num(ordinal_dates)
plt.subplot2grid((2,2),(1,0),colspan=2)
win_size = 30
window = [1./win_size]*win_size
q = (np.convolve(window,totals,'same'))
p1 = plt.plot_date(d,totals, '-',color='c')
p2 = plt.plot_date(d,q, '-',color='r')
plt.ylabel('Total Texts/Day Window = 7')
plt.grid(True)
plt.show() |
83b06eab93ce99b7140cea40c934d7baea62d655 | programmerhardik397/password_generator | /password_generator.py | 1,012 | 4.09375 | 4 | print(f"Hello user!! Welcome to the password generator!!!\n")
print("Firstly,you need to create a new username.")
message0 = input("\nSo enter your first name: ")
mess0 = input("Enter your last name: ")
username = (f"Your username: {message0}_{mess0}")
print(username)
import random
password = []
message2 = input("Enter your email address: ")
message3 = input("Enter your mobile number: ")
password.append(username.title())
password.append(message2)
password.append(message3)
r = random.randint(1,10)
s = random.randint(1,10)
t = random.randint(1,10)
u = random.randint(1,10)
v = random.randint(1,10)
w = random.randint(1,10)
x = random.randint(1,10)
y = random.randint(1,10)
z = random.randint(1,10)
a = random.randint(1,10)
#print(password)
def password_generation():
print(f"\nYour generated password: {message3[r]}{username[s]}"
f"{message2[t]}{username[u]}{username[v]}{message2[w]}{message3[x]}{message2[y]}{message2[z]}{message2[a]}")
print("Thanks for using!!")
password_generation() |
f687393cb17a6e6d4276f216d9f37d5a661186b1 | annabalan/python-challenges | /Practice-Python/ex-03.py | 513 | 4.3125 | 4 | # Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a program that prints out all the elements of the list that are less than 5.
numbers = [1, 3, 3, 5, 7, 11, 13, 17, 39]
numbers_2 = []
userinput = int(input("Enter a number: "))
def below_five(numbers):
for number in numbers:
if number <= userinput:
numbers_2.append(number)
print(numbers_2)
else:
print("Number greater than", str(userinput))
below_five(numbers)
|
794ef10d107fb4f4a65a55a44f8ada8272c56fe2 | Fadssd33/Seminario-de-Programacion | /Funciones/TelefonoFuncion.py | 1,379 | 3.9375 | 4 | # Se requiere relizar un programa que facture el uso de un telefono considerando lo siguiente:
# a. Le pedira la captura la tarifa por segundo al usuario
# b. Solicita al usuario la cantidad de comunicaciones que se realizaron
# c. Solicitara al usuario la duracion de cada comunicacion, expresada en horas, minutos y segundos
# d. Imprime el valor de la llamada la cantidad de comunicaciones
# e. Imprime la cantidad total acumulada en funcion a las llamadas realizadas.
def ConvertirSegundos(Horas, Minutos, Segundos):
# convertir horas
segHoras = Horas * 3600
# convertir Minutos
segMinutos = Minutos * 60
# Juntar todos los segundos:
return segHoras + segMinutos + Segundos
total = 0
tarifaSegundo = int(input('Ingrese la tarifa por segundo: '))
cantLlamadas = int(input('Ingrese el numero de llamadas realizadas: '))
for x in range(cantLlamadas):
horas = int(input('Ingrese las horas de la llamada ' + str(x + 1)))
minutos = int(input('Ingrese los minutos de la llamda ' + str(x + 1)))
segundos = int(input('Ingrese los segundos de la llamada ' + str(x +1)))
print('Valor de la llamada ', x + 1 , ': ' , ConvertirSegundos(horas, minutos, segundos) * tarifaSegundo)
total += ConvertirSegundos(horas, minutos, segundos) * tarifaSegundo
print('Total acumulado ', total, 'Numero de llamadas realizadas: ', cantLlamadas)
|
25286e9eeb01e455fe55e3d819a6a2fe93363cd7 | alyxcsulb/homework3 | /solution-321.py | 350 | 4.1875 | 4 | # Change in cents output
# (Calculate change using fewest number of coins)
change = int(input("Enter amount of change due in cents: "))
print("Your change is: ")
print(change//25, "quarters")
change = change%25
print(change//10, "dimes")
change = change%10
print(change//5, "nickels")
change = change%5
print(change//1, "pennies")
change = change%1
|
41f75e35154b638de9b25c83bc2fe2b8176f32e8 | anmmoinuddin/Python | /Online Course/Computing in Python III(Data Structure)/CP3-I(String).py | 2,553 | 4.28125 | 4 | ##data Structure
## Interger by value
#----------------------------------------------------------------------
#integer
def addone(aninteger):
aninteger=aninteger+1
print("aninterger:", aninteger)
myinteger=5
print("myinteger before addone:", myinteger)
addone(myinteger)
print("myinteger after addone:", myinteger)
#----------------------------------------------------------------------
#string
def addexc(astring):
astring=astring + " !"
print("astring:", astring)
mystring="Hello, World"
print("mylist before additem:", mystring)
addexc(mystring)
print("mystring after addexc", mystring)
#----------------------------------------------------------------------
#List and append option(to add sth new)
def additem(alist):
alist.append("New item!")
print("alist:", alist)
mylist=["One","Two", "Three"]
print("mylist before additem:", mylist)
additem(mylist)
print("myList after additem:", mylist)
#-----------------------------------------------------------------------------
#Variable assignment
#with list everything being updated at the same time
mylist1=["One", "Two", "Three"]
mylist2=mylist1
mylist1.append("Four")
print("mylist1:", mylist1)
print("mylist2:", mylist2)
#---------------------------------------------------------------------------
#with integer it keeps the old value in comparison with list
myint1=5
myint2=myint1
myint1=7
print("myint1:", myint1)
print("myint2:", myint2)
#--------------------------------------------------------------
#Mutable variable
myinteger=1
myinteger=2
print(myinteger)
#---------------------------------------------------------------
##Function vs. Methods
# function is normally defined at the beginnin of program
mynumericstring="123455"
mynonnumericstring="ABCDE"
print(mynumericstring.isdigit())
print(mynonnumericstring.isdigit())
#-------------------------------------------------------------------
##Strings
##3way to declare strings
#---------------------------------------------------------------------------------
mystring1='"12345"'
mystring2="'12345'"
mystring3='''"'12345'"'''
mystring4="'''12345'''"
print(mystring1)
print(mystring2)
print(mystring3)
print(mystring4)
#-------------------------------------------------------------------------------
mystring="12345 \n 45"
print(mystring)
#------------------------------------------------------
mystring="12345\n8910\tabcde\"fghiklm\\no"
print(mystring)
#----------------------------------------------------
|
7466b5a7f5659248bbe47c900e21349aa0a73621 | jaehui327/algorithm | /코딩테스트/200914Line/2.py | 567 | 3.78125 | 4 | def solution(ball, order):
answer = []
for i in range(len(order) - 1, -1, -1):
for j in range(0, i + 1):
if order[j] == ball[0]:
answer.append(ball[0])
ball.pop(0)
order.pop(j)
break
elif order[j] == ball[-1]:
answer.append(ball[-1])
ball.pop(-1)
order.pop(j)
break
# print(answer, ball, order)
return answer
res1 = solution([1, 2, 3, 4, 5, 6], [6, 2, 5, 1, 4, 3])
print("res1: ", res1) |
04bca0bb6c0de6dd3eea80b16551be76b73b2d8e | Eshliforfriends/itstep | /lesson12/only_odd_arguments.py | 670 | 3.96875 | 4 | def only_odd_arguments(func):
def wrapper_odd(*args):
n = 1
for i in args:
for j in args:
if j % 2 != 0:
if n < len(args):
n += 1
continue
elif n == len(args):
return print(func(*args))
else:
print('Enter odd arguments')
break
break
return wrapper_odd
@only_odd_arguments
def add(a, b):
return a + b
add(4, 4)
add(5, 5)
@only_odd_arguments
def multiple(a, b, c, d, e):
return a*b*c*d*e
multiple(11,7,8,1,5)
multiple(5,5,11,9,5)
|
2ce19d9ac8c727e4cd19470d0f9559159de78464 | kgmonisha/PythonScripts | /Numbers/random2.py | 298 | 3.609375 | 4 | import random
import string
moves = ["rock","paper","scissors"]
print(random.choice(moves))
#this will run choice 10 times
print(random.choices(moves, k=10))
#lets assume we have weights for diff colours
wheel = ['red','green','blue']
weights = [10,10,2]
print(random.choices(wheel,weights,k=10))
|
a861c643850a08f6b5c201460f586af9f30a2f5f | kynthus/htnpython | /src/eff_07.py | 637 | 3.78125 | 4 | # -*- coding: utf-8 -*-
R"""
リスト関連の組み込み関数
"""
nums = [1, 2, 3, 4, 5]
# map関数で変換
print(list(map(lambda n: n + 10, nums))) # [[11, 12, 13, 14, 15]
# filter関数で抽出
print(list(filter(lambda n: n % 2 == 0, nums))) # [2, 4]
'''
1000万回繰り返して測定
Python 2系, 3系双方で以下のような結果となった
リスト内包表記
time = 9.73599982262
map関数
time = 13.3900001049
単純な算術変換なら内包表記の方が速い
関数呼出
リスト内包表記
time = 17.1809999943
map関数
time = 13.3710000515
関数呼出が絡むとmap関数の方が速い
'''
|
ce1b86bc3798cae7fc12420411c2e9850d0e2285 | Sarang-1407/CP-LAB-SEM01 | /CP Lab/CP Lab Test/CP Lab Test A1 long version.py | 820 | 4.125 | 4 | seconds=float(input("Enter the time in seconds:"))
minutes=seconds//60
hours=minutes//60
days=hours//24
years=days//365
if seconds<60:
print("Years=0, Days=0, Hours=0, Minutes=0, Seconds=",seconds)
if (seconds>=60 and seconds<3600):
print("Year=0, Days=0, Hours=0, Minutes=",minutes,"Seconds=", seconds-60*minutes)
if (seconds>=3600 and seconds<86400):
print("Year=0, Days=0, Hours=",hours,"Minutes=", minutes-60*hours,"Seconds=", seconds-60*minutes)
if (seconds>=86400 and seconds<31536000):
print("Year=0, Days=",days,"Hours=",hours-24*days,"Minutes=", minutes-60*hours,"Seconds=", seconds-60*minutes)
if (seconds>31536000):
print("Year=",years, "Days=",days-365*years,"Hours=",hours-24*days,"Minutes=", minutes-60*hours,"Seconds=", seconds-60*minutes)
|
237341e360269c81c118f846b3f9587ca0156e6e | rao257/SamplePythonScripts | /hex2int.py | 4,040 | 3.515625 | 4 | #!/usr/bin/python
#Author: Suraj Patil
#Version: 1.0
#Date: 26th March 2014
'''
this file won't execute, you will have to type this all into the python prompt, which is the appropriate way of
doing programming, as it allows the programmer to have an interactive output
output:
0x0800 2048 Internet Protocol version 4 (IPv4)
0x0806 2054 Address Resolution Protocol (ARP)
0x0842 2114 Wake-on-LAN[3]
... any number of entries
input:
0x0800 Internet Protocol version 4 (IPv4)
0x0806 Address Resolution Protocol (ARP)
0x0842 Wake-on-LAN[3]
...any number of entries
0x0800 = hexadecimal of 2048
'''
>>> f = open('/root/Desktop/project/EtherType','r')
>>> lines = f.readlines()
>>> lines
['0x0800 \t2048 Internet Protocol version 4 (IPv4)\n', '0x0806 \t2054 Address Resolution Protocol (ARP)\n', ......
'''now we get the content of the file in python's tuple, the next thing we want to do is extract only the hex numbers'''
>>> for i in lines:
... print i[:7]
...
0x0800
0x0806
0x0842
0x22F3
0x6003
0x8035
0x809B
0x80F3
0x8100
0x8137
0x8138
0x8204
0x86DD
0x8808
0x8809
0x8819
0x8847
0x8848
0x8863
0x8864
0x8870
0x887B
0x888E
0x8892
0x889A
0x88A2
0x88A4
0x88A8
0x88AB
0x88CC
0x88CD
0x88E1
0x88E3
0x88E5
0x88F7
0x8902
0x8906
0x8914
0x8915
0x892F
0x9000
0x9100
0xCAFE
#the next thing we need to do is convert them into integer
for i in lines:
... print int(str(i[:7]),16)
...
2048
2054
2114
8947
24579
32821
32923
33011
33024
33079
33080
33284
34525
34824
34825
34841
34887
34888
34915
34916
34928
34939
34958
34962
34970
34978
34980
34984
34987
35020
35021
35041
35043
35045
35063
35074
35078
35092
35093
35119
36864
37120
51966
the next thing we need to do is to write this to our file, remmember in the actual code we have 'printed' the results,
in reality we have to save them to python variables to work with them, but it is a good practice to see them first
and then do the actual programming
you will now notice that we already have the file read in python, so the pointer is now in the last position. We have to
in a way create a new file with one extra column after the hex number
>>> a=[] #create a new tuple
>>> for i in lines:
... a.append( int(str(i[:7]),16))
...
>>> a
[2048, 2054, 2114, 8947, 24579, 32821, 32923, 33011, 33024, 33079, 33080, 33284, 34525, 34824, 34825, 34841,
34887, 34888, 34915, 34916, 34928, 34939, 34958, 34962, 34970, 34978, 34980, 34984, 34987, 35020, 35021, 35041,
35043, 35045, 35063, 35074, 35078, 35092, 35093, 35119, 36864, 37120, 51966]
>>> lines[0]
'0x0800 \tInternet Protocol version 4 (IPv4)\n'
>>> lines[:7]+str(2048)+lines[7:]
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
>>> lines[0]
'0x0800 \tInternet Protocol version 4 (IPv4)\n'
>>> type(lines[0])
<type 'str'>
>>> lines[:7]
['0x0800 \tInternet Protocol version 4 (IPv4)\n', .....
>>> lines[0][:7]+str(2048)+lines[0][7:]
'0x0800 2048\tInternet Protocol version 4 (IPv4)\n'
# now we got the answer for the first line, we need to do this for a;; the other lines as well
>>> file = open('/root/Desktop/project/EtherType2','a')
>>> dir(file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__',
'__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding',
'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline',
'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
>>> for i in range(43):
... final_print = lines[i][:7]+str(a[i])+lines[i][7:]
... file.write(final_print)
...
>>> file.close()
[root@localhost ~]# cat /root/Desktop/project/EtherType2
0x0800 2048 Internet Protocol version 4 (IPv4)
0x0806 2054 Address Resolution Protocol (ARP)
0x0842 2114 Wake-on-LAN[3]
---
this is the result that we wanted!
|
2ed97fb513d992577d399ce5673fb259469586e5 | AzhariRamadhan/python-cc | /bab-5.py | 3,114 | 4.0625 | 4 | #5-1 Coditional test
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? i predict False.")
print(car == 'audi')
#5-3 Alien Colors
print('\n5-3 Alien Colors')
alien_color = ['green', 'yellow', 'red']
if 'green' in alien_color:
print("The Player earned 5 points")
elif 'yellow' in alien_color:
print("The Player not earned anything")
elif 'red' in alien_color:
print("The Player not earned anything")
print("\nThe Player Passes the game")
#5-4 Alien Color Part 2
print("\nAlien Color Part 2")
if 'green' in alien_color:
print("Player earned 5 point")
if 'yellow' in alien_color:
print("Player earned 10 point")
if 'red' in alien_color:
print("Player earned 10 point")
#5-4 Alien Color Part 2 Else block
print('\n5-4 Else Block')
color_alien = 'red'
if 'yellow' in color_alien:
print("Player earned 5 Point")
else:
print("Player earned 10 Point")
#5-5 Alien Colors part 3
# Turn your if-else chain from Exercise 5-4 into an if-elif-else chain
print("\n5-5 Alien Color part 3")
if 'green' in color_alien:
print("Player earned 5 point")
elif 'yellow' in color_alien:
print("Player earned 10 point")
else:
print("Player earned 15 point")
#5-6
age = 15
if age < 2:
print('The person is a baby')
elif age >= 2 and age < 4:
print('The person is a toddler')
elif age >= 4 and age < 13:
print('The person is a kid')
elif age >= 13 and age < 20:
print('The person is a teenager')
elif age >= 20 and age < 65:
print('The person is an adult')
else:
print('The person is an elder')
#5-7 Favorite Fruits
favorite_fruits = ['banana', 'nectarine', 'peach', 'pears', 'apples']
if 'banana' in favorite_fruits:
print('You really like bananas!')
if 'peach' in favorite_fruits:
print('You really like peaches!')
if 'cantaloupe' in favorite_fruits:
print('You really like cantaloupe!')
if 'watermelon' in favorite_fruits:
print('You really like watermelon!')
if 'pears' in favorite_fruits:
print('You really like pears!')
#5-8 Hello Admin
print("\n5-8 Hello Admin")
list_names = ['admin', 'budi', 'lucinta luna', 'dedy', 'young lex', 'ria ricis']
user_logins = ['admin', 'jaden']
for user_login in user_logins:
if user_login in list_names:
print("Hello {}, would you like to see a status report").format(user_login)
else:
print("Hello {}, thank you for logging in again").format(user_login)
#5-10
current_users = ['admin', 'winston', 'ashley', 'eric', 'martin', 'ben']
new_users = ['Winston', 'ashley', 'dianne', 'xia', 'calvin']
for new_user in new_users:
if new_user.lower() in current_users:
print('You will need to enter a new username')
else:
print('The username is available')
#5-11
numbers = [v for v in range(1, 10)]
ordinal_suffix = ''
for number in numbers:
if number == 1:
ordinal_suffix = 'st'
elif number == 2:
ordinal_suffix = 'nd'
elif number == 3:
ordinal_suffix = 'rd'
else:
ordinal_suffix = 'th'
print(str(number) + ordinal_suffix)
|
15718a8f86410eeec008be7534b269300d2d8541 | rahuldbhadange/Python | /__Python/__Class and Object/python OOPS material/python OOPS material/26 removing attributes from a class del.py | 1,130 | 4.09375 | 4 | Removing attributes from a class:
Removing attributes from a object:
ex:
del test.a
del t1.b
here del cannot remove/delete an object
del:del is a keyword,which is used to decrease the reference count
of an object
Reference count:No of variables pointing to an object will give the
reference count
ex:1
class test:
t1=test() #here the variable t1 pointing to object, so R.C=1
del t1 #means it decreases the reference count by 1,so R.C=0
#whenever an object reference count(R.C) becomes zero
then the object is automatically deleted by garbage collector
whenever object is going to be deleted,then Destructor is called
i.e when RC becomes 0
ex:2
class test:
t1=test()
t2=t1 #here 2 variables(t1,t2) are pointing to same object,so RC=2
#here t1 and t2 storing address of same object
del t1 # Rc decreases to 1,i.e RC=1 ,destructor not called
del t2 # RC becomes 0,i.e RC=0 , destructor called
|
58180395526bdf082716c12a9175d84ca70145cb | AdamZhouSE/pythonHomework | /Code/CodeRecords/2500/60627/299402.py | 72 | 3.5625 | 4 | s = input()
if s=='[3,2,4,1]':
print('[4,2,4,3]')
else:
print(s) |
ade2a61bde172a6c94af422af6b521f72f0f08ce | jfiander/python | /collatz.py | 175 | 3.546875 | 4 | #!/usr/bin/python
import sys
n = 1
while True:
i = n
while i != 1:
if i % 2 == 1:
i = 3 * i + 1
else:
i = i / 2
sys.stdout.write('.')
n = n + 1
|
b24527531c831766b1fe6593c04e20dc97759327 | nagu1417/DemoPyGit | /Poly_DuckTypingExample1.py | 209 | 3.53125 | 4 | class Timing:
def startTime(self):
print("Starts at 9 am")
print("Ends at 7 pm")
class Cricket:
def time(self,time):
time.startTime();
t1=Timing();
c1=Cricket()
c1.time(t1)
|
bc39fbf75d49fd5f9bebb0f448a09769469f10d0 | Obukhova2001/practicum_1 | /task49.py | 1,220 | 4.09375 | 4 | """
Имя проекта: Boring-numpy
Номер версии: 1.0
Имя файла: practicum-1(1-101).py
Автор: 2019 © Д.А.Обухова, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 11/11/2020
Дата последней модификации: 11/11/2020
Связанные файлы/пакеты: numpy, random
Описание: Решение задач № 1-101 практикума №49
Дан одномерный массив числовых значений, насчитывающий N элементов. Определить, имеются ли в массиве два подряд идущих нуля.
#версия Python: 3.6
"""
import random
N = int(input("Введите количество элементов массива: "))
A = [random.randint(-5, 5) for i in range(N)]
print(A)
for i in range(N):
x=0
if A[i] == 0 and A[i-1] == 0:
x+=1
if x>0:
print("В массиве имеются два подряд идущих нуля")
else:
print("В массиве нет нулей идущих подряд")
|
9b7e278b107e63d141c84efa9cbf2c2ddb50358c | vchatchai/python101 | /exercise401.py | 102 | 4 | 4 |
values = input("Please insert value: ")
for value in values:
print(value*2, end = "")
print() |
101984ba8119b03efe384ec993ca4b89c7a3fd62 | nikhil1699/cracking-the-coding-interview | /python_solutions/chapter_04_trees_and_graphs/problem_04_08_first_common_ancestor.py | 2,148 | 3.90625 | 4 | """
Chapter 04 - Problem 08 - First Common Ancestor
Problem Statement:
Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree.
Avoid storing additional nodes in a data structure. Assume that this tree is not necessarily a binary search tree.
Assume that nodes in the tree do not have links to their parents.
Solution:
Traverse the tree recursively using a function whose return value indicates the presence of nodes 1 and 2
in the current node's left or right subtrees. The function also passes a reference to a Null node that is changed
to the identity of the first common ancestor if such a node exists. At each recursive call, the function returns one of
the following: "1" if the current node is an ancestor of node1, "2" if the current node is an ancestor of node2,
"3" if the current node is an ancestor of both nodes 1 and 2 or "0" in case the current node is an ancestor
of neither nodes 1 or 2. The function recurses until nodes1 and 2 are found and their presence is "bubbled up"
the tree in the form of the return values. If case "3" is encountered and the reference is still Null, the reference
is assigned the current node which by definition is the first common ancestor.
The terminating condition of the function is finding node1, node2, or Null.
Time complexity: O(N)
Space complexity: O(log(N)) if tree is balanced
"""
def first_common_ancestor_helper(currentNode, node1, node2, fca_reference):
if currentNode is None:
return 0
elif currentNode is node1:
return 1
elif currentNode is node2:
return 2
return_left = first_common_ancestor_helper(currentNode.left, node1, node2, fca_reference)
return_light = first_common_ancestor_helper(currentNode.right, node1, node2, fca_reference)
sum = return_left + return_light
if sum == 3 and fca_reference[0] is None:
fca_reference[0] = currentNode
return sum
def first_common_ancestor(head, node1, node2):
fca_reference = [None] # rely on mutable list to pass a reference
first_common_ancestor_helper(head, node1, node2, fca_reference)
return fca_reference[0]
|
01b33eddbb4ee68e2dcd7bf315b208588745f2d9 | junfeiZTE/pythonCode | /zip_lambda_map.py | 125 | 3.65625 | 4 | a=[1,2,3]
b=[4,5,6]
print(list(zip(a,b)))
fun=lambda x,y:x+y
print(fun(1,2))
print(list(map(fun,[1,2,3],[4,5,6])))
|
cf2e5dba684b43fd01db23597e70ace70b1b4f97 | Avyuktaj/pythonworks | /B using operators.py | 1,900 | 4.40625 | 4 | # i used operators
# i print used
# Python print(). The print() function prints the given object to the standard output device (screen) or to the text stream file
# operators used : arthematic and logical
# true or false statements
# variables used are x,y,a,b,p,q,p,r,m,n
# all the arthematic operators are given below :
# + Addition Adds values on either side of the operator. a + b = 30
# - Subtraction Subtracts right hand operand from left hand operand. a – b = -10
# * Multiplication Multiplies values on either side of the operator a * b = 200
# / Division Divides left hand operand by right hand operand b / a = 2
# % Modulus Divides left hand operand by right hand operand and returns remainder b % a = 0
# ** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20
# // Floor Division - − 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0
# all the logical operators are given below :
# == If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
# != If values of two operands are not equal, then condition becomes true. (a != b) is true.
# <> If values of two operands are not equal, then condition becomes true. (a <> b) is true. This is similar to != operator.
# > If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is not true.
# < If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true.
# >= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true.
# <= If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true.
x=5+10
y=5
y//=3
print(x)
print(y)
a=5
b=10
print(a>b)
p=3
q=3
r=p is q
print(r)
m=True
n=True
print(m and n)
|
28bc87eea4deff643ac1c3f873eec99aa5435409 | GURUIFENG9139/WEB2 | /threadingtest.py | 543 | 3.5625 | 4 | #!/usr/bin/python
# coding: utf-8
import threading
import time
'''
hhhhhhhh
'''
class MyThread(threading.Thread):
def run(self):
for i in range(0,5):
#print i
#print self.name
msg = '线程' + self.name + str(i)
print msg
print threading.activeCount()
# 单线程 注意 若调用start,则先执行主线程的,后执行子线程的 若调用run()方法,则相当于函数调用,按照程序的顺序执行
if __name__ == '__main__':
t = MyThread()
t.run()
|
3440d218f7e041576f5e1b1ba0d0242c62739e85 | froststars/aws-cfn-templates | /cfnutil/cfnutil/mapping.py | 713 | 3.703125 | 4 | # -*- encoding: utf-8 -*-
__author__ = 'kotaimen'
__date__ = '02/06/2017'
import json
import csv
def load_mapping(filename):
"""Load a mapping form JSON file"""
with open(filename) as f:
return json.load(f)
def load_csv_as_mapping(filename, key1, key2, value):
""" Load mapping from a CSV file
:param filename: name of the csv file
:param key1: column name for first mapping key
:param key2: column name for second mapping key
:param value: column name for second mapping value
"""
mapping = dict()
with open(filename) as f:
reader = csv.DictReader(f)
for row in reader:
mapping[row[key1]] = {key2: row[value]}
return mapping
|
68dd823dd261061a4b7fcae6bb23040f3e0afe84 | NicolasLagaillardie/Python | /hearth.py | 298 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 05 09:33:35 2013
@author: Nicolas
"""
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-5,5,100)
plt.plot(x,np.sin(x)) # on utilise la fonction sinus de Numpy
plt.ylabel('fonction sinus')
plt.xlabel("l'axe des abcisses")
plt.show() |
4962972263f2740e4c356a8ea2c40c8c2abf171d | StefanoBelli/ia1920 | /binsearch.py | 1,163 | 3.78125 | 4 | # versione iterativa
def binsearch(l, e):
low = 0
high = len(l) - 1
while low <= high:
mid = int(((high + low) / 2))
if e > l[mid]:
low = mid + 1
elif e < l[mid]:
high = mid - 1
else:
return e
return False
# prima versione ricorsiva,
# utilizza la notazione e[a:b:c] di python
# effettua un operazione di slicing sulla lista
def binsearch_recursive(l, e):
low = 0
high = len(l)
mid = int(((high + low) / 2))
if e > l[mid]:
return binsearch_recursive(l[mid:], e)
elif e < l[mid]:
return binsearch_recursive(l[:mid], e)
else:
return e
# seconda vesione ricorsiva,
# richiama se stessa modificando low e high
# la lista viene copiata e non vengono effettuate
# ulteriori modifiche
def binsearch_recursive_v2(l, e):
return __binsearch_rec_v2(l, e, 0, len(l))
def __binsearch_rec_v2(l, e, low, high):
mid = int(((high + low) / 2))
if e > l[mid]:
return __binsearch_rec_v2(l, e, mid + 1, high)
elif e < l[mid]:
return __binsearch_rec_v2(l, e, low, mid - 1)
else:
return e
|
72d3de7dc49d3e36a6a8fe11d973e426397a0f8b | mmassom96/IEEE_Xtreme_5.0 | /problem_A.py | 1,501 | 4.3125 | 4 | import numpy
def pearson (x, y):
if (len(x) != len(y)):
# if the two data sets are not of equal length, then Pearson's Correlation Coefficient
# cannot be calculated so the function will end
print("Error: length of set X is not equal to length of set Y.")
return
setLen = len(x) # assigns the length of x and y to a variable
stdX = numpy.std(x) # calculates the standard deviation of the set X
stdY = numpy.std(y) # calculates the standard deviation of the set Y
avgX = numpy.mean(x) # calculates the mean of the set X
avgY = numpy.mean(y) # calculates the mean of the set X
sum = 0 # sum is a variable used to calculate the numberator of Pearson's Correlation Coefficient
for i in range(setLen):
sum = sum + ((x[i] - avgX) * (y[i] - avgY))
num = sum / setLen # num is the numerator of Pearson's Correlation Coefficient
den = stdX * stdY # den is the denominator of Pearson's Correlation Coefficient
return num / den
# for listX and listY, each value in the array listX makes a pair with the corresponding value
# in the array listY Example: listX[0] and listY[0] make (14, 2)
listX = [14, 16, 27, 42, 39, 50, 83] # listX is the set of X values
listY = [2, 5, 7, 9, 10, 13, 20] # listY is the set of Y values
print(pearson(listX, listY)) # executes the function pearson() using listX and listY and prints the result |
f4391fd8d4fe2cf0aa1cee311f6da8e2c387b8d2 | dionysos1/ISCRIP | /week1/mars.py | 928 | 3.75 | 4 | import math
#gebruiker voert het aantal sol dagen in die hij wil weten in mars dagen
input = int(input("aantal hele dagen in sol: "))
# zet het aantal sol om in mars seconden
# methode 1
# seconds = (input * 35.244) + (input * 60 * 39) + (input * 60 * 60 * 24)
# methode 2
seconds = (input * 86400) * 1.02749125170
# kijk hoe vaak dagen in het aantal seconden passen en het daarna van het geheel aftrekken.
days = math.floor(seconds / (60*60*24))
seconds -= (60*60*24) * days
# kijk hoe vaak uren in het overig aantal seconden passen en het daarna van het geheel aftrekken.
hrs = math.floor(seconds / (60*60))
seconds -= 3600 * hrs
# kijk hoe vaak minuten in het overig aantal seconden passen en het daarna van het geheel aftrekken.
mins = math.floor(seconds / 60)
seconds -= 60 * mins
print("{0} sol = {1} dagen {2} uren {3} minuten {4} seconden".format(input, days, hrs, mins, round(seconds))) |
2bff8bb965aa4e19850b5fac318efdb9a6099b31 | pengjinfu/Python3 | /Python05/07--函数的返回值.py | 504 | 3.5625 | 4 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
# Authour:Dreamer
# Tmie:2018.6.11
# 函数的返回值,就是把函数的执行结束返回出来(如果需要使用执行结果,就把它给一个变量)
def func_sum(num1, num2):
sum_num = num1 + num2
# print(sum_num)
return sum_num # return它的作用返回函数的执行结果,只能在函数内部使用
# 如果函数没有写返回值,默认返回函数就是None
result = func_sum(1, 4)
print(result)
# print("*" * result)
|
55f235d755c6565242afbb4b9c9cd40dc65706ad | honey-kingdom/python | /OOP/1_Classes_and_Instances.py | 1,793 | 4.65625 | 5 | """
Python OOP Tutorial 1: Classes and Instances
"""
class Employee:
pass
emp_1 = Employee()
emp_2 = Employee()
print(emp_1)
print(emp_2)
emp_1.first = 'Corey'
emp_1.last = 'Schafer'
emp_1.email = '[email protected]'
emp_1.pay = 50000
emp_2.first = 'Test'
emp_2.last = 'User'
emp_2.email = '[email protected]'
emp_2.pay = 60000
print(emp_1.email)
print(emp_2.email)
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'User', 60000)
print(emp_1.email)
print(emp_2.email)
print('{} {}'.format(emp_1.first, emp_1.last))
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'User', 60000)
print(emp_1.fullname()) # instance passes itself on the background
# transformed into
print(Employee.fullname(emp_1)) # explicitly passes an instance
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
# instead of def fullname(self):
def fullname():
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'User', 60000)
# print(emp_2.fullname()) # TypeError: takes 0 positional arguments but 1 was given
|
47c6eff3713c348e45d79bfb2beea07e7d0e7065 | pascalmcme/myprogramming | /week7/labjson.py | 249 | 3.65625 | 4 | import json
filename = "testdict.json"
exampleDict = dict(
name = "Mary", age = 24, grades = [1,2,3]
)
def writeDict(obj):
with open(filename, "w") as f:
json.dump(obj,f) # two arguemts - the dict and the file name
writeDict(exampleDict) |
1212da7d117b990909f06ddbfa947264806c8b3f | moneyDboat/offer_code | /50_数组中重复的数字.py | 766 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
# @Author : captain
# @Time : 2018/10/30 1:20
# @Ide : PyCharm
"""
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
if not numbers:
return False
i = 0
while i < len(numbers):
if numbers[i] == i:
i += 1
continue
if numbers[numbers[i]] == numbers[i]:
duplication[0] = numbers[i]
return True
else:
temp = numbers[i]
numbers[i] = numbers[numbers[i]]
numbers[temp] = temp
return False |
a671d16233c640548177db2fd5ea4b07935385c1 | Jochizan/courses-python | /palindromes.py | 232 | 3.828125 | 4 | s = input('Ingrese una palabra a evaluar: ')
s = s.replace(' ', '')
s = s.lower()
tmp = s[::-1]
if tmp == s:
print("Es palindromo")
else:
print("NO es palindromo")
# codigo simple para verficar un palindromo con python :)
|
03f5132d64891b21ad81190616007f52d29b7927 | Midnight1Knight/HSE-course | /FifthWeek/Task6.py | 170 | 3.640625 | 4 | def null(n):
s = 0
while n != 0:
num = int(input())
if num == 0:
s += 1
n -= 1
return s
n = int(input())
print(null(n))
|
346c798b54a90e3e7774b184980bcff472daa170 | hz336/Algorithm | /LintCode/DS - Build In/Integer to Roman.py | 714 | 3.90625 | 4 | """
Given an integer, convert it to a roman numeral.
The number is guaranteed to be within the range from 1 to 3999.
https://en.wikipedia.org/wiki/Roman_numerals
"""
class Solution:
"""
@param n: The integer
@return: Roman representation
"""
def intToRoman(self, n):
# write your code here
nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
roman = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
s = ''
digit = 0
while n:
times = n // nums[digit]
n -= nums[digit] * times
s += roman[digit] * times
digit += 1
return s
|
561a6fdf1cfd70dfea345b8e1422e2f26ee35d50 | jaly50/LeetCode-python | /maxProfit1.py | 600 | 3.78125 | 4 |
# @param {integer[]} prices
# @return {integer}
# Jiali Chen
# 5/28/2015 Thu 14:42 am
# 121 Best Time to Buy and Sell Stock
# 维护一个最小值,最大值是减去到当前为止最小值
def maxProfit(prices):
n = len(prices)
if n<2:
return 0
minV = None
maxV = 0
for ele in prices:
if minV==None:
minV = ele
else:
minV = min(minV,ele)
maxV=max(maxV, ele-minV)
# print maxV
return maxV
if __name__ == '__main__':
maxProfit([1,8])
|
7478f4da3a323c88eadcedb0334b67485f9f496d | ArtisanTinkerer/scavenger | /main.py | 1,351 | 3.65625 | 4 | import csv
import random
from fpdf import FPDF
def load_all_items() -> list:
"""Real all items from the file into alist"""
with open('items.txt') as file:
items = file.read().splitlines()
return items
def input_integer() -> int:
"""Obtain an integer from the user"""
valid_integer = None
while valid_integer is None:
try:
valid_integer = int(input('How many items do you require?'))
except ValueError:
print('Please enter an integer.')
continue
return valid_integer
def select_items(number_of_items: int, all_items: list) -> list:
"""Select random items from the list"""
selected_items = random.choices(all_items, k=number_of_items)
return selected_items
def make_pdf(selected_items):
"""Create a PDF file"""
pdf = FPDF('P', 'mm', 'A4')
pdf.add_page()
pdf.set_font('Arial', 'B', 16)
pdf.cell(40, 10, 'Scavenger Hunt',ln=1)
for item in selected_items:
pdf.cell(40, 10, item, ln=0)
pdf.cell(40, 10, '', ln=0)
pdf.cell(20, 10, '', ln=1, border=1)
pdf.output('hunt.pdf', 'F')
def main():
all_items = load_all_items()
number_of_items = input_integer()
selected_items = select_items(number_of_items, all_items)
print(selected_items)
make_pdf(selected_items)
main()
|
feaa9efb33f33db3bef08899138de5b02a698647 | buttermilkcake/Python_Coding | /Python_Coding/ch_11_ex_11_3_employee.py | 1,144 | 4.125 | 4 | class People():
""""A simple attempt to represent some information."""
def __init__(self, name, salary):
"""Initialize people attributes."""
self.name = name
self.salary = salary
self.new_raise = 0
def get_descriptive_info(self):
"""Return a neatly formatted bundle of info."""
long_stuff = self.name + ' ' + str(self.salary)
return long_stuff.title()
def give_raise(self):
"""Print a statement showing the person's salary increase."""
print("This person is getting an increase of " + str(self.new_raise) +
" and their new salary is " + str(self.new_raise + self.salary) +
".")
def update_raise(self, money):
"""Set the salary to the given amount."""
self.new_raise = money
def increment_raise(self, monies):
"""Add the raise amount to the new_raise amount."""
self.new_raise += monies
my_rich_people = People('sally', 60000)
print(my_rich_people.get_descriptive_info())
my_rich_people.increment_raise(5000)
my_rich_people.give_raise()
|
d3f9017f90001ab495ac238d0855b27908c028b9 | IvanWoo/coding-interview-questions | /puzzles/bst_find_modes.py | 1,588 | 3.96875 | 4 | # https://leetcode.com/problems/find-mode-in-binary-search-tree/
"""
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to the node's key.
The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
Both the left and right subtrees must also be binary search trees.
For example:
Given BST [1,null,2,2],
1
\
2
/
2
return [2].
Note: If a tree has more than one mode, you can return them in any order.
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
"""
from typing import List
from puzzles.utils import TreeNode
class FindModes:
def __init__(self):
self.modes = []
self.prev = None
self.count = 0
self.max_count = 0
def find_modes(self, root: TreeNode) -> List[int]:
self.traversal(root)
return self.modes
def traversal(self, node):
if not node:
return
self.traversal(node.left)
if self.prev != node.val:
self.count = 1
else:
self.count += 1
if self.count == self.max_count:
self.modes.append(node.val)
elif self.count > self.max_count:
self.max_count = self.count
self.modes = [node.val]
self.prev = node.val
self.traversal(node.right)
|
8f76ebc011e06da35def50b4f05fff642d11324f | gitmengzh/100-Python-exercises | /100/q41.py | 247 | 3.96875 | 4 | '''
使用给定的元组(1,2,3,4,5,6,7,8,9,10)定义一个函数,第一行打印前一半数值,第二行打印第二半数值
'''
def printHarfTuple():
t = (1,2,3,4,5,6,7,8,9,10)
print(t[:5])
print(t[5:])
test = printHarfTuple()
|
eec319b2ec3f567250cc877422b086538e0974cf | miriamlam1/csc349 | /asgn1-miriamlam1/sort.py | 2,142 | 4.125 | 4 | import sys
import time
# A : unsorted list
# Selection Sort
# repeatedly selects the smallest element from the unsorted elements
def selection_sort(A):
for i in range(len(A)):
mini = i
for j in range(i+1, len(A)):
if A[j] < A[mini]:
mini = j
A[mini], A[i] = A[i], A[mini]
# Insertion Sort
# repeatedly inserts the next unsorted element into a sorted section
def insertion_sort(A):
for i in range(1, len(A)):
curr = A[i]
j = i
while j > 0 and A[j-1] > curr:
A[j] = A[j-1]
j-=1
A[j] = curr
# Merge Sort
# recursively sorts the two halves of a sequence,
# then merges the sorted halves back together
def merge_sort(A):
if len(A) > 1:
mid = len(A)//2
L = A[:mid]
R = A[mid:]
merge_sort(L) # left
merge_sort(R) # right
i = j = k = 0 # i = L index j = R index k = A index
while (i < len(L) and j < len(R)):
if L[i] < R[j]:
A[k]=L[i]
i+=1
else:
A[k]=R[j]
j+=1
k+=1
while i < len(L):
A[k]=L[i]
i+=1
k+=1
while j < len(R):
A[k]=R[j]
j+=1
k+=1
def make_list(fname):
A = (open(fname)).read()
A = A.strip()
A = A.split(", ")
A = [int(i) for i in A]
return A
def main():
A = make_list(sys.argv[1])
time1 = time.time()
selection_sort(A)
time2 = time.time()
print("Selection Sort", "({:.2f}".format((time2-time1)*1000), "ms):", str(A)[1:-1])
A = make_list(sys.argv[1])
time1 = time.time()
insertion_sort(A)
time2 = time.time()
print("Insertion Sort", "({:.2f}".format((time2-time1)*1000), "ms):", str(A)[1:-1])
A = make_list(sys.argv[1])
time1 = time.time()
merge_sort(A)
time2 = time.time()
print("Merge Sort ", "({:.2f}".format((time2-time1)*1000), "ms):", str(A)[1:-1])
if __name__ == "__main__":
main() |
7797e0df5befff3fc93837cd5d8cc92300a29d49 | wslwlm/leetcode-practice | /103. Binary Tree Zigzag Level Order Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.py | 3,680 | 3.671875 | 4 | # 题目地址: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
# Runtime: 32 ms Memory Usage: 12.7 MB
# 借用层次遍历的做法, 用flag记录是否反转(可以简化为用奇偶判定),
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
q = []
q.append(root)
res = []
flag = True
while q:
q_1 = q[:]
temp = []
for node in q_1:
q.pop(0)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
temp.append(node.val)
if len(temp):
if flag:
res.append(temp)
flag = False
else:
temp.reverse()
res.append(temp)
flag = True
return res
# RunTime: 12ms
# 思路: is_order_left标示当前为从左到右(数组尾部)还是从右到左(数组头部).
# 两个队列, node_queue(层次遍历), level_list(添加每一层结果),
from collections import deque
class Solution:
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
ret = []
level_list = deque()
if root is None:
return []
# start with the level 0 with a delimiter
node_queue = deque([root, None])
is_order_left = True
while len(node_queue) > 0:
# 出队
curr_node = node_queue.popleft()
if curr_node:
if is_order_left:
# 放在数组尾部
level_list.append(curr_node.val)
else:
# 放在数组头部
level_list.appendleft(curr_node.val)
if curr_node.left:
node_queue.append(curr_node.left)
if curr_node.right:
node_queue.append(curr_node.right)
else:
# we finish one level
ret.append(level_list)
# add a delimiter to mark the level
# 入队一个None来标识这一层的结束
if len(node_queue) > 0:
node_queue.append(None)
# prepare for the next level
level_list = deque()
is_order_left = not is_order_left
return ret
# RunTime: 24ms
# 思路: 对一棵树进行之字形遍历其实对其子树进行之字形遍历
# 当前层次为偶数时,将当前节点放到当前层的结果数组尾部
# 当前层次为奇数时,将当前节点放到当前层的结果数组头部
# 递归对左子树进行之字形遍历,层数参数为当前层数+1
# 递归对右子树进行之字形遍历,层数参数为当前层数+1
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
res=[]
search(root,0,res)
return res
def search(root,level,res):
if root==None:
return
if len(res)<=level:
res.append([])
if (level%2==0) :
res[level].append(root.val)
else:
res[level].insert(0,root.val)
search(root.left,level+1,res)
search(root.right,level+1,res) |
01703f0bc3dcd0b78ad6c6255ab29367566388c1 | afuous/surim-2018 | /code/ap-continuous.py | 1,060 | 3.546875 | 4 | import numpy as np
import itertools
import matplotlib.pyplot as plt
from random import random
def count_3APs(A,N):
total = 0
for a in range(0, N):
for b in range(1, (N-1)//2):
total += A[a] * A[(a + b) % N] * A[(a + 2 * b) % N]
return total
def main():
nsamples = 1000000
N = 23
x = 10
AP3counts = []
for a in range(nsamples):
if a % 10000 == 0:
print("\r" + str(a), end="")
A = []
for _ in range(N):
A.append(random())
AP3counts.append(count_3APs(A,N).real * x)
print("\rdone ")
minAPct = int(min(AP3counts))
maxAPct = int(max(AP3counts))
all_counts = np.zeros(maxAPct-minAPct+1)
for ct in AP3counts:
all_counts[int(ct) - minAPct] += 1.
plt.plot([b/x for b in range(minAPct, maxAPct+1)], all_counts / nsamples)
plt.xlabel("\"Number of 3APs\"")
plt.ylabel("Frequency")
plt.title("Histogram of continuous 3APs in subsets of Z/" + str(N) + "Z")
plt.show()
if __name__ == "__main__":
main()
|
3b03f33d0b47f400532e149f5cda380ed5d1a69b | petsc/petsc | /src/binding/petsc4py/demo/legacy/taosolve/rosenbrock.py | 3,631 | 3.578125 | 4 | """
This example demonstrates the use of TAO for Python to solve an
unconstrained minimization problem on a single processor.
We minimize the extended Rosenbrock function::
sum_{i=0}^{n/2-1} ( alpha*(x_{2i+1}-x_{2i}^2)^2 + (1-x_{2i})^2 )
"""
try: range = xrange
except NameError: pass
# the two lines below are only
# needed to build options database
# from command line arguments
import sys, petsc4py
petsc4py.init(sys.argv)
from petsc4py import PETSc
class AppCtx(object):
"""
Extended Rosenbrock function.
"""
def __init__(self, n=2, alpha=99.0):
self.size = int(n)
self.alpha = float(alpha)
def formObjective(self, tao, x):
#print 'AppCtx.formObjective()'
alpha = self.alpha
nn = self.size // 2
ff = 0.0
for i in range(nn):
t1 = x[2*i+1] - x[2*i] * x[2*i]
t2 = 1 - x[2*i];
ff += alpha*t1*t1 + t2*t2;
return ff
def formGradient(self, tao, x, G):
#print 'AppCtx.formGradient()'
alpha = self.alpha
nn = self.size // 2
G.zeroEntries()
for i in range(nn):
t1 = x[2*i+1] - x[2*i] * x[2*i]
t2 = 1 - x[2*i];
G[2*i] = -4*alpha*t1*x[2*i] - 2*t2;
G[2*i+1] = 2*alpha*t1;
def formObjGrad(self, tao, x, G):
#print 'AppCtx.formObjGrad()'
alpha = self.alpha
nn = self.size // 2
ff = 0.0
G.zeroEntries()
for i in range(nn):
t1 = x[2*i+1] - x[2*i] * x[2*i]
t2 = 1 - x[2*i];
ff += alpha*t1*t1 + t2*t2;
G[2*i] = -4*alpha*t1*x[2*i] - 2*t2;
G[2*i+1] = 2*alpha*t1;
return ff
def formHessian(self, tao, x, H, HP):
#print 'AppCtx.formHessian()'
alpha = self.alpha
nn = self.size // 2
idx = [0, 0]
v = [[0.0, 0.0],
[0.0, 0.0]]
H.zeroEntries()
for i in range(nn):
v[1][1] = 2*alpha
v[0][0] = -4*alpha*(x[2*i+1]-3*x[2*i]*x[2*i]) + 2
v[1][0] = v[0][1] = -4.0*alpha*x[2*i];
idx[0] = 2*i
idx[1] = 2*i+1
H[idx,idx] = v
H.assemble()
# access PETSc options database
OptDB = PETSc.Options()
# create user application context
# and configure user parameters
user = AppCtx()
user.size = OptDB.getInt ( 'n', user.size)
user.alpha = OptDB.getReal('alpha', user.alpha)
# create solution vector
x = PETSc.Vec().create(PETSc.COMM_SELF)
x.setSizes(user.size)
x.setFromOptions()
# create Hessian matrix
H = PETSc.Mat().create(PETSc.COMM_SELF)
H.setSizes([user.size, user.size])
H.setFromOptions()
H.setOption(PETSc.Mat.Option.SYMMETRIC, True)
H.setUp()
# pass the following to command line:
# $ ... -methods nm,lmvm,nls,ntr,cg,blmvm,tron
# to try many methods
methods = OptDB.getString('methods', '')
methods = methods.split(',')
for meth in methods:
# create TAO Solver
tao = PETSc.TAO().create(PETSc.COMM_SELF)
if meth: tao.setType(meth)
tao.setFromOptions()
# solve the problem
tao.setObjectiveGradient(user.formObjGrad)
tao.setObjective(user.formObjective)
tao.setGradient(user.formGradient)
tao.setHessian(user.formHessian, H)
#app.getKSP().getPC().setFromOptions()
x.set(0) # zero initial guess
tao.setSolution(x)
tao.solve()
tao.destroy()
## # this is just for testing
## x = app.getSolution()
## G = app.getGradient()
## H, HP = app.getHessian()
## f = tao.computeObjective(x)
## tao.computeGradient(x, G)
## f = tao.computeObjectiveGradient(x, G)
## tao.computeHessian(x, H, HP)
|
b7bd5a1abb004a202813d4fa7737ab78d4affca6 | Ranyaron/euler | /euler2.py | 683 | 3.875 | 4 | '''Каждый следующий элемент ряда Фибоначчи получается при сложении двух предыдущих.
Начиная с 1 и 2, первые 10 элементов будут: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Найдите сумму всех четных элементов ряда Фибоначчи, которые не превышают четыре миллиона.'''
a = 1
b = 1
c = 0
while True:
if a > 0:
a += b
b += a
if b >= 4000000:
break
else:
if (a % 2 == 0):
c += a
if (b % 2 == 0):
c += b
print(c)
|
7675274b328e6fa6ed58753a0119be04fa84407c | cybermin/pythonturtle | /Day1/Ex05.py | 408 | 3.984375 | 4 | """
python 예제 : N각형 그리기
"""
import turtle
# 입력
line = input("변의 길이를 입력하세요.")
# 입력된 내용은 문자열로 취급됨으로 정수로 변환
line = int(line)
n = input("n 각형의 n을 입력하세요.")
n = int(n)
# 다각형 그리기
for i in range(n):
turtle.forward(line)
turtle.left(360/n)
# 화면 유지
turtle.exitonclick() |
ad8db100079544c7d73f96395f00f42f591f5ace | rajarathod214/Python | /upper_lower.py | 146 | 3.6875 | 4 | #!usr/bin/python
message=raw_input("What is your name ?")
print message
print(message.lower())
print(message.upper())
print(message.swapcase())
|
9665209d2550bbb4bc442d9e5e3b365462c4b99f | xsupremeyx/GUI_Calculator_By_Supreme | /Calculator/MainCalc.py | 6,794 | 3.859375 | 4 | # Import
from tkinter import *
# Program Structure start
window = Tk()
window.title("Calculator")
color1 = '#%02x%02x%02x' % (217, 228, 241)
window.configure(bg='grey')
'''Structure continued ahead'''
# Program's Variables
op=1
operand1=[]
operator=[]
operand2=[]
sum=0
# Functions
def click(a):
global operand1
global operand2
global operator
global op
if op==0:
global sum
sum=str(sum)
digits = [int(x) for x in str(sum)]
operand1=[]
operand1.extend(digits)
operator=[]
operand2=[]
op=1
else:
pass
if a=='.':
print("Coming soon")
else:
pass
numentry.insert(END,a)
if op==1:
operand1.append(int(a))
print(operand1,operator,operand2)
print(op)
elif op==2:
op+=1
operand2.append(int(a))
print(operand1,operator,operand2)
print(op)
elif op==3:
operand2.append(int(a))
print(operand1,operator, operand2)
print(op)
def click2(a):
global operand1
global operand2
global operator
global op
if op==0:
global sum
sum = str(sum)
digits = [int(x) for x in str(sum)]
operand1 = []
operand1.extend(digits)
operator=[]
operator.append(a)
operand2 = []
numentry.insert(END, a)
op+=2
else:
pass
if op==1:
numentry.insert(END, a)
operator.append(a)
op+=1
elif op==2:
print("error")
print(operand1, operator, operand2)
print(op)
def delete():
global operand1
global operand2
global op
if op==0:
clear()
else:
pass
if op==1:
lenght = len(operand1)
if lenght==0:
print("error")
else:
strstr= numentry.get()
numentry.delete(0,END)
numentry.insert(0,strstr[0:len(strstr)-1])
operand1.pop(lenght-1)
print(operand1,operator,operand2)
print(op)
elif op==2:
op-=1
strstr = numentry.get()
numentry.delete(0, END)
numentry.insert(0, strstr[0:len(strstr) - 1])
print(operand1,operator, operand2)
print(op)
elif op==3:
lenght = len(operand2)
if lenght==0:
lenght = len(operator)
op-=2
strstr = numentry.get()
numentry.delete(0, END)
numentry.insert(0, strstr[0:len(strstr) - 1])
operator.pop(lenght-1)
print(operand1,operator,operand2)
print(op)
elif lenght>0:
strstr = numentry.get()
numentry.delete(0, END)
numentry.insert(0, strstr[0:len(strstr) - 1])
operand2.pop(lenght-1)
print(operand1, operator,operand2)
print(op)
def clear():
numentry.delete(0,END)
global operand1
global operand2
global operator
global op
operand1=[]
operand2=[]
operator=[]
op=1
def submit_answer():
global op
global sum
num1=""
num2=""
for item in operand1:
item=str(item)
num1+=item
for item in operand2:
item=str(item)
num2+=item
num1=int(num1)
num2=int(num2)
op=0
if '+' in operator:
sum = num1+num2
numentry.delete(0, END)
numentry.insert(END, sum)
if '-' in operator:
sum = num1-num2
numentry.delete(0, END)
numentry.insert(END, sum)
if '*' in operator:
sum = num1*num2
numentry.delete(0, END)
numentry.insert(END, sum)
if '/' in operator:
sum = num1//num2
numentry.delete(0, END)
numentry.insert(END, sum)
# Images:
Num1 = PhotoImage(file="Calculator_Num1.png")
Num2 = PhotoImage(file="Calculator_Num2.png")
Num3 = PhotoImage(file="Calculator_Num3.png")
Num4 = PhotoImage(file="Calculator_Num4.png")
Num5 = PhotoImage(file="Calculator_Num5.png")
Num6 = PhotoImage(file="Calculator_Num6.png")
Num7 = PhotoImage(file="Calculator_Num7.png")
Num8 = PhotoImage(file="Calculator_Num8.png")
Num9 = PhotoImage(file="Calculator_Num9.png")
Num0 = PhotoImage(file="Calculator_Num0.png")
Plus = PhotoImage(file="Calculator_Plus.png")
Minus = PhotoImage(file="Calculator_Minus.png")
Division = PhotoImage(file="Calculator_Div.png")
Multi = PhotoImage(file="Calculator_Mult.png")
Point = PhotoImage(file="Calculator_Point.png")
Backspace = PhotoImage(file="Calculator_Backspace.png")
Equal = PhotoImage(file="Calculator_Submit.png")
# Program GUI Structure
Label(window,text="Entry:",bg="black",fg="yellow").grid(row=0,column=0,sticky='wnse')
numentry=Entry(window,bg="light gray",fg="black")
numentry.grid(row=0,column=1,columnspan=5,sticky='wnse')
Label(window,text="Don't use Decimals,Coming soon.",bg="black",fg="yellow").grid(row=6,column=0,columnspan=5,sticky='wnse')
Button(window,image= Num1,command=lambda: click("1")).grid(row=1,column=0,sticky='w')
Button(window,image= Num2,command=lambda: click("2")).grid(row=1,column=1,sticky='wnse')
Button(window,image= Num3,command=lambda: click("3")).grid(row=1,column=2,sticky='w')
Button(window,image= Plus,command=lambda: click2("+")).grid(row=1,column=3,sticky='w')
Button(window,image= Num4,command=lambda: click("4")).grid(row=2,column=0,sticky='w')
Button(window,image= Num5,command=lambda: click("5")).grid(row=2,column=1,sticky='wnse')
Button(window,image= Num6,command=lambda: click("6")).grid(row=2,column=2,sticky='w')
Button(window,image= Minus,command=lambda: click2("-")).grid(row=2,column=3,sticky='w')
Button(window,image= Num7,command=lambda: click("7")).grid(row=3,column=0,sticky='w')
Button(window,image= Num8,command=lambda: click("8")).grid(row=3,column=1,sticky='wnse')
Button(window,image= Num9,command=lambda: click("9")).grid(row=3,column=2,sticky='w')
Button(window,image= Multi,command=lambda: click2("*")).grid(row=3,column=3,sticky='w')
Button(window,image= Num0,command=lambda: click("0")).grid(row=4,column=0,columnspan=2,sticky='w')
Button(window,image= Point,command=lambda: click(".")).grid(row=4,column=2,sticky='w')
Button(window,image= Division,command=lambda: click2("/")).grid(row=4,column=3,sticky='wnse')
Button(window,image=Backspace,command=lambda: delete()).grid(row=1,rowspan=2,column=4,stick='wnse')
Button(window,image=Equal,command=lambda: submit_answer()).grid(row=3,rowspan=2,column=4,stick='wnse')
Button(window,text="Clear",command=lambda: clear()).grid(row=5,column=0,columnspan=5,stick='wnse')
window.mainloop() |
04417545dfa7a74e9e43633ba2d5e2b0bb033f98 | elsa1302/code_project | /GUI.py | 6,493 | 3.515625 | 4 | from tkinter import *
import tkinter as tk
import serial
import Execution_stm as gfe
class GuiWindow:
"""The Class GUIWindow includes all the front end features of the GUI """
def __init__(self, root, width, height, stm_protocols, perf_tests, title):
self.root = root
self.width = width
self.height = height
self.stm_protocols = stm_protocols
self.perf_tests = perf_tests
self.title = title
self.protocol_string_var = ""
self.graph_var = 0
self.data_var = 1
self.perf_tests_string_var = ""
def gui_features(self):
"""Entry point to the class: GUIWindow(). All functions are invoked from here."""
self.root.geometry(self.width + "x" + self.height)
self.root.resizable(0, 0)
self.root.title(self.title)
self.gui_win_position()
self.gui_label_frame()
def gui_win_position(self):
"""Position the GUI in the center of the window screen. The height and width is hard coded in main function"""
# Gets both half the screen width/height and window width/height
position_right = int(self.root.winfo_screenwidth() / 2 - int(self.width) / 2)
position_down = int(self.root.winfo_screenheight() / 2 - int(self.height) / 2)
# Positions the window in the center of the page.
self.root.geometry("+{}+{}".format(position_right, position_down))
def gui_protocol_dropdown(self, protocol_label_frame):
self.protocol_string_var = tk.StringVar(protocol_label_frame) # variable pointing
self.protocol_string_var.set("none") # default
protocol_drop_down = tk.OptionMenu(protocol_label_frame, self.protocol_string_var,
*self.stm_protocols)
protocol_drop_down.config(width=25)
protocol_drop_down.place(x=20, y=20)
def gui_perf_test_dropdown(self, perf_test_label_frame):
self.perf_tests_string_var = tk.StringVar(perf_test_label_frame)
self.perf_tests_string_var.set("none")
perf_tests_drop_down = tk.OptionMenu(perf_test_label_frame, self.perf_tests_string_var,
*self.perf_tests)
perf_tests_drop_down.config(width=23)
perf_tests_drop_down.place(x=20, y=20)
def gui_graph_checkbox(self, graph_label_frame):
"""The function creates a checkbox on GUI and calls function checkbox_graph to implement visualization using
graphs """
"graph_var variable points to the checkbox object"
self.graph_var = tk.IntVar(value=0)
"""data_var variable points to the text object"""
graph_cb = tk.Checkbutton(graph_label_frame, text='Generate graph', variable=self.graph_var,
command=lambda: self.checkbox_graph(self.graph_var))
graph_cb.place(x=20, y=22)
def gui_dis_textbox(self, dis_label_frame):
self.data_var = tk.IntVar(value=1)
data = tk.Text(master=dis_label_frame, width='41', height='6')
data.pack()
if self.data_var.get():
ser = serial.Serial(port='COM3', baudrate=9600, timeout=None)
ser.isOpen()
data.insert(END, "\n")
serial_data = ser.readline().decode()
data.insert(END, ser.readline())
ser.close()
def checkbox_graph(self, graph_var):
"""Fetches the value in checkbox to generate graph. Invokes function in Class: Execution_stm"""
print(graph_var)
if self.graph_var.get():
print("Graph clicked")
else:
print("Graph unclicked")
def gui_exec_button(self,button_label_frame):
"""The function gui_exec_button displays two buttons: Run and Reset on the GUI.
Button *Run*: calls the functions in class Execution_stm to execute tests based on protocol and
test user selects.
Button *Reset*: Function clear is invoked. The function clears the changes in GUI and sets the selection
to default value.
:param self: """
test_result_button = tk.Button(master=button_label_frame, text="Run ", width='17',
command=gfe.Execute(self.graph_var, self.perf_tests_string_var,
self.data_var).stm_execute)
test_result_button.grid(row=0, column=0, padx='20', pady='10', sticky='W')
reset_button = tk.Button(master=button_label_frame, text="Reset to default", width='17', command=self.clear)
reset_button.grid(row=0, column=1, padx='20', pady='10', sticky='W')
def clear(self):
"""Implements Button Reset functionality. The function clears the changes in GUI and sets the selection to
default value """
self.protocol_string_var.set("Protocol 1")
self.perf_tests_string_var.set("Execution Time")
self.graph_var.set(0)
self.data_var.set(0)
def gui_label_frame(self):
"""The function gui_label_frame divides the GUI into various frames, each having a feature.
A label frame for each category generates an object, which is passed over to the respective functions."""
protocol_label_frame = tk.LabelFrame(self.root, text="STM 32 Protocols", width=340, height=80)
protocol_label_frame.grid(row=0, column=0, padx='20', pady='10', sticky='W')
perf_test_label_frame = tk.LabelFrame(self.root, text="Performance Test", width=340, height=80)
perf_test_label_frame.grid(row=1, column=0, padx='20', pady='10', sticky='W')
graph_label_frame = tk.LabelFrame(self.root, width=340, height=80)
graph_label_frame.grid(row=2, column=0, padx='20', pady='0', sticky='W')
dis_label_frame = tk.LabelFrame(self.root, text="Display Output", width=340, height=80)
dis_label_frame.grid(row=3, column=0, padx='20', pady='0', sticky='W')
button_label_frame = tk.LabelFrame(self.root, text="Execute test", width=340, height=80)
button_label_frame.grid(row=4, column=0, padx='20', pady='0', sticky='W')
'''Functions to display each feature. Label frame object passed as parameter'''
self.gui_protocol_dropdown(protocol_label_frame)
self.gui_perf_test_dropdown(perf_test_label_frame)
self.gui_graph_checkbox(graph_label_frame)
self.gui_dis_textbox(dis_label_frame)
self.gui_exec_button(button_label_frame)
|
11482fe11832e73065c320476196753d9bf2502e | nyasho4ka/crack_coding_interview | /arrays_and_strings/is_unique/test_is_unique.py | 1,141 | 3.53125 | 4 | import is_unique
import unittest
class IsUniqueTestCase(object):
def test_unique_string(self):
unique_string = 'abcde'
self.assertEqual(self.is_unique(unique_string), True)
def test_non_unique_string(self):
non_unique_string = 'aabbccee'
self.assertEqual(self.is_unique(non_unique_string), False)
def test_empty_string(self):
empty_string = ''
self.assertEqual(self.is_unique(empty_string), True)
def test_one_char_string(self):
one_char_string = 'f'
self.assertEqual(self.is_unique(one_char_string), True)
def test_extremely_string(self):
extremely_string = 'abcdefghjzxva'
self.assertEqual(self.is_unique(extremely_string), False)
class IsUniqueV1TestCase(unittest.TestCase, IsUniqueTestCase):
def setUp(self):
self.is_unique = is_unique.is_unique_v1
class IsUniqueV2TestCase(unittest.TestCase, IsUniqueTestCase):
def setUp(self):
self.is_unique = is_unique.is_unique_v2
class IsUniquePITestCase(unittest.TestCase, IsUniqueTestCase):
def setUp(self):
self.is_unique = is_unique.is_unique_pi
|
638acd199b2eba067488da253986874cdefe0041 | MateoKrile/Elements-of-AI---Building-AI | /Section 3 Machine Learning/Working with text/Bag of words.py | 1,765 | 4.46875 | 4 | """
Your task is to write a program that calculates the distances (or differences) between every pair of lines in the
This Little Piggy rhyme and finds the most similar pair. Use the Manhattan distance as your distance metric.
You can start by building a numpy array to store all the distances. Notice that the diagonal elements in the array
(elements at positions [i, j] with i=j) will be equal to zero. This happens because the program will compare every
row also with itself. To avoid selecting those elements, you can assign the value np.inf (the maximum possible floating point value).
To do this, it's necessary to make sure the type of the array is float.
A quick way to get the index of the element with the lowest value in a 2D array (or in fact, any dimension) is by the function
np.unravel_index(np.argmin(dist), dist.shape))
where dist is the 2D array. This will return the index as a list of length two.
"""
import numpy as np
data = [[1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1],
[1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 0, 1, 3, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1]]
def manhattan_dist(a, b):
dist = 0
for ai, bi in zip(a, b):
dist += abs(ai-bi)
return dist
def find_nearest_pair(data):
N = len(data)
dist = np.empty((N, N), dtype=np.float)
for x in range(len(data)):
for y in range(len(data)):
if x==y:
dist[x][y] = np.Inf
else:
dist[x][y] = manhattan_dist()(data[x], data[y])
print(np.unravel_index(np.argmin(dist), dist.shape))
find_nearest_pair(data)
|
0186a44a90735716d421714b5b5cdb9bd0692576 | amovah/ACM | /QueraIR/2.py | 132 | 3.703125 | 4 | max = 0
for i in range(int(input())):
current = set(input())
if len(current) > max:
max = len(current)
print(max)
|
94f8ec83b101f7e3ef2ca488bbee3e217af448cc | AlexandraFil/Geekbrains_2.0 | /Python_start/lesson_5/lesson_5.3.py | 897 | 4.21875 | 4 | # 3. Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов.
# Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников.
# Выполнить подсчет средней величины дохода сотрудников.
wages = {}
with open('lesson_5.3.txt', 'r', encoding='utf-8') as f:
for line in f:
wages[line.split()[0]] = float(line.split()[1])
print('Сотрудники, получающие меньше 20 000: ', end= " ")
for surname, salary in wages.items():
if salary < 20000:
print(surname, end= ", ")
print(f"cредняя величина дохода сотрудников: {sum(wages.values())/len(wages)}") |
70cc7fcb8567698f2aed1d73c72eec47bba35264 | EuniceHu/python15_api_test | /Myself/class_214_str_tuple_list_dict/class_tuple.py | 1,034 | 3.859375 | 4 |
#整数 浮点数 字符串 布尔值 True False
#元祖 关键字 tuple
#1:特征
#1.1.圆括号括起来的数据,都是元祖
#1.2.空元祖 t_1=()
#1.3.如果一个元祖里面只有一个元素,要在元素后面加一个逗号
#1.4 元祖里面可以包含各种类型的数据 整数 浮点数 字符串 布尔值
#1.5 元素与元素之间是用逗号隔开的,看元素的长度 len
#1.6 取值方式:与字符串一样 根据索引取值 可以切片取值
#取单个值的方式 元祖名[索引值] 索引值从0开始
#嵌套取值 怎么取
# t_1=(2,0.0089,'1',True,(1,2,3,'hello'))
# s=t_1[-1]#取出值 存到s变量里面
# print(s[3])
# print(s[-1])
# print(t_1[-1][-1][1])
# print(s[-1][1])
#切片:同字符串 元祖名[索引开始值:索引结束值:步长]
#取左不取右
#1.7.元祖是有序数据 但是不支持做增删改
t=(2,0.0089,'1',True,(1,2,3,'hello'),2,3,4,5)
print(t[0::2])
print(t.count(2))
print(t.index(2,1))
#2:用法 和 场景
#用在什么场景下?
|
a375c1710040b8cad8ed00f8fb7a9fe600680a7d | shivakrshn49/python-concepts | /bound_vs_unbound_methods.py | 1,584 | 3.765625 | 4 | #https://stackoverflow.com/questions/13348031/python-bound-and-unbound-method-object
#Whenever you look up a method via instance.name (and in Python 2, class.name), the method object is created a-new.
#Python uses the descriptor protocol to wrap the function in a method object each time.
#So, when you look up id(C.foo), a new method object is created, you retrieve its id (a memory address),
#then discard the method object again. Then you look up id(cobj.foo), a new method object created that re-uses the now freed memory
#address and you see the same value. The method is then, again, discarded (garbage collected as the reference count drops to 0).
#Next, you stored a reference to the C.foo unbound method in a variable. Now the memory address is not freed
#(the reference count is 1, instead of 0), and you create a second method instance by looking up cobj.foo which has to use a new memory
#location. Thus you get two different values.
#Two objects with non-overlapping lifetimes may have the same id() value python
class D(object):
def f(self, x):
return x
def g(self, x):
return x
d = D()
print D.__dict__['f'], id(D.__dict__['f'])
print D.f, id(D.f), '<<<D.f'
print d.f, id(d.f), '<<<d.f'
print '*************'
# print D.__dict__['g'], id(D.__dict__['g'])
# print D.g, id(D.g), '<<<D.g'
# print d.g, id(d.g), '<<<d.g'
# print '**************'
assigned = d.f
again_assigned = D.f
print id(assigned)
print id(again_assigned)
print d.f, id(d.f), '<<<d.f<<<<<<'
print D.f, id(D.f), '<<<D.f'
# print [id(x) for x in (d.f, d.f, D.f, D.f)]
|
6c7bbfbc165ea61089e1edd47cbf79ff5bb503b4 | maohaoyang369/Python_exercise | /152.遍历一个列表[1,2,3,4,5,1],请判断列表里面是否有1,有的话打印findit,没有的话提示,没有1.py | 429 | 3.671875 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# 遍历一个列表[1,2,3,4,5,1],请判断列表里面是否有1,有的话打印find it,没有的话提示,没有1
sentence = [1, 2, 3, 4, 5]
is_break = False
for i in sentence:
if not isinstance(i, (int, float)):
print("None")
elif i == 1:
print("find it!")
break
elif i != 1:
is_break = True
if is_break:
print("没有1")
|
eb2ac5d889273149ad42386393cd403f94f92fd4 | 7enTropy7/Tic-Tac-Toe_AI | /ttt.py | 2,655 | 3.765625 | 4 | def toggle(player):
if player == 'X':
return 'O'
else:
return 'X'
class Game:
def __init__(self):
self.board = [' ']*9
def minimax_algorithm(self,node,depth,player):
if depth == 0 or node.draw():
if node.check() == "X":
return 0
elif node.check() == "O":
return 100
else:
return 50
if player == "O":
optimum_value = 0
for pos in node.empty_pos():
node.play_move(pos, player)
val = self.minimax_algorithm(node,depth-1,toggle(player))
node.play_move(pos,' ')
optimum_value = max(optimum_value,val)
return optimum_value
if player == "X":
optimum_value = 100
for pos in node.empty_pos():
node.play_move(pos, player)
val = self.minimax_algorithm(node,depth-1,toggle(player))
node.play_move(pos,' ')
optimum_value = min(optimum_value,val)
return optimum_value
def display(self):
print(" %c | %c | %c " % (self.board[0], self.board[1], self.board[2]))
print("___|___|___")
print(" %c | %c | %c " % (self.board[3], self.board[4], self.board[5]))
print("___|___|___")
print(" %c | %c | %c " % (self.board[6], self.board[7], self.board[8]))
print(" | | ")
def check(self):
win_cases = ([0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6])
for p in ('X','O'):
possible = self.filled_pos(p)
for case in win_cases:
win = True
for pos in case:
if pos not in possible:
win = False
if win == True:
return p
def winner(self):
if self.check() == 'X':
return 'X'
elif self.check() == 'O':
return 'O'
elif self.draw() == True:
return 'Draw'
def draw(self):
if self.check() != None:
return True
for i in self.board:
if i == ' ':
return False
return True
def play_move(self,pos,player):
self.board[pos] = player
def empty_pos(self):
empty = []
for i in range(9):
if self.board[i]==' ':
empty.append(i)
return empty
def filled_pos(self, player):
filled = []
for i in range(0,9):
if self.board[i] == player:
filled.append(i)
return filled |
256810dcadab649f0696ccec9d8b4b10193c36d2 | moontasirabtahee/OOP_Python_BRACU | /CSE111 Lab Assignment 6/Task9.py | 1,476 | 3.734375 | 4 | # Created by Moontasir Abtahee at 6/8/2021
class Student:
t_stu=0
brac_stu=0
other_stu=0
def __init__(self, name, dept, ins='BRAC University'):
self.name = name
self.dept = dept
self.ins = ins
Student.t_stu += 1
if self.ins == 'BRAC University':
Student.brac_stu += 1
else:
Student.other_stu += 1
@classmethod
def printDetails(cls):
print('Total Student(s):', Student.t_stu)
print('BRAC University Student(s):', Student.brac_stu)
print('Other Institution Student(s):', Student.other_stu)
@classmethod
def createStudent(cls, name, dept, ins='BRAC University'):
x = cls(name, dept, ins)
return x
def individualDetail(self):
print('Name:', self.name)
print('Department:', self.dept)
print('Institution:', self.ins)
Student.printDetails()
print('#########################')
mikasa = Student('Mikasa Ackerman', "CSE")
mikasa.individualDetail()
print('------------------------------------------')
Student.printDetails()
print('========================')
harry = Student.createStudent('Harry Potter', "Defence Against Dark Arts", "Hogwarts School")
harry.individualDetail()
print('-------------------------------------------')
Student.printDetails()
print('=========================')
levi = Student.createStudent("Levi Ackerman", "CSE")
levi.individualDetail()
print('--------------------------------------------')
Student.printDetails() |
e267f8d15bd01a0e3b4cc61f6f4a4a429689ba1c | niru23/algorithms | /movezeros.py | 769 | 3.703125 | 4 | #!/usr/bin/python
import unittest
def movezeros(array):
i =0
j =1
while i <len(nums)-1 and j<len(nums):
if nums[i] !=0 :
i+=1
j+=1
elif nums[i]== 0 and nums[j] ==0:
j+=1
elif nums[i] ==0 and nums[j]!=0:
temp = nums[i]
nums[i] =nums[j]
nums[j] =temp
i+=1
j+=1
return nums
class Test:
data =[[0, 1, 0, 3, 12],[1, 3, 12, 0, 0]]
def test_movezeros(self):
for a1,expected in self.data:
actual =movezeros(a1)
self.assertTrue(actual)
if __name__ == "__main__":
unittest.main()
|
c4435eabc1db731be246bc1619579e807ffc97c9 | bsummerset/exercises | /python/sequences/med_3.py | 125 | 3.640625 | 4 | num = [[2,4,6,4], [3,7,5,9]]
new = []
for num[0], num[1] in zip(num[0], num[1]):
new.append(num[0] + num[1])
print(new) |
b36f62160f6610a54c2bc1204aacb6a720879fce | Sahil-Ovhal/CS_Dojo | /weather/graphs.py | 606 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 19 21:01:08 2019
@author: Admin
"""
import matplotlib.pyplot as plt
import numpy as np
import math
## Create functions and set domain length
x = np.arange(-5.0, 5.0, 0.01)
y = x**x
z=0
## Plot functions and a point where they intersect
plt.plot(x, y)
plt.plot(x, z)
plt.plot(1, 1, 'or')
## Config the graph
plt.title('A Cool Graph')
plt.xlabel('X')
plt.ylabel('Y')
#plt.ylim([0, 4])
plt.grid(True)
plt.legend(['y = x', 'y = 2x'], loc='upper left')
## Show the graph
plt.show() |
11fb1a87c0d5e8b929e21fb4dfc47cf625684a03 | HarshaMatta/PythonProjects | /F_to_C.py | 594 | 4.34375 | 4 | # created by harsha matta
# created on 26/10/18
# this program will convert celsius to fahrenheit and vice versa
# this program takes two inputs: type of temperature you start with and the number that you want to convert
# then it output the converted temperature
def fahrenheit(number):
print( float((number - 32) * 5 / 9 ))
def celcius(number):
print(float((number * 9 / 5) + 32))
x = input("fahrenheit or celsius")
num = float(input("type number here"))
if x == "f" or x == "F":
fahrenheit(num)
elif x == "c" or x == "C":
celcius(num)
else :
print("type f or c only")
|
e80abb98a565aa3bf985269f626011127c05d3b3 | Leonard-Atorough/python-practice | /example_a.py | 320 | 3.828125 | 4 | a = "A B C D E F"
b = "Y B H D A G"
def first_difference(str1, str2):
difference = ""
set_a = set(a)
set_b = set(b)
for word_a in set_a:
if word_a not in set_b:
if word_a not in difference:
difference += word_a
print(sorted(difference))
first_difference(a, b)
|
9f6efc997bbaa486dfcd91670a41c8aa2cfd03ab | vdudi/playwithpython | /fileOpen.py | 373 | 3.71875 | 4 | file = input("Enter File Name, like email-short.txt: ")
try:
#fhand = open('mbox-short.txt')
fhand = open(file)
except:
print("Exception, file not found")
#inp = fhand.read()
#print((len(inp)))
#print("111 "+ inp[:20])
for line in fhand:
if line.startswith('From:'):
line = line.rstrip()
line = line.upper()
print("Line: "+ line)
|
9dae4620d627e4cd7ec7459b92fe3eb5fd44ce58 | nirakarmohanty/Python | /controlflow/WhileExample.py | 100 | 3.78125 | 4 | #Print the number from 1->10
i=0;
while i < 10:
print(i);
i=i+1;
print("latest value :",i);
|
5b6d3ea80843e1ddc43f740311233765cbc534d4 | xiao-bo/leetcode | /medium/swapNodeInPairs.py | 1,465 | 3.953125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
## iteration method by me
## I spend 30 min to solve it
## Runtime: 20 ms, faster than 50.14% of Python online submissions for Swap Nodes in Pairs.
## Memory Usage: 11.8 MB, less than 22.73% of Python online submissions for Swap Nodes in Pairs.
if not head or not head.next:
return head
prev = ListNode(0)
ans = ListNode(0)
ans = head.next
while head and head.next:
prev.next = head.next
head.next = head.next.next
prev.next.next = head
head = head.next
prev = prev.next.next
return ans
def printAllnode(self,head):
while head:
print(head.val)
head = head.next
def main():
a = Solution()
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
node6 = ListNode(6)
#node1.next = node2
#node2.next = node3
#node3.next = node4
#node4.next = node5
#node5.next = node6
ans = a.swapPairs(node1)
a.printAllnode(ans)
if __name__ == '__main__':
main() |
09ed7213c04674928c5e183106b350ade30791a0 | Nishith170217/Python-Self-Challenge | /List Program/Sort the values of first list using second list in Python.py | 333 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 30 16:52:52 2021
@author: Nishith
"""
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for c, x in sorted(zipped_pairs)]
return z
x = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
print(sort_list(x, y))
|
8359b8f7612cdc744ddb66acd170a813a0cb2941 | ResearchInMotion/CloudForce-Python- | /UnboxQuestions/F-19.py | 146 | 3.578125 | 4 | def girl(str,c):
if(c in str):
return("1")
else:
return("0")
print("The character is present or not ",girl("chinky","n")) |
549fbdb1cee15b9285b297b7f8536c84e4f913f6 | Miked7531/Python | /pieabstract.py | 396 | 3.8125 | 4 | from abc import ABC, abstractmethod
class pie(ABC):
def pieSlice(self, amount):
print("Your slice of the pie is: ",amount)
@abstractmethod
def piethief(self, amount):
pass
class Totalpieslices(pie):
def piethief(self, amount):
print('You have stolen {} slices of pie!!'.format(amount))
obj = Totalpieslices()
obj.pieSlice("0")
obj.piethief("4")
|
a6e9b0022f9f8d6d9d2fb1bda9798922cb7a413c | syurskyi/Python_Topics | /070_oop/004_inheritance/examples/super/0001.py | 3,284 | 4.71875 | 5 | # The super() builtin returns a proxy object (temporary object of the superclass) that allows us to access methods
# of the base class.
# In Python, super() has two major use cases:
#
# Allows us to avoid using the base class name explicitly
# Working with Multiple Inheritance
# Example 1: super() with Single Inheritance
# In the case of single inheritance, it allows us to refer base class by super().
class Mammal(object):
def __init__(self, mammalName):
print(mammalName, 'is a warm-blooded animal.')
class Dog(Mammal):
def __init__(self):
print('Dog has four legs.')
super().__init__('Dog')
d1 = Dog()
# Output
#
# Dog has four legs.
# Dog is a warm-blooded animal.
# Here, we called the __init__() method of the Mammal class (from the Dog class) using code
#
# super().__init__('Dog')
# instead of
#
# Mammal.__init__(self, 'Dog')
# Since we do not need to specify the name of the base class when we call its members, we can easily change the base class name (if we need to).
#
# # changing base class to CanidaeFamily
# class Dog(CanidaeFamily):
# def __init__(self):
# print('Dog has four legs.')
#
# # no need to change this
# super().__init__('Dog')
# The super() builtin returns a proxy object, a substitute object that can call methods of the base class
# via delegation. This is called indirection (ability to reference base object with super())
# Since the indirection is computed at the runtime, we can use different base classes
# at different times (if we need to).
#
# Example 2: super() with Multiple Inheritance
class Animal:
def __init__(self, Animal):
print(Animal, 'is an animal.');
class Mammal(Animal):
def __init__(self, mammalName):
print(mammalName, 'is a warm-blooded animal.')
super().__init__(mammalName)
class NonWingedMammal(Mammal):
def __init__(self, NonWingedMammal):
print(NonWingedMammal, "can't fly.")
super().__init__(NonWingedMammal)
class NonMarineMammal(Mammal):
def __init__(self, NonMarineMammal):
print(NonMarineMammal, "can't swim.")
super().__init__(NonMarineMammal)
class Dog(NonMarineMammal, NonWingedMammal):
def __init__(self):
print('Dog has 4 legs.');
super().__init__('Dog')
d = Dog()
print('')
bat = NonMarineMammal('Bat')
# Output
#
# Dog has 4 legs.
# Dog can't swim.
# Dog can't fly.
# Dog is a warm-blooded animal.
# Dog is an animal.
#
# Bat can't swim.
# Bat is a warm-blooded animal.
# Bat is an animal.
# Method Resolution Order (MRO)
# Method Resolution Order (MRO) is the order in which methods should be inherited in the presence
# of multiple inheritance. You can view the MRO by using the __mro__ attribute.
#
Dog.__mro__
# (<class 'Dog'>,
# <class 'NonMarineMammal'>,
# <class 'NonWingedMammal'>,
# <class 'Mammal'>,
# <class 'Animal'>,
# <class 'object'>)
# Here is how MRO works:
#
# A method in the derived calls is always called before the method of the base class.
# In our example, Dog class is called before NonMarineMammal or NoneWingedMammal. These two classes are called before
# Mammal, which is called before Animal, and Animal class is called before the object.
# If there are multiple parents like Dog(NonMarineMammal, NonWingedMammal), methods of NonMarineMammal
# is invoked first because it appears first.
|
6c0614461a1d930c0ddf91d8fa2f0fae92f4f89f | randylodes/Coursera | /pay-calculator.py | 261 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 16 13:52:15 2017
@author: Randy
"""
# Gather the input data
hrs = input("Enter hours: ")
rate = input("Enter rate: ")
# Calculate the result
pay = float(hrs) * float(rate)
# Output the result
print("Pay:", pay) |
3eeb32cccd9753566f185b01dd6e88da17b92561 | StartAmazing/Python | /venv/Include/tuling/chapter1/strfunc.py | 2,182 | 4.5 | 4 | # str 内置函数
# 字符串的查找
str = "hello, java, python and Scala"
print(str.find("Scala"))
# print(str.index("C++")) # value error
print(help(str.find))
# 判断类函数
print(str.islower())
# 判断是否全部是字母或汉字字符
print(str.isalpha())
print("Linus".isalpha())
print("你好".isalpha())
print( "-----------------------isdigit, isnumeric, isdecimal三个判断数字的函数(不建议使用,尽量使用正则表达式)--------------------")
# 总结
'''
isdigit: Unicode数字,byte数字(单字节),全角数字(双字节)
False: 汉字数字
Error: 无
'''
print("3".isdigit())
print("".isdigit())
print("三".isdigit())
'''
isdecimal()
True: Unicode数字,全角数字(双字节)
False: 罗马数字,汉字数字
Error:byte数字(单字节)
'''
'''
isnumeric()
True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
False:无
Error:byte数字(单字节)
'''
print("三".isnumeric()) # true
# 内容判断类
print("----------------------- 内容判断类 --------------------")
# startwith / endwith: 是否以xxx开头或者结尾
print(help(str.startswith))
print("Alice".startswith("alic"))
# 操作类函数
print("----------------------- 操作类函数 --------------------")
# format格式化的
# strip: 这个函数主要作用是删除字符串两边的空格,其实这个函数允许你去定义删除字符串两边的哪个
# 字符,只不过如果不指定的话默认是空格。同样还有lstrip和rstrip,此处l和r分别表示左边右边,即删
# 除字符串左边或者右边指定的字符,默认空格。需要注意的是,此处的删除不是删除哪个一个,而是从头
# 开始符合条件的连续字符
c = "LLLLLLL love xiaojingyu "
print(c)
print(c.strip())
# join函数,我们使用s1, s2, s3作为分隔符,把ss内的内容拼接在一起
print("------------------ join函数 ----------------")
s1 = "$"
s2 = "-"
s3 = " "
ss = ["Alice Smith", "Donald Knuth", "Krict Annie"]
print(s1.join(ss))
print(s2.join(ss))
print(s3.join(ss)) |
fa6e214260d065003c42711480659142c9ca4982 | kellyseeme/pythonexample | /323/isString.py | 762 | 4.46875 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
#this is test a string is a string or not
#this is use isinstance to check is this a string
def isString(x):
return isinstance(x,basestring)
print map(isString,["kel",34,u"ko"])
#this is use the duck string to test a string is a string
def isStringLike(obj):
try:
obj.lower() + ""
except:
return False
else:
return True
print map(isStringLike,["kel",34,u"ko"])
"""
用来检查一个字符串是否是字符串,
第一种方法是用isinstance来进行检查,主要是由于str和unicodestring都是basestring的子类,从而
可以使用isinstance来进行检查
第二种方法是使用鸭子判断法,叫声像鸭子,行为像鸭子,那么就认识是
"""
|
1d9154fcdf96fd895b650c2e6109ae266ea60bdb | jaeyoung-jane-choi/2016-2021_Sungkyunkwan_University | /2020-Data-Structure-Algorithms/bfs.py | 956 | 3.84375 | 4 |
# from clqueue import Queue #큐를 한 과제가 없어서, 큐를 새로 정의했습니다.
#first in first out
class Queue:
def __init__(self):
self.item = [] #empty list
def is_empty(self):
return self.items == []
def enqueue(self,item):
self.item.append(item) #append at first
def dequeue(self):
if self.is_empty():
return None
else:
self.item.pop(0)
adj_list =[[2,1],[3,0],[3,0],[9,8,2,1],[5],[7,6,4],[7,5],[6,5],[3],[3]]
N=len(adj_list)
visited = [False]*N #make false *n list
def bfs(v):
queue = Queue()
visited[v] =True
queue.enqueue(v)
while not queue.is_empty():
v= queue.dequeue()
print(v,' ', end='')
for i in adj_list[v]:
if not visited[i]:
visited[i] = True
queue.enqueue(i)
print('BFT 방문 순서: ')
for i in range(N):
if not visited[i]:
bfs(i)
|
784a4888ee8851d1cd065f8bce0dcbead5409526 | s1s1ty/Calculator | /Calculator.py | 2,856 | 3.75 | 4 | from tkinter import *
import math
root = Tk()
root.resizable(0,0)
equa = ""
root.title("Shaonty's Calculator")
#Display
num1 = StringVar()
e = Label(root,textvariable=num1,height=3,width=25,font=150)
e.grid(columnspan = 4)
def btnPress(num):
global equa
equa = equa+str(num)
num1.set(equa)
def equalPress():
global equa
total = str(eval(equa))
num1.set(total)
equa=total
def squre():
global equa
total = str(int(equa)*int(equa))
num1.set(total)
equa = str(total)
def clear():
global equa
equa=""
num1.set("")
def power():
global equa
total = str(math.sqrt(float(equa)))
num1.set(total)
equa = str(total)
def Percent():
global equa
n = float(equa)
total = str(n/100.0)
equa=total
num1.set(total)
#button
button1 = Button(root,text="1",font=8,padx=20,command = lambda:btnPress(1))
button1.grid(row=3,column=0)
button2 = Button(root,text="2",font=8,padx=20,command = lambda:btnPress(2))
button2.grid(row=3 , column = 1)
button3 = Button(root,text="3",font=8,padx=20,command = lambda:btnPress(3))
button3.grid(row=3 , column = 2)
button4 = Button(root,text="4",font=8,padx=20,command = lambda:btnPress(4))
button4.grid(row=2, column = 0)
button5 = Button(root,text="5",font=8,padx=20,command = lambda:btnPress(5))
button5.grid(row=2,column=1)
button6 = Button(root,text="6",font=8,padx=20,command = lambda:btnPress(6))
button6.grid(row=2,column=2)
button7 = Button(root,text="7",font=8,padx=20,command = lambda:btnPress(7))
button7.grid(row=1,column=0)
button8 = Button(root,text="8",font=8,padx=20,command = lambda:btnPress(8))
button8.grid(row=1,column=1)
button9 = Button(root,text="9",font=8,padx=20,command = lambda:btnPress(9))
button9.grid(row=1,column=2)
button0 = Button(root,text="0",font=8,padx=20,command = lambda:btnPress(0))
button0.grid(row=4,column=1)
clear1 = Button(root,text="C",font=8,bg="#EE691D",command = clear)
clear1.grid(row=1,column=3)
Plus = Button(root,text="+",font=8,bg="#13E2DB",command = lambda:btnPress("+"))
Plus.grid(row=2, column = 3)
Minus= Button(root,text="-",font=8,padx=20,bg="#13E2DB",command = lambda:btnPress("-"))
Minus.grid(row=2, column = 4)
mul = Button(root,text="*",font=8,padx=13,bg="#13E2DB",command = lambda:btnPress("*"))
mul.grid(row=3, column = 3)
div= Button(root,text="/",font=8,padx=20,bg="#13E2DB",command = lambda:btnPress("/"))
div.grid(row=3, column = 4)
point = Button(root,text=".",font=20,bg="#13E2DB",padx=22,command = lambda:btnPress("."))
point.grid(row=4,column=0)
percent = Button(root,text="%",padx=20,bg="#13E2DB",command=Percent)
percent.grid(row=4,column=2)
sqr = Button(root,text="x2",bg="#13E2DB",command=squre)
sqr.grid(row=4,column = 3)
pwr = Button(root,text="root",bg="#13E2DB",command=power)
pwr.grid(row=1,column=4)
equal = Button(root,text="=",font=10,padx=18,bg="#248A05",command = equalPress)
equal.grid(row=4,column=4)
root.mainloop() |
c8d996e9a89e5ac05ebda1538225cea697537009 | kk2491/Probability_Distributions | /Exponential_Distribution/Exponential_Distribution_Python_1.py | 611 | 3.546875 | 4 | '''
mean = 1 / lambda
variance = 1 /(lambda)^2
'''
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
lambd =0.5
x = np.arange(0, 15, 0.1)
y = lambd * np.exp(-lambd * x)
plt.figure(1)
plt.plot(x, y)
plt.title('Exponential: $\lambda$ = %.2f ' % lambd)
plt.xlabel('x')
plt.ylabel('Probability Density')
# plt.show()
data = stats.expon.rvs(scale = 2, size = 1000)
print("Mean : %g " % np.mean(data))
print ("SD : %g" % np.std(data, ddof = 1))
plt.figure(2)
plt.hist(data, bins = 20, normed = True)
plt.xlim(0, 15)
plt.title("Simulating Exponential Random Variables")
plt.show()
|
1722671a152ef77a2b7ff58723e4843ef387ba66 | tnakaicode/jburkardt-python | /triangle_grid/triangle_integrals.py | 58,010 | 3.953125 | 4 | #! /usr/bin/env python3
#
def i4_to_pascal_degree(k):
# *****************************************************************************80
#
# I4_TO_PASCAL_DEGREE converts a linear index to a Pascal triangle degree.
#
# Discussion:
#
# We describe the grid points in Pascal's triangle in two ways:
#
# As a linear index K:
#
# 1
# 2 3
# 4 5 6
# 7 8 9 10
#
# As elements (I,J) of Pascal's triangle:
#
# 0,0
# 1,0 0,1
# 2,0 1,1 0,2
# 3,0 2,1 1,2 0,3
#
# The quantity D represents the "degree" of the corresponding monomial,
# that is, D = I + J.
#
# We can compute D directly from K using the quadratic formula.
#
# Example:
#
# K I J D
#
# 1 0 0 0
#
# 2 1 0 1
# 3 0 1 1
#
# 4 2 0 2
# 5 1 1 2
# 6 0 2 2
#
# 7 3 0 3
# 8 2 1 3
# 9 1 2 3
# 10 0 3 3
#
# 11 4 0 4
# 12 3 1 4
# 13 2 2 4
# 14 1 3 4
# 15 0 4 4
#
# 16 5 0 5
# 17 4 1 5
# 18 3 2 5
# 19 2 3 5
# 20 1 4 5
# 21 0 5 5
#
# 22 6 0 6
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 14 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer K, the linear index of the (I,J) element.
# 1 <= K.
#
# Output, integer D, the degree (sum) of the corresponding Pascal indices.
#
import numpy as np
from sys import exit
if (k <= 0):
print('')
print('I4_TO_PASCAL_DEGREE - Fatal error!')
print(' K must be positive.')
exit('I4_TO_PASCAL_DEGREE - Fatal error!')
d = int(0.5 * (- 1.0 + np.sqrt(1.0 + 8.0 * (k - 1))))
return d
def i4_to_pascal_degree_test():
# *****************************************************************************80
#
# % I4_TO_PASCAL_DEGREE_TEST tests I4_TO_PASCAL_DEGREE.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 14 April 2015
#
# Author:
#
# John Burkardt
#
import platform
print('')
print('I4_TO_PASCAL_DEGREE_TEST')
print(' Python version: %s' % (platform.python_version()))
print(' I4_TO_PASCAL_DEGREE converts a linear index to')
print(' the degree of the corresponding Pascal triangle indices.')
print('')
print(' K => D')
print('')
for k in range(1, 21):
d = i4_to_pascal_degree(k)
print(' %4d %4d' % (k, d))
#
# Terminate.
#
print('')
print('I4_TO_PASCAL_DEGREE_TEST:')
print(' Normal end of execution.')
return
def i4_to_pascal(k):
# *****************************************************************************80
#
# % I4_TO_PASCAL converts a linear index to Pascal triangle coordinates.
#
# Discussion:
#
# We describe the grid points in Pascal's triangle in two ways:
#
# As a linear index K:
#
# 1
# 2 3
# 4 5 6
# 7 8 9 10
#
# As elements (I,J) of Pascal's triangle:
#
# 0,0
# 1,0 0,1
# 2,0 1,1 0,2
# 3,0 2,1 1,2 0,3
#
# Example:
#
# K I J
#
# 1 0 0
# 2 1 0
# 3 0 1
# 4 2 0
# 5 1 1
# 6 0 2
# 7 3 0
# 8 2 1
# 9 1 2
# 10 0 3
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 14 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer K, the linear index of the (I,J) element.
# 1 <= K.
#
# Output, integer I, J, the Pascal indices.
#
from sys import exit
if (k <= 0):
print('')
print('I4_TO_PASCAL - Fatal error!')
print(' K must be positive.')
exit('I4_TO_PASCAL - Fatal error!')
d = i4_to_pascal_degree(k)
j = k - (d * (d + 1)) // 2 - 1
i = d - j
return i, j
def i4_to_pascal_test():
# *****************************************************************************80
#
# I4_TO_PASCAL_TEST tests I4_TO_PASCAL.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 14 April 2015
#
# Author:
#
# John Burkardt
#
import platform
print('')
print('I4_TO_PASCAL_TEST')
print(' Python version: %s' % (platform.python_version()))
print(' I4_TO_PASCAL converts a linear index to')
print(' Pascal triangle indices.')
print('')
print(' K => I J')
print('')
for k in range(1, 21):
i, j = i4_to_pascal(k)
print(' %4d %4d %4d' % (k, i, j))
#
# Terminate.
#
print('')
print('I4_TO_PASCAL_TEST:')
print(' Normal end of execution.')
return
def pascal_to_i4(i, j):
# *****************************************************************************80
#
# PASCAL_TO_I4 converts Pacal triangle coordinates to a linear index.
#
# Discussion:
#
# We describe the grid points in a Pascal triangle in two ways:
#
# As a linear index K:
#
# 1
# 2 3
# 4 5 6
# 7 8 9 10
#
# As elements (I,J) of Pascal's triangle:
#
# 0,0
# 1,0 0,1
# 2,0 1,1 0,2
# 3,0 2,1 1,2 0,3
#
# Example:
#
# K I J
#
# 1 0 0
# 2 1 0
# 3 0 1
# 4 2 0
# 5 1 1
# 6 0 2
# 7 3 0
# 8 2 1
# 9 1 2
# 10 0 3
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 14 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer I, J, the row and column indices. I and J must
# be nonnegative.
#
# Output, integer K, the linear index of the (I,J) element.
#
from sys import exit
if (i < 0):
print('')
print('PASCAL_TO_I4 - Fatal error!')
print(' I < 0.')
print(' I = %d' % (i))
exit('PASCAL_TO_I4 - Fatal error!')
elif (j < 0):
print('')
print('PASCAL_TO_I4 - Fatal error!')
print(' J < 0.')
print(' J = %d' % (j))
exit('PASCAL_TO_I4 - Fatal error!')
d = i + j
k = (d * (d + 1)) // 2 + j + 1
return k
def pascal_to_i4_test():
# *****************************************************************************80
#
# % PASCAL_TO_I4_TEST tests PASCAL_TO_I4.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 14 April 2015
#
# Author:
#
# John Burkardt
#
import platform
print('')
print('PASCAL_TO_I4_TEST')
print(' Python version: %s' % (platform.python_version()))
print(' PASCAL_TO_I4 converts Pascal triangle indices to a')
print(' linear index.')
print('')
print(' I J => K')
print('')
for d in range(0, 5):
for i in range(d, -1, -1):
j = d - i
k = pascal_to_i4(i, j)
print(' %4d %4d %4d' % (i, j, k))
print('')
#
# Terminate.
#
print('')
print('PASCAL_TO_I4_TEST:')
print(' Normal end of execution.')
return
def poly_power_linear(d1, p1, n):
# *****************************************************************************80
#
# POLY_POWER_LINEAR computes the polynomial ( a + b*x + c*y ) ^ n.
#
# Location:
#
# http://people.sc.fsu.edu/~jburkardt/py_src/triangle_integrals/poly_power_linear.py
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 22 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer D1, the degree of the linear polynomial,
# which should be 1.
#
# Input, real P1(M1), the coefficients of the linear polynomial.
# M1 = ( (D1+1)*(D1+2) ) / 2, which should be 3.
#
# Input, integer N, the power to which the polynomial is to be raised.
# 0 <= N.
#
# Output, integer D2, the degree of the power polyynomial, which
# should be D2 = N * D1 = N.
#
# Output, real P2(M2), the coefficients of the power polynomial.
# M2 = ( (D2+1)*(D2+2) ) / 2, which should be ((N+1)*(N+2))/2.
#
import numpy as np
from sys import exit
if (d1 < 0):
print('')
print('POLY_POWER_LINEAR - Fatal error!')
print(' D1 < 0.')
exit('POLY_POWER_LINEAR - Fatal error!')
if (n < 0):
print('')
print('POLY_POWER_LINEAR - Fatal error!')
print(' N < 0.')
exit('POLY_POWER_LINEAR - Fatal error!')
d2 = n * d1
m2 = ((d2 + 1) * (d2 + 2)) // 2
p2 = np.zeros(m2)
if (d1 == 0):
p2[0] = p1[0] ** n
return d2, p2
if (n == 0):
p2[0] = 1.0
return d2, p2
#
# Use the Trinomial formula.
#
for i in range(0, n + 1):
for j in range(0, n - i + 1):
for k in range(0, n - i - j + 1):
#
# We store X^J Y^K in location L.
#
l = pascal_to_i4(j, k)
lm1 = l - 1
p2[lm1] = trinomial(i, j, k) * p1[0] ** i * \
p1[1] ** j * p1[2] ** k
return d2, p2
def poly_power_linear_test():
# *****************************************************************************80
#
# POLY_POWER_LINEAR_TEST tests POLY_POWER_LINEAR.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 22 April 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
print('')
print('POLY_POWER_LINEAR_TEST:')
print(' Python version: %s' % (platform.python_version()))
print(' POLY_POWER_LINEAR computes the N-th power of')
print(' a linear polynomial in X and Y.')
#
# P = ( 1 + 2 x + 3 y )^2
#
d1 = 1
p1 = np.array([1.0, 2.0, 3.0])
print('')
poly_print(d1, p1, ' p1(x,y)')
dp, pp = poly_power_linear(d1, p1, 2)
print('')
poly_print(dp, pp, ' p1(x,y)^n')
dc = 2
pc = np.array([1.0, 4.0, 6.0, 4.0, 12.0, 9.0])
print('')
poly_print(dc, pc, ' Correct answer: p1(x,y)^2')
#
# P = ( 2 - x + 3 y )^3
#
d1 = 1
p1 = np.array([2.0, -1.0, 3.0])
print('')
poly_print(d1, p1, ' p1(x,y)')
dp, pp = poly_power_linear(d1, p1, 3)
print('')
poly_print(dp, pp, ' p1(x,y)^3')
dc = 3
pc = np.array([8.0, -12.0, 36.0, 6.0, -36.0, 54.0, -1.0, 9.0, -27.0, 27.0])
print('')
poly_print(dc, pc, ' Correct answer: p1(x,y)^n')
#
# Terminate.
#
print('')
print('POLY_POWER_LINEAR_TEST')
print(' Normal end of execution.')
return
def poly_power(d1, p1, n):
# *****************************************************************************80
#
# POLY_POWER computes a power of a polynomial.
#
# Location:
#
# http://people.sc.fsu.edu/~jburkardt/py_src/triangle_integrals/poly_power.py
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 22 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer D1, the degree of the polynomial.
#
# Input, real P1(M1), the polynomial coefficients.
# M1 = ((D1+1)*(D1+2))/2.
#
# Input, integer N, the nonnegative integer power.
#
# Output, integer D2, the degree of the power polynomial.
# D2 = N * D1.
#
# Output, real P2(M2), the polynomial power.
# M2 = ((D2+1)*(D2+2))/2.
#
import numpy as np
#
# Create P2, a polynomial representation of 1.
#
d2 = 0
m2 = ((d2 + 1) * (d2 + 2)) // 2
p2 = np.zeros(m2)
p2[0] = 1.0
#
# Iterate N times:
# P2 <= P2 * P1
#
for i in range(0, n):
d2, p2 = poly_product(d2, p2, d1, p1)
return d2, p2
def poly_power_test():
# *****************************************************************************80
#
# POLY_POWER_TEST tests POLY_POWER.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 22 April 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
print('')
print('POLY_POWER_TEST:')
print(' POLY_POWER computes the N-th power of an X,Y polynomial.')
#
# P1 = ( 1 + 2 x + 3 y )
# P2 = P1^2 = 1 + 4x + 6y + 4x^2 + 12xy + 9y^2
#
d1 = 1
p1 = np.array([1.0, 2.0, 3.0])
n = 2
print('')
poly_print(d1, p1, ' p1(x,y)')
d2, p2 = poly_power(d1, p1, n)
print('')
poly_print(d2, p2, ' p2(x,y) = p1(x,y)^2')
d3 = 2
p3 = np.array([1.0, 4.0, 6.0, 4.0, 12.0, 9.0])
print('')
poly_print(d3, p3, ' p3(x,y)=correct answer')
#
# P1 = ( 1 - 2 x + 3 y - 4 x^2 + 5 xy - 6 y^2 )
# P2 = P1^3 =
# 1
# -6x +9y
# +0x^2 - 21xy + 9y^2
# +40x^3 - 96x^2y + 108x^y2 - 81y^3
# +0x^4 + 84x^3y - 141 x^2y^2 +171xy^3 - 54y^4
# -96x^5 + 384x^4y -798x^3y^2 + 1017 x^2y^3 - 756 xy^4 + 324 y^5
# -64x^6 + 240x^5y - 588x^4y^2 + 845 x^3y^3 - 882 x^2y^4 +540 xy^5 - 216y^6
#
d1 = 2
p1 = np.array([1.0, -2.0, 3.0, -4.0, +5.0, -6.0])
n = 3
print('')
poly_print(d1, p1, ' p1(x,y)')
d2, p2 = poly_power(d1, p1, n)
print('')
poly_print(d2, p2, ' p2(x,y) = p1(x,y)^3')
d3 = 6
p3 = np.array([
1.0,
-6.0, 9.0,
0.0, -21.0, 9.0,
40.0, -96.0, 108.0, -81.0,
0.0, 84.0, -141.0, 171.0, -54.0,
-96.0, 384.0, -798.0, 1017.0, -756.0, 324.0,
-64.0, 240.0, -588.0, 845.0, -882.0, 540.0, -216.0])
print('')
poly_print(d3, p3, ' p3(x,y)=correct answer')
#
# Terminate.
#
print('')
print('POLY_POWER_TEST')
print(' Normal end of execution.')
return
def poly_print(d, p, title):
# *****************************************************************************80
#
# POLY_PRINT prints an XY polynomial.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 17 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer D, the degree of the polynomial.
#
# Output, real P(M), the coefficients of all monomials of degree 0 through D.
# P must contain ((D+1)*(D+2))/2 entries.
#
# Input, string TITLE, a title string.
#
m = ((d + 1) * (d + 2)) // 2
allzero = True
for i in range(0, m):
if (p[i] != 0.0):
allzero = False
if (allzero):
print('%s = 0.0' % (title))
else:
print('%s = ' % (title))
for k in range(1, m + 1):
i, j = i4_to_pascal(k)
di = i + j
km1 = k - 1
if (p[km1] != 0.0):
if (p[km1] < 0.0):
print(' -%g' % (abs(p[km1]))),
else:
print(' +%g' % (p[km1])),
if (di != 0):
print(''),
#
# "PASS" does nothing, but Python requires a statement here.
#
# Python idiotically insists on putting a space between successive prints,
# and I don't feel like calling sys.stdout.write ( string ) in order to
# suppress something I shouldn't have to deal with in the first place,
# so pretend you like it.
#
if (i == 0):
pass
elif (i == 1):
print('x'),
else:
print('x^%d' % (i)),
if (j == 0):
pass
elif (j == 1):
print('y'),
else:
print('y^%d' % (j)),
print('')
return
def poly_print_test():
# *****************************************************************************80
#
# POLY_PRINT_TEST tests POLY_PRINT.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 22 April 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
print('')
print('POLY_PRINT_TEST:')
print(' Python version: %s' % (platform.python_version()))
print(' POLY_PRINT can print a D-degree polynomial in X and Y.')
#
# P = 12.34
#
d = 0
p = np.array([12.34])
print('')
poly_print(d, p, ' p1(x,y)')
#
# P = 1.0 + 2.0 * x + 3.0 * Y
#
d = 1
p = np.array([1.0, 2.0, 3.0])
print('')
poly_print(d, p, ' p2(x,y)')
#
# P = XY
#
d = 2
p = np.array([0.0, 0.0, 0.0, 0.0, 1.0, 0.0])
print('')
poly_print(d, p, ' p3(x,y) = xy')
#
# P = 1 - 2.1 * x + 3.2 * y - 4.3 * x^2 + 5.4 * xy - 6.5 * y^2
# + 7.6 * x^3 - 8.7 * x^2y + 9.8 * xy^2 - 10.9 * y^3.
#
d = 3
p = np.array([1.0, -2.1, +3.2, -4.3, +5.4, -6.5, +7.6, -8.7, +9.8, -10.9])
print('')
poly_print(d, p, ' p4(x,y)')
#
# Terminate.
#
print('')
print('POLY_PRINT_TEST')
print(' Normal end of execution.')
return
def poly_product(d1, p1, d2, p2):
# *****************************************************************************80
#
# % POLY_PRODUCT computes P3(x,y) = P1(x,y) * P2(x,y) for polynomials.
#
# Location:
#
# http://people.sc.fsu.edu/~jburkardt/py_src/triangle_integrals/poly_product.py
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 22 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer D1, the degree of factor 1.
#
# Input, real P1(M1), the factor 1 coefficients.
# M1 = ((D1+1)*(D1+2))/2.
#
# Input, integer D2, the degree of factor 2.
#
# Input, real P2(M2), the factor2 coefficients.
# M2 = ((D2+1)*(D2+2))/2.
#
# Output, integer D3, the degree of the result.
#
# Output, real P3(M3), the result coefficients.
# M3 = ((D3+1)*(D3+2))/2.
#
import numpy as np
d3 = d1 + d2
m3 = ((d3 + 1) * (d3 + 2)) // 2
p3 = np.zeros(m3)
#
# Consider each entry in P1:
# P1(K1) * X^I1 * Y^J1
# and multiply it by each entry in P2:
# P2(K2) * X^I2 * Y^J2
# getting
# P3(K3) = P3(K3) + P1(K1) * P2(X2) * X^(I1+I2) * Y(J1+J2)
#
m1 = ((d1 + 1) * (d1 + 2)) // 2
m2 = ((d2 + 1) * (d2 + 2)) // 2
for k1m1 in range(0, m1):
k1 = k1m1 + 1
i1, j1 = i4_to_pascal(k1)
for k2m1 in range(0, m2):
k2 = k2m1 + 1
i2, j2 = i4_to_pascal(k2)
i3 = i1 + i2
j3 = j1 + j2
k3 = pascal_to_i4(i3, j3)
k3m1 = k3 - 1
p3[k3m1] = p3[k3m1] + p1[k1m1] * p2[k2m1]
return d3, p3
def poly_product_test():
# *****************************************************************************80
#
# POLY_PRODUCT_TEST tests POLY_PRODUCT.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 22 April 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
print('')
print('POLY_PRODUCT_TEST:')
print(' Python version: %s' % (platform.python_version()))
print(' POLY_PRODUCT computes the product of two X,Y polynomials.')
#
# P1 = ( 1 + 2 x + 3 y )
# P2 = ( 4 + 5 x )
# P3 = 4 + 13x + 12y + 10x^2 + 15xy + 0y^2
#
d1 = 1
p1 = np.array([1.0, 2.0, 3.0])
print('')
poly_print(d1, p1, ' p1(x,y)')
d2 = 1
p2 = np.array([4.0, 5.0, 0.0])
print('')
poly_print(d2, p2, ' p2(x,y)')
d3, p3 = poly_product(d1, p1, d2, p2)
print('')
poly_print(d3, p3, ' p3(x,y) = p1(x,y) * p2(x,y)')
dc = 2
pc = np.array([4.0, 13.0, 12.0, 10.0, 15.0, 0.0])
print('')
poly_print(dc, pc, ' Correct answer: p3(x,y)=p1(x,y)*p2(x,y)')
#
# P1 = ( 1 - 2 x + 3 y - 4x^2 + 5xy - 6y^2)
# P2 = ( 7 + 3x^2 )
# P3 = 7
# - 14x + 21y
# - 25 x^2 + 35 xy - 42y^2
# - 6x^3 + 9x^2y + 0xy^2 + 0y^3
# - 12x^4 + 15x^3y - 18x^2y^2 + 0 xy^3 + 0y^4
#
d1 = 2
p1 = np.array([1.0, -2.0, 3.0, -4.0, +5.0, -6.0])
print('')
poly_print(d1, p1, ' p1(x,y)')
d2 = 2
p2 = np.array([7.0, 0.0, 0.0, 3.0, 0.0, 0.0])
print('')
poly_print(d2, p2, ' p2(x,y)')
d3, p3 = poly_product(d1, p1, d2, p2)
print('')
poly_print(d3, p3, ' p3(x,y) = p1(x,y) * p2(x,y)')
dc = 4
pc = np.array([
7.0,
-14.0, 21.0,
-25.0, +35.0, -42.0,
-6.0, 9.0, 0.0, 0.0,
-12.0, +15.0, -18.0, 0.0, 0.0])
print('')
poly_print(dc, pc, ' Correct answer: p3(x,y)=p1(x,y)*p2(x,y)')
#
# Terminate.
#
print('')
print('POLY_PRODUCT_TEST')
print(' Normal end of execution.')
return
def r8mat_print(m, n, a, title):
# *****************************************************************************80
#
# R8MAT_PRINT prints an R8MAT.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 31 August 2014
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer M, the number of rows in A.
#
# Input, integer N, the number of columns in A.
#
# Input, real A(M,N), the matrix.
#
# Input, string TITLE, a title.
#
r8mat_print_some(m, n, a, 0, 0, m - 1, n - 1, title)
return
def r8mat_print_test():
# *****************************************************************************80
#
# R8MAT_PRINT_TEST tests R8MAT_PRINT.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 10 February 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
print('')
print('R8MAT_PRINT_TEST')
print(' Python version: %s' % (platform.python_version()))
print(' R8MAT_PRINT prints an R8MAT.')
m = 4
n = 6
v = np.array([
[11.0, 12.0, 13.0, 14.0, 15.0, 16.0],
[21.0, 22.0, 23.0, 24.0, 25.0, 26.0],
[31.0, 32.0, 33.0, 34.0, 35.0, 36.0],
[41.0, 42.0, 43.0, 44.0, 45.0, 46.0]], dtype=np.float64)
r8mat_print(m, n, v, ' Here is an R8MAT:')
#
# Terminate.
#
print('')
print('R8MAT_PRINT_TEST:')
print(' Normal end of execution.')
return
def r8mat_print_some(m, n, a, ilo, jlo, ihi, jhi, title):
# *****************************************************************************80
#
# R8MAT_PRINT_SOME prints out a portion of an R8MAT.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 10 February 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer M, N, the number of rows and columns of the matrix.
#
# Input, real A(M,N), an M by N matrix to be printed.
#
# Input, integer ILO, JLO, the first row and column to print.
#
# Input, integer IHI, JHI, the last row and column to print.
#
# Input, string TITLE, a title.
#
incx = 5
print('')
print(title)
if (m <= 0 or n <= 0):
print('')
print(' (None)')
return
for j2lo in range(max(jlo, 0), min(jhi + 1, n), incx):
j2hi = j2lo + incx - 1
j2hi = min(j2hi, n)
j2hi = min(j2hi, jhi)
print('')
print(' Col: ', end='')
for j in range(j2lo, j2hi + 1):
print('%7d ' % (j), end='')
print('')
print(' Row')
i2lo = max(ilo, 0)
i2hi = min(ihi, m)
for i in range(i2lo, i2hi + 1):
print('%7d :' % (i), end='')
for j in range(j2lo, j2hi + 1):
print('%12g ' % (a[i, j]), end='')
print('')
return
def r8mat_print_some_test():
# *****************************************************************************80
#
# R8MAT_PRINT_SOME_TEST tests R8MAT_PRINT_SOME.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 31 October 2014
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
print('')
print('R8MAT_PRINT_SOME_TEST')
print(' Python version: %s' % (platform.python_version()))
print(' R8MAT_PRINT_SOME prints some of an R8MAT.')
m = 4
n = 6
v = np.array([
[11.0, 12.0, 13.0, 14.0, 15.0, 16.0],
[21.0, 22.0, 23.0, 24.0, 25.0, 26.0],
[31.0, 32.0, 33.0, 34.0, 35.0, 36.0],
[41.0, 42.0, 43.0, 44.0, 45.0, 46.0]], dtype=np.float64)
r8mat_print_some(m, n, v, 0, 3, 2, 5, ' Here is an R8MAT:')
#
# Terminate.
#
print('')
print('R8MAT_PRINT_SOME_TEST:')
print(' Normal end of execution.')
return
def rs_to_xy_map(t):
# *****************************************************************************80
#
# RS_TO_XY_MAP returns the linear map from reference to physical triangle.
#
# Location:
#
# http://people.sc.fsu.edu/~jburkardt/py_src/triangle_poly_integral/rs_to_xy_map.py
#
# Discussion:
#
# This function returns the coefficients of the linear map that sends
# the vertices of the reference triangle, (0,0), (1,0) and (0,1), to
# the vertices of a physical triangle T, of the form:
#
# X = A + B * R + C * S;
# Y = D + E * R + F * S.
#
# Reference Element:
#
# |
# 1 3
# | |\
# | | \
# S | \
# | | \
# | | \
# 0 1-----2
# |
# +--0--R--1-->
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 22 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, real T[3,2], the coordinates of the vertices. The vertices are
# assumed to be the images of (0,0), (1,0) and (0,1) respectively.
#
# Output, real A, B, C, D, E, F, the mapping coefficients.
#
a = t[0, 0]
b = t[1, 0] - t[0, 0]
c = t[2, 0] - t[0, 0]
d = t[0, 1]
e = t[1, 1] - t[0, 1]
f = t[2, 1] - t[0, 1]
return a, b, c, d, e, f
def rs_to_xy_map_test():
# *****************************************************************************80
#
# RS_TO_XY_MAP_TEST tests RS_TO_XY_MAP.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 22 April 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
print('')
print('RS_TO_XY_MAP_TEST:')
print(' Python version: %s' % (platform.python_version()))
print(' RS_TO_XY_MAP determines the coefficients of the linear map')
print(' from a the reference in RS coordinates to the physical')
print(' triangle in XY coordinates:')
print(' X = a + b * R + c * S')
print(' Y = d + e * R + f * S')
tr = np.array([
[0.0, 0.0],
[1.0, 0.0],
[0.0, 1.0]])
t = np.array([
[2.0, 0.0],
[3.0, 4.0],
[0.0, 3.0]])
r8mat_print(3, 2, t, ' XY triangle vertices:')
a, b, c, d, e, f = rs_to_xy_map(t)
print('')
print(' Mapping coefficients are:')
print('')
print(' X = %g + %g * R + %g * S' % (a, b, c))
print(' Y = %g + %g * R + %g * S' % (d, e, f))
print('')
print(' Apply map to RS triangle vertices.')
print(' Recover XY vertices (2,0), (3,4) and (0,3).')
print('')
for i in range(0, 3):
x = a + b * tr[i, 0] + c * tr[i, 1]
y = d + e * tr[i, 0] + f * tr[i, 1]
print(' V(%d) = ( %g, %g )' % (i, x, y))
#
# Terminate.
#
print('')
print('RS_TO_XY_MAP_TEST:')
print(' Normal end of execution.')
return
def timestamp():
# *****************************************************************************80
#
# TIMESTAMP prints the date as a timestamp.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 06 April 2013
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# None
#
import time
t = time.time()
print(time.ctime(t))
return None
def timestamp_test():
# *****************************************************************************80
#
# TIMESTAMP_TEST tests TIMESTAMP.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 03 December 2014
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# None
#
import platform
print('')
print('TIMESTAMP_TEST:')
print(' Python version: %s' % (platform.python_version()))
print(' TIMESTAMP prints a timestamp of the current date and time.')
print('')
timestamp()
#
# Terminate.
#
print('')
print('TIMESTAMP_TEST:')
print(' Normal end of execution.')
return
def triangle01_monomial_integral(i, j):
# *****************************************************************************80
#
# TRIANGLE01_MONOMIAL_INTEGRAL: monomial integrals in the unit triangle.
#
# Location:
#
# http://people.sc.fsu.edu/~jburkardt/py_src/triangle_integrals/triangle01_monomial_integral.py
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 23 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer I, J, the exponents.
# Each exponent must be nonnegative.
#
# Output, real Q, the integral.
#
k = 0
q = 1.0
for l in range(1, i + 1):
k = k + 1
q = q * float(l) / float(k)
for l in range(1, j + 1):
k = k + 1
q = q * float(l) / float(k)
for l in range(1, 3):
k = k + 1
q = q / float(k)
return q
def triangle01_monomial_integral_test():
# *****************************************************************************80
#
# TRIANGLE01_MONOMIAL_INTEGRAL_TEST estimates integrals over the unit triangle.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 23 April 2015
#
# Author:
#
# John Burkardt
#
import platform
print('')
print('TRIANGLE01_MONOMIAL_INTEGRAL_TEST')
print(' Python version: %s' % (platform.python_version()))
print(' TRIANGLE01_MONOMIAL_INTEGRAL returns the integral Q of')
print(' a monomial X^I Y^J over the interior of the unit triangle.')
print('')
print(' I J Q(I,J)')
for d in range(0, 6):
print('')
for i in range(0, d + 1):
j = d - i
q = triangle01_monomial_integral(i, j)
print(' %2d %2d %14.6g' % (i, j, q))
#
# Terminate.
#
print('')
print('TRIANGLE01_MONOMIAL_INTEGRAL_TEST')
print(' Normal end of execution.')
return
def triangle01_poly_integral(d, p):
# *****************************************************************************80
#
# TRIANGLE01_POLY_INTEGRAL: polynomial integral over the unit triangle.
#
# Location:
#
# http://people.sc.fsu.edu/~jburkardt/py_src/triangle_integrals/triangle01_poly_integral.py
#
# Discussion:
#
# The unit triangle is T = ( (0,0), (1,0), (0,1) ).
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 23 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer D, the degree of the polynomial.
#
# Input, real P(M), the polynomial coefficients.
# M = ((D+1)*(D+2))/2.
#
# Output, real Q, the integral.
#
m = ((d + 1) * (d + 2)) // 2
q = 0.0
for k in range(1, m + 1):
km1 = k - 1
i, j = i4_to_pascal(k)
qk = triangle01_monomial_integral(i, j)
q = q + p[km1] * qk
return q
def triangle01_poly_integral_test():
# *****************************************************************************80
#
# TRIANGLE01_POLY_INTEGRAL_TEST: polynomial integrals over the unit triangle.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 23 April 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
d_max = 6
k_max = ((d_max + 1) * (d_max + 2)) // 2
qm = np.zeros(k_max, dtype=np.int32)
for k in range(1, k_max + 1):
km1 = k - 1
i, j = i4_to_pascal(k)
qm[km1] = triangle01_monomial_integral(i, j)
print('')
print('TRIANGLE01_POLY_INTEGRAL_TEST')
print(' TRIANGLE01_POLY_INTEGRAL returns the integral Q of')
print(' a polynomial P(X,Y) over the interior of the unit triangle.')
d = 1
m = ((d + 1) * (d + 2)) // 2
p = np.array([1.0, 2.0, 3.0])
print('')
poly_print(d, p, ' p(x,y)')
q = triangle01_poly_integral(d, p)
print('')
print(' Q = %g' % (q))
q2 = np.dot(p, qm[0:m])
print(' Q (exact) = %g' % (q2))
d = 2
m = ((d + 1) * (d + 2)) // 2
p = np.array([0.0, 0.0, 0.0, 0.0, 1.0, 0.0])
print('')
poly_print(d, p, ' p(x,y)')
q = triangle01_poly_integral(d, p)
print('')
print(' Q = %g' % (q))
q2 = np.dot(p, qm[0:m])
print(' Q (exact) = %g' % (q2))
d = 2
m = ((d + 1) * (d + 2)) // 2
p = np.array([1.0, -2.0, 3.0, -4.0, 5.0, -6.0])
print('')
poly_print(d, p, ' p(x,y)')
q = triangle01_poly_integral(d, p)
print('')
print(' Q = %g' % (q))
q2 = np.dot(p, qm[0:m])
print(' Q (exact) = %g' % (q2))
#
# Terminate.
#
print('')
print('TRIANGLE01_POLY_INTEGRAL_TEST')
print(' Normal end of execution.')
return
def triangle_area(t):
# *****************************************************************************80
#
# TRIANGLE_AREA returns the area of a triangle.
#
# Location:
#
# http://people.sc.fsu.edu/~jburkardt/py_src/triangle_integrals/triangle_area.py
#
# Discussion:
#
# If the vertices are given in counter clockwise order, the area
# will be positive.
#
# Licensing:
#
# This code is distributed under the GNU GPL license.
#
# Modified:
#
# 23 April 2015
#
# Author:
#
# John Burkardt.
#
# Parameters:
#
# Input, real T[3,2], the vertices of the triangle.
#
# Output, real AREA, the area of the triangle.
#
area = 0.5 * \
(
(t[1, 0] - t[0, 0]) * (t[2, 1] - t[0, 1])
- (t[2, 0] - t[0, 0]) * (t[1, 1] - t[0, 1])
)
return area
def triangle_area_test():
# *****************************************************************************80
#
# TRIANGLE_AREA_TEST tests TRIANGLE_AREA_MAP.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 23 April 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
print('')
print('TRIANGLE_AREA_TEST:')
print(' Python version: %s' % (platform.python_version()))
print(' TRIANGLE_AREA determines the (signed) area of a triangle.')
print('')
print(' Triangle vertices are:')
print(' (X1,Y1) = (0,0)')
print(' (X2,Y2) = 2*(cos(angle),sin(angle))')
print(' (X3,Y3) = (0,1)')
print(' where angle will sweep from 0 to 360 degrees.')
t = np.array([
[0.0, 0.0],
[2.0, 0.0],
[0.0, 1.0]])
r = 2.0
print('')
print(' I Angle X2 Y2 Area')
print(' (degrees)')
print('')
for i in range(0, 25):
angled = float(i) * 180.0 / 12.0
angler = float(i) * np.pi / 12.0
t[1, 0] = r * np.cos(angler)
t[1, 1] = r * np.sin(angler)
area = triangle_area(t)
print(' %2d %10.4f %10.4f %10.4f %14.6g'
% (i, angled, t[1, 0], t[1, 1], area))
#
# Terminate.
#
print('')
print('TRIANGLE_AREA_TEST')
print(' Normal end of execution.')
return
def triangle_integrals_test():
# *****************************************************************************80
#
# TRIANGLE_INTEGRALS_TEST tests the TRIANGLE_INTEGRALS library.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 22 April 2015
#
# Author:
#
# John Burkardt
#
import platform
print('')
print('TRIANGLE_INTEGRALS_TEST')
print(' Python version: %s' % (platform.python_version()))
print(' Test the TRIANGLE_INTEGRALS library.')
#
# Utilities:
#
i4_to_pascal_test()
i4_to_pascal_degree_test()
pascal_to_i4_test()
r8mat_print_test()
r8mat_print_some_test()
timestamp_test()
trinomial_test()
rs_to_xy_map_test()
xy_to_rs_map_test()
poly_print_test()
poly_power_linear_test()
poly_power_test()
poly_product_test()
#
# Library functions:
#
triangle01_monomial_integral_test()
triangle01_poly_integral_test()
triangle_area_test()
triangle_xy_integral_test()
triangle_monomial_integral_test()
triangle_poly_integral_test()
#
# Terminate.
#
print('')
print('TRIANGLE_INTEGRALS_TEST:')
print(' Normal end of execution.')
return
def triangle_monomial_integral(i, j, t):
# *****************************************************************************80
#
# TRIANGLE_MONOMIAL_INTEGRAL integrates a monomial over an arbitrary triangle.
#
# Location:
#
# http://people.sc.fsu.edu/~jburkardt/py_src/triangle_integrals/triangle_monomial_integral.py
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 23 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer I, J, the exponents of X and Y in the monomial.
# 0 <= I, J.
#
# Input, real T(2,3), the vertices of the triangle.
#
# Output, real Q, the integral of X^I * Y^J over triangle T.
#
import numpy as np
#
# Get map coefficients from reference RS triangle to general XY triangle.
# R = a+b*X+c*Y
# S = d+e*X+f*Y
#
a, b, c, d, e, f = rs_to_xy_map(t)
#
# Compute
# P1(R,S) = (a+b*R+c*S)^i.
# P2(R,S) = (d+e*R+f*S)^j.
#
d1 = 1
p1 = np.array([a, b, c])
dp1, pp1 = poly_power_linear(d1, p1, i)
d2 = 1
p2 = np.array([d, e, f])
dp2, pp2 = poly_power_linear(d2, p2, j)
#
# Compute the product
# P3(R,S) = (a+b*R+c*S)^i * (d+e*R+f*S)^j.
#
d3, p3 = poly_product(dp1, pp1, dp2, pp2)
#
# Compute the integral of P3(R,S) over the reference triangle.
#
q = triangle01_poly_integral(d3, p3)
#
# Multiply by the area of the physical triangle T(X,Y) divided by
# the area of the reference triangle.
#
q = q * triangle_area(t) / 0.5
return q
def triangle_monomial_integral_test():
# *****************************************************************************80
#
# TRIANGLE_MONOMIAL_INTEGRAL_TEST estimates integrals over a triangle.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 23 April 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
print('')
print('TRIANGLE_MONOMIAL_INTEGRAL_TEST')
print(' Python version: %s' % (platform.python_version()))
print(' TRIANGLE_MONOMIAL_INTEGRAL returns the integral Q of')
print(' a monomial X^I Y^J over the interior of a triangle.')
#
# Test 1:
#
t = np.array([
[0.0, 0.0],
[1.0, 0.0],
[0.0, 1.0]])
i = 1
j = 0
print('')
print(' Triangle vertices:')
print(' (X1,Y1) = (%g,%g)' % (t[0, 0], t[0, 1]))
print(' (X2,Y2) = (%g,%g)' % (t[1, 0], t[1, 1]))
print(' (X3,Y3) = (%g,%g)' % (t[2, 0], t[2, 1]))
print(' Integrand = x^%d * y^%d\n' % (i, j))
q = triangle_monomial_integral(i, j, t)
q2 = 1.0 / 6.0
print(' Computed Q = %g' % (q))
print(' Exact Q = %g' % (q2))
#
# Test 2:
#
t = np.array([
[0.0, 0.0],
[1.0, 0.0],
[1.0, 2.0]])
i = 1
j = 1
print('')
print(' Triangle vertices:')
print(' (X1,Y1) = (%g,%g)' % (t[0, 0], t[0, 1]))
print(' (X2,Y2) = (%g,%g)' % (t[1, 0], t[1, 1]))
print(' (X3,Y3) = (%g,%g)' % (t[2, 0], t[2, 1]))
print(' Integrand = x^%d * y^%d\n' % (i, j))
q = triangle_monomial_integral(i, j, t)
q2 = 0.5
print(' Computed Q = %g' % (q))
print(' Exact Q = %g' % (q2))
#
# Test 3:
#
t = np.array([
[-3.0, 0.0],
[6.0, 0.0],
[0.0, 3.0]])
i = 1
j = 0
print('')
print(' Triangle vertices:')
print(' (X1,Y1) = (%g,%g)' % (t[0, 0], t[0, 1]))
print(' (X2,Y2) = (%g,%g)' % (t[1, 0], t[1, 1]))
print(' (X3,Y3) = (%g,%g)' % (t[2, 0], t[2, 1]))
print(' Integrand = x^%d * y^%d\n' % (i, j))
q = triangle_monomial_integral(i, j, t)
q2 = 13.5
print(' Computed Q = %g' % (q))
print(' Exact Q = %g' % (q2))
#
# Test 4:
#
t = np.array([
[0.0, 0.0],
[4.0, 0.0],
[0.0, 1.0]])
i = 1
j = 1
print('')
print(' Triangle vertices:')
print(' (X1,Y1) = (%g,%g)' % (t[0, 0], t[0, 1]))
print(' (X2,Y2) = (%g,%g)' % (t[1, 0], t[1, 1]))
print(' (X3,Y3) = (%g,%g)' % (t[2, 0], t[2, 1]))
print(' Integrand = x^%d * y^%d\n' % (i, j))
q = triangle_monomial_integral(i, j, t)
q2 = 2.0 / 3.0
print(' Computed Q = %g' % (q))
print(' Exact Q = %g' % (q2))
#
# Terminate.
#
print('')
print('TRIANGLE_MONOMIAL_INTEGRAL_TEST')
print(' Normal end of execution.')
return
def triangle_poly_integral(d, p, t):
# *****************************************************************************80
#
# TRIANGLE_POLY_INTEGRAL: polynomial integral over a triangle.
#
# Location:
#
# http://people.sc.fsu.edu/~jburkardt/py_src/triangle_integrals/triangle_poly_integral.py
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 23 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer D, the degree of the polynomial.
#
# Input, real P(M), the polynomial coefficients.
# M = ((D+1)*(D+2))/2.
#
# Input, real T(2,3), the vertices of the triangle.
#
# Output, real Q, the integral.
#
m = ((d + 1) * (d + 2)) // 2
q = 0.0
for k in range(1, m + 1):
km1 = k - 1
i, j = i4_to_pascal(k)
qk = triangle_monomial_integral(i, j, t)
q = q + p[km1] * qk
return q
def triangle_poly_integral_test():
# *****************************************************************************80
#
# TRIANGLE_POLY_INTEGRAL_TEST estimates integrals over a triangle.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 23 April 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
print('')
print('TRIANGLE_POLY_INTEGRAL_TEST')
print(' Python version: %s' % (platform.python_version()))
print(' TRIANGLE_POLY_INTEGRAL returns the integral Q of')
print(' a polynomial over the interior of a triangle.')
#
# Test 1:
# Integrate x over reference triangle.
#
t = np.array([
[0.0, 0.0],
[1.0, 0.0],
[0.0, 1.0]])
d = 1
p = np.array([0.0, 1.0, 0.0])
print('')
print(' Triangle vertices:')
print(' (X1,Y1) = (%g,%g)' % (t[0, 0], t[0, 1]))
print(' (X2,Y2) = (%g,%g)' % (t[1, 0], t[1, 1]))
print(' (X3,Y3) = (%g,%g)' % (t[2, 0], t[2, 1]))
print('')
poly_print(d, p, ' Integrand p(x,y)')
q = triangle_poly_integral(d, p, t)
q2 = 1.0 / 6.0
print('')
print(' Computed Q = %g' % (q))
print(' Exact Q = %g' % (q2))
#
# Test 2:
# Integrate xy over a general triangle.
#
t = np.array([
[0.0, 0.0],
[1.0, 0.0],
[1.0, 2.0]])
d = 2
p = np.array([0.0, 0.0, 0.0, 0.0, 1.0, 0.0])
print('')
print(' Triangle vertices:')
print(' (X1,Y1) = (%g,%g)' % (t[0, 0], t[0, 1]))
print(' (X2,Y2) = (%g,%g)' % (t[1, 0], t[1, 1]))
print(' (X3,Y3) = (%g,%g)' % (t[2, 0], t[2, 1]))
print('')
poly_print(d, p, ' Integrand p(x,y)')
q = triangle_poly_integral(d, p, t)
q2 = 0.5
print('')
print(' Computed Q = %g' % (q))
print(' Exact Q = %g' % (q2))
#
# Test 3:
# Integrate 2-3x+xy over a general triangle.
#
t = np.array([
[0.0, 0.0],
[1.0, 0.0],
[1.0, 3.0]])
d = 2
p = np.array([2.0, -3.0, 0.0, 0.0, 1.0, 0.0])
print('')
print(' Triangle vertices:')
print(' (X1,Y1) = (%g,%g)' % (t[0, 0], t[0, 1]))
print(' (X2,Y2) = (%g,%g)' % (t[1, 0], t[1, 1]))
print(' (X3,Y3) = (%g,%g)' % (t[2, 0], t[2, 1]))
print('')
poly_print(d, p, ' Integrand p(x,y)')
q = triangle_poly_integral(d, p, t)
q2 = 9.0 / 8.0
print('')
print(' Computed Q = %g' % (q))
print(' Exact Q = %g' % (q2))
#
# Test 4:
# Integrate -40y + 6x^2 over a general triangle.
#
t = np.array([
[0.0, 3.0],
[1.0, 1.0],
[5.0, 3.0]])
d = 2
p = np.array([0.0, 0.0, -40.0, 6.0, 0.0, 0.0])
print('')
print(' Triangle vertices:')
print(' (X1,Y1) = (%g,%g)' % (t[0, 0], t[0, 1]))
print(' (X2,Y2) = (%g,%g)' % (t[1, 0], t[1, 1]))
print(' (X3,Y3) = (%g,%g)' % (t[2, 0], t[2, 1]))
print('')
poly_print(d, p, ' Integrand p(x,y)')
q = triangle_poly_integral(d, p, t)
q2 = - 935.0 / 3.0
print('')
print(' Computed Q = %g' % (q))
print(' Exact Q = %g' % (q2))
#
# Terminate.
#
print('')
print('TRIANGLE_POLY_INTEGRAL_TEST')
print(' Normal end of execution.')
return
def triangle_xy_integral(x1, y1, x2, y2, x3, y3):
# *****************************************************************************80
#
# TRIANGLE_XY_INTEGRAL computes the integral of XY over a triangle.
#
# Location:
#
# http://people.sc.fsu.edu/~jburkardt/py_src/triangle_integrals/triangle_xy_integral.py
#
# Discussion:
#
# This function was written as a special test case for the general
# problem of integrating a monomial x^alpha * y^beta over a general
# triangle.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 23 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, real X1, Y1, X2, Y2, X3, Y3, the coordinates of the
# triangle vertices.
#
# Output, real Q, the integral of X*Y over the triangle.
#
#
# x = x1 * ( 1 - xi - eta )
# + x2 * xi
# + x3 * eta
#
# y = y1 * ( 1 - xi - eta )
# + y2 * xi
# + y3 * eta
#
# Rewrite as linear polynomials in (xi,eta):
#
# x = x1 + ( x2 - x1 ) * xi + ( x3 - x1 ) * eta
# y = y1 + ( y2 - y1 ) * xi + ( y3 - y1 ) * eta
#
# Jacobian:
#
# J = [ ( x2 - x1 ) ( x3 - x1 ) ]
# [ ( y2 - y1 ) ( y3 - y1 ) ]
#
# det J = ( x2 - x1 ) * ( y3 - y1 ) - ( y2 - y1 ) * ( x3 - x1 )
#
# Integrand
#
# x * y = ( x1 + ( x2 - x1 ) * xi + ( x3 - x1 ) * eta )
# * ( y1 + ( y2 - y1 ) * xi + ( y3 - y1 ) * eta )
#
# Rewrite as linear combination of monomials:
#
# x * y = 1 * x1 * y1
# + eta * ( x1 * ( y3 - y1 ) + ( x3 - x1 ) * y1 )
# + xi * ( x1 * ( y2 - y1 ) + ( x2 - x1 ) * y1 )
# + eta^2 * ( x3 - x1 ) * ( y3 - y1 )
# + xi*eta * ( ( x2 - x1 ) * ( y3 - y1 ) + ( x3 - x1 ) * ( y2 - y1 ) )
# + xi^2 * ( x2 - x1 ) * ( y2 - y1 )
#
det = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)
p00 = x1 * y1
p01 = x1 * (y3 - y1) + (x3 - x1) * y1
p10 = x1 * (y2 - y1) + (x2 - x1) * y1
p02 = (x3 - x1) * (y3 - y1)
p11 = (x2 - x1) * (y3 - y1) + (x3 - x1) * (y2 - y1)
p20 = (x2 - x1) * (y2 - y1)
q = 0.0
q = q + p00 * triangle01_monomial_integral(0, 0)
q = q + p10 * triangle01_monomial_integral(1, 0)
q = q + p01 * triangle01_monomial_integral(0, 1)
q = q + p20 * triangle01_monomial_integral(2, 0)
q = q + p11 * triangle01_monomial_integral(1, 1)
q = q + p02 * triangle01_monomial_integral(0, 2)
q = q * det
return q
def triangle_xy_integral_test():
# *****************************************************************************80
#
# TRIANGLE_XY_INTEGRAL_TEST tests TRIANGLE_XY_INTEGRAL.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 23 April 2015
#
# Author:
#
# John Burkardt
#
import platform
print('')
print('TRIANGLE_XY_INTEGRAL_TEST')
print(' Python version: %s' % (platform.python_version()))
print(' TRIANGLE_XY_INTEGRAL determines Q, the integral of the')
print(' monomial X*Y over a triangle (X1,Y1), (X2,Y2), (X3,Y3). )')
x1 = 0.0
y1 = 0.0
x2 = 1.0
y2 = 0.0
x3 = 1.0
y3 = 2.0
q = triangle_xy_integral(x1, y1, x2, y2, x3, y3)
print('')
print(' (X1,Y1) = ( %g,%g )' % (x1, y1))
print(' (X2,Y2) = ( %g,%g )' % (x2, y2))
print(' (X3,Y3) = ( %g,%g )' % (x3, y3))
print(' Q = %g' % (q))
print(' (Expecting answer 1/2.')
x1 = 0.0
y1 = 0.0
x2 = 4.0
y2 = 0.0
x3 = 0.0
y3 = 1.0
q = triangle_xy_integral(x1, y1, x2, y2, x3, y3)
print('')
print(' (X1,Y1) = ( %g,%g )' % (x1, y1))
print(' (X2,Y2) = ( %g,%g )' % (x2, y2))
print(' (X3,Y3) = ( %g,%g )' % (x3, y3))
print(' Q = %g' % (q))
print(' (Expecting answer 2/3.')
#
# Terminate.
#
print('')
print('TRIANGLE_XY_INTEGRAL_TEST')
print(' Normal end of execution.')
return
def trinomial(i, j, k):
# *****************************************************************************80
#
# TRINOMIAL computes a trinomial coefficient.
#
# Discussion:
#
# The trinomial coefficient is a generalization of the binomial
# coefficient. It may be interpreted as the number of combinations of
# N objects, where I objects are of type 1, J of type 2, and K of type 3.
# and N = I + J + K.
#
# T(I,J,K) = N! / ( I! J! K! )
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 11 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer I, J, K, the factors.
# All should be nonnegative.
#
# Output, integer VALUE, the trinomial coefficient.
#
from sys import exit
#
# Each factor must be nonnegative.
#
if (i < 0 or j < 0 or k < 0):
print('')
print('TRINOMIAL - Fatal error!')
print(' Negative factor encountered.')
exit('TRINOMIAL - Fatal error!')
value = 1
t = 1
for l in range(1, i + 1):
# value = value * t // l
t = t + 1
for l in range(1, j + 1):
value = value * t // l
t = t + 1
for l in range(1, k + 1):
value = value * t // l
t = t + 1
return value
def trinomial_test():
# *****************************************************************************80
#
# TRINOMIAL_TEST tests TRINOMIAL.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 11 April 2015
#
# Author:
#
# John Burkardt
#
import platform
print('')
print('TRINOMIAL_TEST')
print(' Python version: %s' % (platform.python_version()))
print(' TRINOMIAL evaluates the trinomial coefficient:')
print('')
print(' T(I,J,K) = (I+J+K)! / I! / J! / K!')
print('')
print(' I J K T(I,J,K)')
print('')
for k in range(0, 5):
for j in range(0, 5):
for i in range(0, 5):
t = trinomial(i, j, k)
print(' %4d %4d %4d %8d' % (i, j, k, t))
#
# Terminate.
#
print('')
print('TRINOMIAL_TEST')
print(' Normal end of execution.')
return
def xy_to_rs_map(t):
# *****************************************************************************80
#
# XY_TO_RS_MAP returns the linear map from physical to reference triangle.
#
# Location:
#
# http://people.sc.fsu.edu/~jburkardt/py_src/triangle_integrals/xy_to_rs_map.py
#
# Discussion:
#
# Given the vertices T of an arbitrary triangle in the (X,Y) coordinate
# system, this function returns the coefficients of the linear map
# that sends the vertices of T to (0,0), (1,0) and (0,1) respectively
# in the reference triangle with coordinates (R,S):
#
# R = A + B * X + C * Y;
# S = D + E * X + F * Y.
#
# Reference Element T3:
#
# |
# 1 3
# | |\
# | | \
# S | \
# | | \
# | | \
# 0 1-----2
# |
# +--0--R--1-->
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 22 April 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, real T[3,2], the X and Y coordinates
# of the vertices. The vertices are assumed to be the images of
# (0,0), (1,0) and (0,1) respectively.
#
# Output, real A, B, C, D, E, F, the mapping coefficients.
#
g = ((t[2, 1] - t[0, 1]) * (t[1, 0] - t[0, 0])
- (t[2, 0] - t[0, 0]) * (t[1, 1] - t[0, 1]))
a = (- (t[2, 1] - t[0, 1]) * t[0, 0]
+ (t[2, 0] - t[0, 0]) * t[0, 1]) / g
b = (t[2, 1] - t[0, 1]) / g
c = - (t[2, 0] - t[0, 0]) / g
d = ((t[1, 1] - t[0, 1]) * t[0, 0]
- (t[1, 0] - t[0, 0]) * t[0, 1]) / g
e = - (t[1, 1] - t[0, 1]) / g
f = (t[1, 0] - t[0, 0]) / g
return a, b, c, d, e, f
def xy_to_rs_map_test():
# *****************************************************************************80
#
# XY_TO_RS_MAP_TEST tests XY_TO_RS_MAP.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 22 April 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
print('')
print('XY_TO_RS_MAP_TEST:')
print(' Python version: %s' % (platform.python_version()))
print(' XY_TO_RS_MAP determines the coefficients of the linear map')
print(' from a general triangle in XY coordinates to the reference')
print(' triangle in RS coordinates:')
print(' R = a + b * X + c * Y')
print(' S = d + e * X + f * Y')
t = np.array([
[2.0, 0.0],
[3.0, 4.0],
[0.0, 3.0]])
r8mat_print(3, 2, t, ' XY triangle vertices:')
a, b, c, d, e, f = xy_to_rs_map(t)
print('')
print(' Mapping coefficients are:')
print('')
print(' R = %g + %g * X + %g * Y' % (a, b, c))
print(' S = %g + %g * X + %g * Y' % (d, e, f))
print('')
print(' Apply map to XY triangle vertices.')
print(' Recover RS vertices (0,0), (1,0) and (0,1).')
print('')
for i in range(0, 3):
r = a + b * t[i, 0] + c * t[i, 1]
s = d + e * t[i, 0] + f * t[i, 1]
print(' V(%d) = (%g,%g)' % (i, r, s))
#
# Terminate.
#
print('')
print('XY_TO_RS_MAP_TEST:')
print(' Normal end of execution.')
return
if (__name__ == '__main__'):
timestamp()
triangle_integrals_test()
timestamp()
|
8828a4c23e6bc1a580b0e2b82647a629cdb4652d | LorranSutter/HackerRank | /Mathematics/Geometry/Points_On_a_Line.py | 407 | 3.640625 | 4 | #!/bin/python3
if __name__ == '__main__':
n = int(input())
points = []
for _ in range(n):
x, y = map(int, input().split())
points.append([x, y])
horizontal = [points[k][0] == points[k+1][0] for k in range(n-1)]
vertical = [points[k][1] == points[k+1][1] for k in range(n-1)]
if all(horizontal) or all(vertical):
print('YES')
else:
print('NO')
|
c042dd221e00fd2ad85a1246b512164b31bfbf8d | saulhappy/algoPractice | /python/miscPracticeProblems/Fundamentals/revString.py | 84 | 3.75 | 4 | word = "saul"
def revString(word):
return word[::-1]
print(revString(word))
|
a9d9ad6aec6907e28c53341cec5d5baba2760981 | Rahul91/pytest | /simple_class.py | 290 | 3.59375 | 4 | class Person:
def set_details(self, name, age):
self.name = name
self.age = age
def get_details(self):
return self.name, self.age
obj1 = Person()
obj2 = Person()
obj1.set_details("Rahul", 23)
obj2.set_details("Bittu", 26)
print obj1.get_details()
print obj2.get_details()
|
b9adae0dfb386b2cb47d2336260b32f4819eb46b | LeonVillanueva/Projects | /Daily Exercises/daily_6.py | 1,138 | 4.15625 | 4 | '''
Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock. You're also given a number fee that represents a transaction fee for each buy and sell transaction.
You must buy before you can sell the stock, but you can make as many transactions as you like.
For example, given [1, 3, 2, 8, 4, 10] and fee = 2, you should return 9, since you could buy the stock at 1 dollar, and sell at 8 dollars, and then buy it at 4 dollars and sell it at 10 dollars. Since we did two transactions, there is a 4 dollar fee, so we have 7 + 6 = 13 profit minus 4 dollars of fees.
'''
prices = [10, 3, 2, 8, 5, 12]
def max_price (n, fee)
# assume list is numericals
current_max = 0
hold = n[0]
history = []
for p in n[1:]:
current_max = max (current_max, n[p]-hold-fee)
hold = max(hold, current_max-p)
history.append (current_max, hold)
return current_max, history
profit, history = max_price(prices)
print (profit)
print (history)
|
97bc705cecd26a377627218464f588c38662ef72 | ccjoness/CG_StudentWork | /Skip/unsorted/divisors.py | 581 | 4.34375 | 4 | # Create a program that asks the user for a number and then prints out a list
# of all the divisors of that number. (If you don’t know what a divisor is, it
# is a number that divides evenly into another number. For example, 13 is a
# divisor of 26 because 26 / 13 has no remainder.)
# Remember you can generate a list using range(start, stop)
# range(2,10) == [2,3,4,5,6,7,8,9,10]
num = int(input("Enter any number. "))
def divisor(num):
d_list = []
for x in range(2,num):
if num % x == 0:
d_list.append(x)
return d_list
print(divisor(num))
|
de5f6df4fad4731e677a52c7ee7cf76978f4d9ad | ndbellew/PythonProjects | /OOP/initIntroducion.py | 295 | 3.671875 | 4 | #initIntroducion.py
class Point:
def __init__(self,x,y):
self.move(x,y)
def move(self,x,y):
self.x=x
self.y=y
def reset(self):
self.move(0,0)
# Constructing a Point
point = Point(3, 5)
point.z = 4
print(point.x, point.y, point.z)
point.reset()
print(point.x, point.y, point.z)
|
551a368e955c36d6f4bea32f3b9d18e4ba3039db | LuizFernandoR/CursoPython | /Praticando/Exercicio01.py | 253 | 3.59375 | 4 | lista1 =[1,2,3,4,5,6,7,8,9,10]
lista2 =[10,9,8,7,6,5,4,3,2,1]
soma = 0
produto = 0
for i in lista1:
for j in lista2:
soma= i + j
produto= i * j
print('Lista soma:',soma,'- Lista produto:',produto)
|
b67f259ace3503413d63f5bb4900b1a4dc9fa86a | h4x0rlol/codewars | /playingwithdigits.py | 229 | 3.5 | 4 | def dig_pow(n, p):
res = 0
numbers = list(map(int, str(n)))
for number in numbers:
res += number**p
p = p+1
k = res//n
if(res % n == 0):
return k
return -1
print(dig_pow(212, 6))
|
d14aa4306cb1b10e25342a4b6a4ada32724b0908 | manonansart/rosalind | /fibd.py | 455 | 3.53125 | 4 | # http://rosalind.info/problems/fibd/
import sys
n = int(sys.argv[1])
m = int(sys.argv[2])
if m == 0:
print 0
elif m == 1:
if n == 1:
print 1
else:
print 0
elif n == 1:
print 1
else:
f1 = 1
f2 = 1
f = 1
births = [1, 0]
for i in range(3, n+1):
if i < m+1:
f = f1 + f2
f2 = f1
f1 = f
fm.append(f)
births.append(f1 - f2)
else:
newBirths = sum(births[0:-1])
births.append(f)
births.pop(0)
print sum(births) |
1aec4c2343dcbee8fb344707b0c2f682a43401f4 | drichardson/examples | /python/closure.py | 188 | 3.53125 | 4 | def foo():
print("foo")
for i in range(0, 10):
print("i: {}".format(i))
loop_var = {'val': i}
f = lambda x: print(loop_var.get(x))
f('val')
foo()
|
00d05f4a45b4156647a0763b16edaa78d4ca71de | crowjdh/QuesStudyCabinet | /180518/codefight/arcade/core/JungDongHyun/7. lateRide.py | 320 | 3.609375 | 4 | def lateRide(n):
hours_past = n / 60
minutes_past = n - (hours_past * 60)
result = 0
result += sum_digits(hours_past)
result += sum_digits(minutes_past)
return result
def sum_digits(n):
total = 0
while n > 0:
total += n % 10
n /= 10
return total
|
20dd569c4ad791aca11c9a2ada490ed5515eeff0 | Dylan-Cairns/Package_Delivery_Scheduler | /sort_algorithm.py | 1,388 | 4.0625 | 4 | import data_structures
# this method contains the algorithm which, given a list of packages,
# chooses the order of packages for delivery. time complexity: O(N^2)
def choose_delivery_order(packages_list):
current_location_id = 0
unordered_list = packages_list.copy()
ordered_list = []
total_mileage = 0.0
while len(ordered_list) < len(packages_list):
lowest_distance = 9999
nearest_package = None
for package in unordered_list:
if package not in ordered_list:
current_distance = check_distance(current_location_id, package.get_location_id())
if current_distance < lowest_distance:
lowest_distance = current_distance
nearest_package = package
ordered_list.append(nearest_package)
current_location_id = nearest_package.get_location_id()
total_mileage += lowest_distance
unordered_list.remove(nearest_package)
return ordered_list, total_mileage
# check the distance between two locations. time complexity: O(1)
def check_distance(current_location, check_location):
distances_matrix = data_structures.import_distances_from_csv()
distance = distances_matrix[current_location][check_location]
if distance == '':
distance = distances_matrix[check_location][current_location]
return float(distance)
|
53b217c63d4e486c923a778b2e3ae027351aaf2b | Mohit-Sharma1/Takenmind_Internship_assignments | /Section2/L8 Conditional clause and boolean operations/conditional_and_boolean.py | 538 | 3.59375 | 4 | import numpy as np
x= np.array([100,400,500,600]) #each member pf 'a'
y=np.array([10,15,20,25]) #each member of 'b'
condition=np.array([True,True,False,False]) #each member cond.
#add some boolean expersion
#use loops indirectly to perform this
z=[a if cond else b for a,cond,b in zip(x,condition,y)] #this is some mushkil so we will do by other method
print z
#np.where(#condition,#value for yes, #value for No) #this function is used by the numpy fn.
z2=np.where(condition,x,y)
print z2
z3=np.where(x>0,0,1)
print z3
|
200385e0c3532ed2ba927efa251cea88db7aa2d9 | hopdino/actor-model | /actor_model/chapter06/examples/actors_cooperating_counts.py | 1,032 | 3.53125 | 4 | """
Multiple cooperating actors
本例子是展示多个actor之间的通信.
多个actor 一起数数.
"""
import threading
from actor_model.chapter06.actor_register import ActorRegistry
from actor_model.chapter06.threading import ThreadingActor
class Adder(ThreadingActor):
"""
我负责统计
"""
def add_one(self, i):
print(f"{self} is increasing {i}::{threading.current_thread()}")
return i + 1
class Bookkeeper(ThreadingActor):
"""
我是图书统计员,具体统计给另一个人员Adder来做
"""
def __init__(self, adder):
super().__init__()
self.adder = adder
def count_to(self, target):
i = 0
while i < target:
i = self.adder.add_one(i).get() # 返回下一个值(i+1)
print(f"{self} got {i} back {threading.current_thread()}")
if __name__ == "__main__":
adder = Adder.start().proxy()
bookkeeper = Bookkeeper.start(adder).proxy()
bookkeeper.count_to(10).get()
ActorRegistry.stop_all()
|
63555014647d9e6e96cab2a742cd6ee0c5b5c569 | april9288/ds_algorithms | /Sort Algorithms/selection.py | 274 | 4 | 4 | def selectionSort(array):
for i in range(0, len(array)):
minimum = i
for j in range(i+1, len(array)):
if array[j] < array[minimum]:
minimum = j
temp = array[minimum]
array[minimum] = array[i]
array[i] = temp
return print(array)
selectionSort([6,5,0,1]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.