blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
714da2929f26a6b2788bad27279aec26de30f66b
Ashok-Mishra/python-samples
/python exercises/dek_program053.py
747
4.28125
4
# !/user/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # Define a class named Rectangle which can be constructed by a length and # width. The Rectangle class has a method which can compute the area. # Hints: # Use def methodName(self) to define a method. class Ractangle(object): def __init__(self, length, width): self.length = length self.width = width def areaOfRactangle(self): return self.length * self.width def main(): ractangleObj = Ractangle( int(raw_input('Enter Value for length of Ractangle :')), int(raw_input('Enter Value for Width of Ractangle :'))) print 'Area of Ractangle is : ', ractangleObj.areaOfRactangle() if __name__ == '__main__': main()
1e5e2cbb3083c6a9ca4c91d4b71efe964f987bb9
Ashok-Mishra/python-samples
/python exercises/dek_program094.py
725
4.0625
4
# !/usr/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # program094: # With a given list [12,24,35,24,88,120,155,88,120,155], write a program # to print this list after removing all duplicate values with original # order reserved. # Hints: # Use set() to store a number of values without duplicate. def main(numbers): newlist = [] uniqueD = set() # print "asdfasdf ", set(lst) # set(list) unuseful since "with original order reserved" required. for num in numbers: if num not in uniqueD: uniqueD.add(num) newlist.append(num) print newlist if __name__ == '__main__': main([12, 24, 35, 24, 88, 120, 155, 88, 120, 155])
ef2f0b6305acf196994ca53109035688722d342e
Ashok-Mishra/python-samples
/python exercises/dek_program001.py
913
4.125
4
#!/user/bin/python # -*- coding: utf-8 -*- # Author : (DEK) Devendra Kavthekar # program001 : divisibleBy7not5 # Write a program which will find all such numbers which are divisible by 7 # but are not a multiple of 5, between 2000 and 3200 (both included). # The numbers obtained should be printed in a comma-separated sequence # on a single line. # Hints: # Consider use range(#begin, #end) method def divisibleBy7not5(startLimit, endLimit): result = [] for number in range(startLimit, endLimit + 1): # "endLimit + 1" bcoz limits too,should be included # print number if number % 7 == 0 and number % 5 != 0: result.append(number) return result def main(): print 'numbers divisible by 7 and not 5' print divisibleBy7not5(int(raw_input('Enter Value:')), int(raw_input('Enter Value:'))) if __name__ == '__main__': main() # checked
ae0fed29cb1b49c8deb8c0807df7f222c6aae61a
Ashok-Mishra/python-samples
/python exercises/dek_program008.py
722
4.28125
4
#!/user/bin/python # -*- coding: utf-8 -*- # Author : (DEK) Devendra Kavthekar # program008 : # Write a program that accepts a comma separated # sequence of words as input and prints the words # in a comma-separated sequence after sorting them alphabetically. # Suppose the following input is supplied to the program: # without,hello,bag,world # Then, the output should be: # bag,hello,without,world # Hints: # In case of input data being supplied to the question, it should be # assumed to be a console input. def main(): print "sample input ", 'without,hello,bag,world' str = raw_input('Enter : ') li1 = str.split(',') # print li1 li1.sort() print li1 if __name__ == '__main__': main() # checked
bb8be1f8046be290b5a453dcae9774bbac3df864
analBrotherhood/UCrypt-CLI
/ucrypt.py
1,649
4.21875
4
alphabet = '=>?@[\\]678hiVWlmABCDEpqrsjkJKL01234RюБжэяЩРтшЦМйu&UмоПtлС5хКцvЧёgчwSещFTвНZ#ОькТЖЯЁфбГъуЗиргШЪ$ЮХыЫIXHЕ!ВДG"Фа%АYсЙЬИздЛoxyz<MNOPQnУЭпн9abcdef^_`{|}~ \'()*+,-./:;' def encrypt(): enc = '' msg = input('Type message for encrypting: ') key = input('Enter key for encrypting: ') for c in msg: if c in alphabet: s1 = alphabet.find(c) s1 = (s1 + int(key)) % len(alphabet) enc += alphabet[s1] else: enc += c print('Encrypted message: ' + enc) print('Key, what used for encrypting: ' + key) print('Goodbye!') def decrypt(): dec = '' msg = input('Type message for decrypting: ') key = input('Enter key for decrypting: ') for c in msg: if c in alphabet: s1 = alphabet.find(c) s1 = (s1 - int(key)) % len(alphabet) dec += alphabet[s1] else: dec += c print('Decrypted message: ' + dec) print('Key, what used for decrypting: ' + key) print('Goodbye!') def main(): print(''' <====== UCrypt v1.0 ======> What do you want? 0 - Encrypt 1 - Decrypt''') k = input('\nYou choice (0/1): ') try: int(k) except ValueError: print('Error #0. Entered choice not a number.') exit() if k == '0': encrypt() elif k == '1': decrypt() else: print('Error #1. Enter 0 or 1 for choosing.') exit() try: main() except KeyboardInterrupt: print('\nGood bye!') exit()
5a18389a8063d941ddd7421de6680da28984eeb6
jacokyle/CIS457_Projects
/Project_1/serverDir/server.py
5,340
3.75
4
# Project 1 - Building an FTP Server # CIS 457 - Data Communications # Authors: Kyle Jacobson, Logan Jaglowski # Date of Submission: October 26, 2020 # The server program binds to a port and listens to requests from a client. import os import socket from pathlib import Path HOST = socket.gethostname() # The socket's hostname or IP address. PORT = 5000 # The port used by the socket. # Initializes the filename for file retrieval and file sending. fileName = " " # Allow the server to engage in the send file action. def sendFile(): programState = "retrieveFile" while programState == "retrieveFile": # Displays the list of files in the server directory. global fileName serverFileList = os.listdir(os.getcwd()) serverDir = '\n'.join(serverFileList) # Parse through each file in the list. for _ in serverDir: fileName = serverDir.splitlines() # Print the list from the server. print("\nServer Directory Files:") print(serverDir) # Ask the user the retrieve file question. sendingFile = input(str("\nEnter a file to send to the client: ")) # Checks if the inputted file matches what was sent by the client. if sendingFile in fileName and len(sendingFile) >= 1: # Read the designated file in the server directory. fileSelection = open(sendingFile, "rb") fileData = fileSelection.read(1024) conn.send(fileData) # Confirms a file was sent to the client and sets back to normal. print('\nSent a file to:', addr) programState = "normal" # Warn the user a file doesn't exist and try again. elif sendingFile not in fileName and len(sendingFile) >= 1: print("\nIMPORTANT: The file does not exist in the directory.") # Refuse whitespace. else: print("\nIMPORTANT: Please input a filename.") def retrieveFile(): programState = "retrieveFile" while programState == "retrieveFile": # Displays the list of files in the client directory. global fileName home = str(Path.home()) + "\PycharmProjects\FTPServer\clientDir" clientFileList = os.listdir(home) clientDir = '\n'.join(clientFileList) # Parse through each file in the list. for _ in clientDir: fileName = clientDir.splitlines() # Print the list from the client. print("\nClient Directory Files:") print(clientDir) # Ask the user the send file question. retrievingFile = input(str("\nEnter a file to receive from the client: ")) # Checks if the inputted file matches what was sent by the client. if retrievingFile in fileName and len(retrievingFile) >= 1: # Write the designated file to the client directory. fileSelection = open(retrievingFile, "wb") fileData = conn.recv(1024) fileSelection.write(fileData) fileSelection.close() # Sends a signal to the client to continue interaction. conn.send(fileData) # Confirms a file was received from the client and sets back to normal. print('\nReceived a file from:', addr) programState = "normal" # Warn the user a file doesn't exist and try again. elif retrievingFile not in fileName and len(retrievingFile) >= 1: print("\nIMPORTANT: The file does not exist in the directory.") # Refuse whitespace. else: print("\nIMPORTANT: Please input a filename.") # Displays the list of files in the server directory. def listFiles(connection): directory = os.getcwd() fileList = os.listdir(directory) message = '\n'.join(fileList) connection.sendall(message.encode()) print('Listed files for:', addr) # Builds the connection with the client and responds to selected options. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() # Initializes the connection with the client. conn, addr = s.accept() with conn: while True: # Decodes the client information for the server. data = conn.recv(1024).decode() # Continue listening to future connections. if not data: conn, addr = s.accept() # Print whenever a client has connected to the server. if data == '1': print('Connected by:', addr) # When client chooses to list files, list the files in the current directory. if data == '2': listFiles(conn) # When client chooses to retrieve a file, send the file to the client. if data == '3': sendFile() # When client chooses to send a file, accept the file from the client. if data == '4': retrieveFile() # When client chooses to close the program, shutdown the server. if data == '5': print('Disconnected from:', addr) # When client chooses to close the program, shutdown the server. if data == '6': print('Shutting down server...') conn.close() exit()
046bd214c938e63595f3d9fdeed82ecf1327b6b7
ayushtiwari7112001/Rolling-_dice
/Dice_Roll_Simulator.py
640
4.4375
4
#importing modual import random #range of the values of dice min_val = 1 max_val = 6 #to loop the rolling through user input roll_again = "yes" #loop while roll_again == "yes" or roll_again == "y": print("Roll the dices...") print("** The values are **") #generating and printing 1st random integer from 1 to 6 print(random.randint(min_val,max_val)) #generating and printing 2nd random integer from 1 to 6 print(random.randint(min_val, max_val)) #asking user to roll the dice again. Any input other than yes or y will terminate the loop roll_again=input("Roll the dices again (yes/no) or (y/n) ")
86a59878b82707a40a49eb27a362d8f666eb437d
Mikemike-22/Password-Locker
/details.py
1,109
3.859375
4
class Details: ''' class generating new instances of Details ''' def __init__(self,first_name,last_name,email): # properties for the objects self.first_name = first_name self.last_name = last_name self.email = email details_list=[] def save_details(self): """ method saves contact objects into details_list """ Details.details_list.append(self) def delete_details(self): """ delete method deletes a saved detail """ Details.details_list.remove(self) @classmethod def find_by_first_name(cls,first_name): ''' method that takes in first name and returns an email ''' for details in cls.details_list: if details.first_name == first_name: return details @classmethod def details_exist(cls,email): ''' method that checks if details exist from the details list ''' for details in cls.details_list: if details.email == email: return True return False
8f3989945afd0defa4477c3955d38869dfad125d
changqing1234/learning
/python语法-学习/tuple_and_list.py
222
3.96875
4
a_tuple = (12, 3, 4, 5, 6) another_tuple = 2,4, 6, 7, 8 a_list = [2,3, 4,6, 8] for content in a_list: print(content) for index in range(len(a_list)): print('index=', index, 'number in list=', a_list[index])
949d5610a81c4092c76eee5a047f3b06cdfe4f3a
changqing1234/learning
/机器学习 -学习/一元线性回归例子.py
1,338
3.6875
4
import numpy as np import matplotlib.pyplot as plt #原理地址 https://www.jianshu.com/p/d8a4d3b9ded0 """ 利用 Python 实现线性回归模型 """ class LinerRegressionModel(object): def __init__(self, data): self.data = data self.x = data[:, 0] self.y = data[:, 1] def log(self, a, b): print("计算出的线性回归函数为:\ny = {:.5f}x + {:.5f}".format(a, b)) def plt(self, a, b): plt.plot(self.x, self.y, 'o', label='data', markersize=10) plt.plot(self.x, a * self.x + b, 'r', label='line') plt.legend() plt.show() def least_square_method(self): """ 最小二乘法的实现 """ def calc_ab(x, y): sum_x, sum_y, sum_xy, sum_xx = 0, 0, 0, 0 n = len(x) for i in range(0, n): sum_x += x[i] sum_y += y[i] sum_xy += x[i] * y[i] sum_xx += x[i]**2 a = (sum_xy - (1/n) * (sum_x * sum_y)) / (sum_xx - (1/n) * sum_x**2) b = sum_y/n - a * sum_x/n return a, b a, b = calc_ab(self.x, self.y) self.log(a, b) self.plt(a, b) data = np.array([[1, 2.5], [2, 3.3], [2.5, 3.8],[3, 4.5], [4, 5.7], [5, 6]]) model = LinerRegressionModel(data) model.least_square_method()
83d5c61d22d614005973eb782b4da2fc3e7371ac
kenpuca/db.science.uoit.ca
/courses/algorithms/mst/code/mst.py
1,916
3.53125
4
def minimal_edge(H, V0): """pick an edge with the minimal weight from V0 to the rest of the nodes""" w_min = None e_min = None for e in H.E.keys(): if e[0] in V0 and e[1] not in V0: w = H.E[e]["weight"] if w_min == None or w < w_min: e_min = e w_min = w return e_min def prims(G, debug=None): "returns a list of edges" tree_nodes = set() tree_edges = set() # start with an arbitrarily picked vertex N = len(G.V) v = G.V.keys()[0] tree_nodes.add(v) for i in range(N-1): if debug: debug(i, tree_nodes, tree_edges) e = minimal_edge(G, tree_nodes) if not e: print "graph is not fully connected" return tree_edges tree_nodes.add(e[1]) tree_edges.add(e) if debug: debug(i, tree_nodes, tree_edges) return tree_edges #================================ # Kruskal #================================ def find_set(partition, v): for i,p in enumerate(partition): if v in p: return i return None def join_sets(partition, i1, i2): p1 = partition[i1] p2 = partition[i2] j1 = min(i1, i2) j2 = max(i1, i2) partition[j2:j2+1] = [] # remove the later one partition[j1:j1+1] = [p1 | p2] def kruskal(G, debug=None): "returns a list of edges" # get the edges and short by the weights tree_edges = set() edges = [e for e in G.E.keys() if e[0] < e[1]] edges.sort(key=lambda e: G.E[e]["weight"]) partition = [set([v]) for v in G.V.keys()] for i,e in enumerate(edges): if len(partition) == 1: break i1 = find_set(partition, e[0]) i2 = find_set(partition, e[1]) if not i1 == i2: join_sets(partition, i1, i2) tree_edges.add(e) if debug: debug(i, None, tree_edges) return tree_edges
641c65e39fb210b8d7403b4562be7429e2444017
bewakes/bewakes
/journal/helpers.py
438
3.796875
4
def xor_encrypt(string, password): """ Encrypt the string with password """ passlen = len(password) chunks = [string[x:x+passlen] for x in range(0,len(string), passlen)] xored = [xor_strings(password, x) for x in chunks] return "".join(xored) def xor_strings(s1, s2): """ xor two strings """ zipped = zip(s1, s2) xored = [chr(ord(x)^ord(y)) for (x, y) in zipped] return "".join(xored)
dd46f1d183a105d8aec13e26ae9cb6a756b8e064
liu13722002716/python-interview
/面试题/位运算符/191 位1的个数.py
1,611
3.703125
4
""" :Author: Mr.Liu :Create: 2020/6/29 9:30 :Github: https://XXXXXXXX Copyright (c) 2020,Mr.Liu Group All Rights Reserved. """ """ 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。 示例 1: 输入:00000000000000000000000000001011 输出:3 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。 示例 2: 输入:00000000000000000000000010000000 输出:1 解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。 示例 3: 输入:11111111111111111111111111111101 输出:31 解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1' 提示: 请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。 在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3。 进阶: 如果多次调用这个函数,你将如何优化你的算法? """ class Solution: def hammingWeight(self, n: int) -> int: count = 0 while n != 0: n = n & (n - 1) count += 1 return count if __name__ == '__main__': a = Solution() print(a.hammingWeight(10000111111111111101))
048140f0b4c6212182255ac8b2a4ea344c842f66
liu13722002716/python-interview
/面试题/位运算符/136 只出现一次的数字.py
749
3.875
4
""" :Author: Mr.Liu :Create: 2020/6/29 10:12 :Github: https://XXXXXXXX Copyright (c) 2020,Mr.Liu Group All Rights Reserved. """ """ 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。 说明: 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? 示例 1: 输入: [2,2,1] 输出: 1 示例 2: 输入: [4,1,2,1,2] 输出: 4 """ from typing import List class Solution: def singleNumber(self, nums: List[int]) -> int: res = 0 for i in nums: res = res ^ i return res if __name__ == '__main__': s = Solution() print(s.singleNumber([2,2,1]))
2620868cedaaddc8b8270c31ad5af040790f5958
liu13722002716/python-interview
/面试题/位运算符/477 汉明距离总和.py
1,755
3.5625
4
""" :Author: Mr.Liu :Create: 2020/6/29 10:29 :Github: https://XXXXXXXX Copyright (c) 2020,Mr.Liu Group All Rights Reserved. """ """ 两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。 计算一个数组中,任意两个数之间汉明距离的总和。 示例: 输入: 4, 14, 2 输出: 6 解释: 在二进制表示中,4表示为0100,14表示为1110,2表示为0010。(这样表示是为了体现后四位之间关系) 所以答案为: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. 注意: 数组中元素的范围为从 0到 10^9。 数组的长度不超过 10^4。 """ from typing import List class Solution: def totalHammingDistance(self, nums: List[int]) -> int: count = 0 for i in range(len(nums)): for j in range(i+1,len(nums)): a = nums[i] ^ nums[j] while a != 0: a = a & (a - 1) count += 1 return count if __name__ == '__main__': s = Solution() print(s.totalHammingDistance([4, 14, 2])) class Solution: def totalHammingDistance(self, nums: List[int]) -> int: res = 0 for i in range(32): # O(32) count_0 = 0 count_1 = 0 for j in range(len(nums)): if (nums[j] >> i) & 1 is not 0: # 每个数右数第 i 位的汉明距离 count_1 += 1 # 第 j 个数右移 i 位,和 1 做位与运算,只关注最后一位 else: count_0 += 1 res += count_0 * count_1 return res if __name__ == '__main__': s = Solution() print(s.totalHammingDistance([4, 14, 2]))
93278240e775bbba67da1572331d7a1d3cb279db
YeomeoR/codewars-python
/sum_of_cubes.py
656
4.25
4
# Write a function that takes a positive integer n, sums all the cubed values from 1 to n, and returns that sum. # Assume that the input n will always be a positive integer. # Examples: # sum_cubes(2) # > 9 # # sum of the cubes of 1 and 2 is 1 + 8 ### from cs50 video python, lecture 2 # def sum_cubes(n): # cubed = [] # i = 1 # while (i <= n): # cubed.append(i**3) # i+=1 # print(sum(cubed)) def sum_cubes(n): return sum(i**3 for i in range(0,n+1)) print(sum_cubes(1), 1) print(sum_cubes(2), 9) print(sum_cubes(3), 36) print(sum_cubes(4), 100) print(sum_cubes(10), 3025) print(sum_cubes(123), 58155876)
4f481dd9a6205e9979b2f9f17103dd3816a226ab
YeomeoR/codewars-python
/count_by_step.py
827
4.21875
4
# Implement a function named generateRange(min, max, step), which takes three arguments and generates a range of integers from min to max, with the step. The first integer is the minimum value, the second is the maximum of the range and the third is the step. (min < max) # def generate_range(min, max, step): # listed = [] # rangey = range(min,max +1,step) # for n in rangey: # listed.append(n) # return listed def generate_range(min, max, step): return list(range(min, max + 1, step)) print(generate_range(1, 10, 1), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(generate_range(-10, 1, 1), [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1]) # print(generate_range(1, 15, 20), [1]) # print(generate_range(1, 7, 2), [1, 3, 5, 7]) # print(generate_range(0, 20, 3), [0, 3, 6, 9, 12, 15, 18])
92b874bc57e471491517a2c95f8c90f8c45c8531
YeomeoR/codewars-python
/count_of_positives_sum_of_negatives.py
1,223
3.953125
4
# Given an array of integers. # Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers. # If the input array is empty or null, return an empty array. # Example # For input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15], you should return [10, -65]. # def count_positives_sum_negatives(arr): # store numbers > 0 # store numbers < 0 # store result # iterate over arr # add/append pos_numbers.count() to result # add/append sum_neg_numbers to result def count_positives_sum_negatives(arr): pos = 0 neg = [] lst = list() for ele in arr: if ele > 0: pos += 1 elif ele <= 0: neg.append(ele) if len(arr) == 0: return lst return [pos, sum(neg)] print(count_positives_sum_negatives([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]),[10,-65]) print(count_positives_sum_negatives([0, 2, 3, 0, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14]),[8,-50]) print(count_positives_sum_negatives([1]),[1,0]) print(count_positives_sum_negatives([-1]),[0,-1]) print(count_positives_sum_negatives([0,0,0,0,0,0,0,0,0]),[0,0]) print(count_positives_sum_negatives([]),[])
489f6db924c5b734943ac905a4483251a39171d6
W-R-Ramirez/Scrabble-Solver
/board.py
486
3.703125
4
import Tkinter from starter import numbers_to_letters # Creates the GUI for the board before the game root = Tkinter.Tk() canvas = Tkinter.Canvas(root, width = 550, height = 550) canvas.grid() for i in range(9): for j in range(9): column = j+1 v = Tkinter.StringVar() name = numbers_to_letters[column] + str(i+1) print name name = Tkinter.Entry(canvas, width =4 , textvariable = v) name.grid(row = i, column = j) root.mainloop()
3d40b4229c78f200c882547349bf5ad433a87908
goruma/CTI110
/P2HW1_PoundsKilograms_AdrianGorum.py
586
4.40625
4
# Program converts pounds value to kilograms for users. # 2-12-2019 # CTI-110 P2HW1 - Pounds to Kilograms Converter # Adrian Gorum # #Pseudocode #input pound amount > calculate pound amount divided by 2.2046 > display #conversion in kilograms #Get user input for pound amount. poundAmount = float(input('Enter the pound amount to be converted: ')) #Calculate the kilogram amount as pound amount / 2.2046. kilogramAmount = poundAmount / 2.2046 #Display the pound amount as kilograms. print('The pound amount converted to kilograms is: ', format(kilogramAmount, ',.3f'))
1ef83617a069d51eb924275376f133f4c323d375
goruma/CTI110
/P4HW4_Gorum.py
796
4.3125
4
# This programs draws a polygonal shape using nested for loops # 3-18-19 # P4HW4 - Nested Loops # Adrian Gorum # def main(): #Enable turtle graphics import turtle #Set screen variable window = turtle.Screen() #Set screen color window.bgcolor("red") #Pen Settings myPen = turtle.Turtle() myPen.shape("arrow") myPen.speed(10) myPen.pensize(8) myPen.color("yellow") #Nested loop to create square and then iterate the square 8 times at 45 degree angle for x in range(8): for y in range(4): #Create square shape myPen.forward(100) myPen.left(90) #Turn square 45 degrees to the left to start next iteration myPen.left(45) #Program Start main()
37cf173edeedd27a53151cc74fcf50f42293d5b5
nawazyarkhan/python-challenge
/PyBank/main.py
2,338
3.5
4
#### Import dependencies for os.path.join() import os import csv ### Read in a .csv file csv_file=os.path.join("Resources", "budget_data.csv") output_path=os.path.join("analysis","financial_analysis.csv") #define variables month_total=0 change_month=[] revenue_total=0 greatest_value=0 revenue=[] revenue_previous=0 greatest_decrease=["",9999999] greatest_increase=["",0] change_revenue_list=[] change_in_revenue=0 total_amount=[] highest_profit=0 revenue_average=0 with open(csv_file,"r") as csv_file: csv_reader=csv.reader(csv_file,delimiter=',') #skip header next(csv_reader) for row in csv_reader: #add months month_total +=1 revenue_total=revenue_total+int(row[1]) change_in_revenue=float(row[1]) - revenue_previous revenue_previous =float(row[1]) change_revenue_list=change_revenue_list+[change_in_revenue] change_month=[change_month] + [row[0]] if change_in_revenue>greatest_increase[1]: greatest_increase[1]=change_in_revenue greatest_increase[0]=row[0] if change_in_revenue<greatest_decrease[1]: greatest_decrease[1]=change_in_revenue greatest_decrease[0]=row[0] revenue_average= sum(change_revenue_list)/len(change_revenue_list) with open(output_path,'w', newline='') as csvwrite: csvwriter=csv.writer(csvwrite, delimiter=' ') csvwriter.writerow(['Financial Analysis']) csvwriter.writerow(['------------------------']) csvwriter.writerow(['Total Months: %d' % month_total]) csvwriter.writerow(['Total Revenue: $%d' % revenue_total]) csvwriter.writerow(['Average Revenue Change: $%d' % revenue_average]) csvwriter.writerow(['Greatest Increase in Revenue:%s ($%s)' % (greatest_increase[0], greatest_increase[1]) ]) csvwriter.writerow(['Greatest decrease in Revenue:%s ($%s)' % (greatest_decrease[0],greatest_decrease[1]) ]) print(f'Financial Analysis') print(f'------------------------') print("Total Months: %d" % month_total) print("Total Revenue: $%d " % revenue_total) print("Average Revenue Change: $%d" % revenue_average) print("Greatest Increase in revenue: %s ($%s)" % (greatest_increase[0], (greatest_increase[1]))) print("Greatest decrease in revenue:%s ($%s)" % (greatest_decrease[0], (greatest_decrease[1])))
9d40a535b1548c9a9d2893bfec30964048843d43
sid597/vadaPav
/transform.py
903
3.53125
4
from PIL import Image import os ''' Rotate and flip the images present into the resized folder ''' ctr = len(os.listdir('/home/siddharth/vadaPav/resized/')) # no of images image_path = '/home/siddharth/vadaPav/resized/' nctr = 900 def rotate(img_path): l = [90,180,270] for degree in l: try: img = Image.open(img_path) img = img.rotate(degree, expand = 1) img.save('/home/siddharth/vadaPav/rotated/' + str(ctr) + str(degree) + '.jpg') except: print "I tried" def flip(img_path): try: img = Image.open(img_path) img = img.transpose(Image.FLIP_LEFT_RIGHT) img.save('/home/siddharth/vadaPav/flip/' + str(nctr) + '.jpg') except: print "I Tried" for i in (os.listdir(image_path)): print i # rotate(image_path + i) flip(image_path + i) # ctr += 1 nctr+=1
f3de93f96f4247c3bccba5f699eadd168e4439d0
vincent1879/Python
/MITCourse/ps1_Finance/PS1-1.py
844
4.125
4
#PS1-1.py balance = float(raw_input("Enter Balance:")) AnnualInterest = float(raw_input("Enter annual interest rate as decimal:")) MinMonthPayRate = float(raw_input("Enter minimum monthly payment rate as decimal:")) MonthInterest = float(AnnualInterest / 12.0) TotalPaid = 0 for month in range(1,13): print "Month", str(month) MinMonthPay = float(balance * MinMonthPayRate) print "Minimum monthly payment: $", str(round(MinMonthPay, 2)) InterestPaid = float(balance * MonthInterest) PrincipalPaid = float(MinMonthPay - InterestPaid) print "Principle paid:$", str(round(PrincipalPaid, 2)) TotalPaid += MinMonthPay balance = balance - PrincipalPaid print "Remaining balance: $", str(round(balance, 2)) print "RESULT:" print "Total amount paid:$", str(round(TotalPaid, 2)) print "Remaining balance:$", str(round(balance, 2))
21f9e3f2fdbd00211d4c1d77eaaefcec9f9c627a
fadetoblack72/PracticeRepo
/problems.py
1,013
3.796875
4
"""" given a list of numbers "nums", and a target number "target" finds the indices of the first two numbers in nums whose sum = target """ def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(0, len(nums)): for j in range(i + 1, len(nums)): if nums[i]+nums[j] == target: return [i, j] #Checks to see if the given integer, x, is a palindrome def isPalindrome(x): """ :type x: int :rtype: bool """ if x < 0: return False else: return (x == int(str(x)[::-1])) """ given a sorted array, nums returns the length of nums with duplicates removed """ def removeDuplicates(nums): """ :type nums: List[int] :rtype: int """ i = 1 while i < len(nums): if nums[i] == nums[i-1]: del nums[i] else: i += 1 return len(nums) #problems solved here found at leetcode.com
ff90bd31a30d71b3b60b5f66cd626a4251598b48
melvin3113/lets-upgrade-python-assignment
/python assignment.py
714
3.96875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: print("hello") # In[3]: print("hello python") # In[6]: print(""" ()()()()()(~~~~"") """) # In[7]: print("hy\thello") # In[8]: print("hy\nhello") # In[9]: name="mel" age="20" print("my name is",name,"and of age",age) # In[11]: print(f"my name is {name} of age { age}") # In[12]: a=10 b=10 c=a+b print(c) # In[13]: b=2 d=a**b print(d) # In[14]: print(a-b,a/b,a*b,a//b) # In[19]: a==b,a<=b,a>b,a!=b # In[20]: a|b # In[22]: a=16 b=1 a|b # In[23]: bin(a) # In[24]: a>b or b>a # In[25]: a>b and b>a # In[28]: x="abababab" "a" not in x # In[29]: 5+10/2*2 # In[31]: (5+(10/2))*2 # In[ ]:
f36288e8a5623ec4dcfaff80f5891b5a0e2d96f4
vijayb95/blackjackSimplified
/blackjack.py
7,983
3.734375
4
import random, time userCards = [] def main(): print("**************************** Welcome to BlackJack ****************************") count = 0 user = getUser() print(f"\nHi {(user.user).capitalize()}, your current balance in BlackJack wallet is ${user.balance}\n") while True: time.sleep(1.5) deck = Deck() deck.shuffle() betAmt = bet(user) print("\nLet the Game Begins!\n\nLoading... ") time.sleep(3) dealerCards = [] userTotal = 0 dealerTotal = 0 while True: if count == 0: count += 1 userCards.append(deck.drawCard(userTotal)) userCards.append(deck.drawCard(userTotal)) dealerCards.append(deck.drawCard(dealerTotal)) dealerCards.append(deck.drawCard(dealerTotal)) userTotal = total(userCards) print(f"\nThe Cards {user.user.capitalize()} have are: ") for card in userCards: card.show() time.sleep(0.5) print(f"\nThe total value of your card is {userTotal} points\n") time.sleep(1) print(f"The Cards Dealer have are: ") dealerCards[0].show() print("This card is hidden\n") dealerTotal = total(dealerCards) else: time.sleep(1) choice = input("You wanna hit or stand? (H for hit, S for stand): ") if choice.upper() == 'H': time.sleep(0.5) print("You chose to Hit") userCards.append(deck.drawCard(userTotal)) userTotal = total(userCards) print(f"\nThe Cards {user.user.capitalize()} have are: ") for card in userCards: card.show() time.sleep(0.5) print(f"\nThe total value of your card is {userTotal} points\n") if bust(userTotal): break else: if dealerTotal < userTotal and dealerTotal < 17: while True: if dealerBust(dealerTotal): time.sleep(1) Player.deposit(user, (betAmt*2)) break else: if dealerTotal < userTotal and dealerTotal < 17: time.sleep(1) dealerCards.append(deck.drawCard(dealerTotal)) print(f"The Cards Dealer have are: ") for card in dealerCards: card.show() time.sleep(0.5) dealerTotal = total(dealerCards) print(f"\nThe total value of dealer's card are {dealerTotal}.\n") elif draw(dealerTotal, userTotal): time.sleep(1) for card in dealerCards: card.show() time.sleep(0.5) dealerTotal = total(dealerCards) print(f"\nThe total value of dealer's card are {dealerTotal}.\n") Player.deposit(user, betAmt) break else: print("You've won the match!!") time.sleep(1) Player.deposit(user, (betAmt*2)) break break elif draw(dealerTotal, userTotal): time.sleep(1) for card in dealerCards: card.show() time.sleep(0.5) dealerTotal = total(dealerCards) print(f"\nThe total value of dealer's card are {dealerTotal}.\n") Player.deposit(user, betAmt) break else: print("\nYou've won the match!!\n") time.sleep(1) Player.deposit(user, (betAmt*2)) break if replay(): userCards.clear() count = 0 continue else: break def getUser(): amount = 0 name = "" while amount == 0: name = input("Please enter your name: ") amount = int(input("Please enter the amount you want to add to your wallet(in tenths position): $")) user = Player(name, amount) return user def replay(): response = input("Press Y to replay: ") if response.upper() == "Y" or response.upper() == "YES": return True return False def total(cardList): total = 0 for c in cardList: total += c.value return total def bet(user): while True: amt = int(input("Choose your bet amount: $")) if amt <= user.balance: print(f"The amount you chose to bet is ${amt}.") time.sleep(0.5) Player.withDraw(user,amt) break else: print(f"The available balance in your wallet is {user.balance}") print("Please try again...") time.sleep(0.5) continue return amt def bust(total): if total > 21: if 11 in userCards: for i in range(len(userCards)): if userCards[i] == 11: userCards[i] == 1 return False time.sleep(1) print("You're bust, your point is above 21\n") time.sleep(0.5) print("You've lost your money\n") return True return False def dealerBust(total): if total > 21: time.sleep(1) print("The dealer is bust, you won the game!!\n") time.sleep(0.75) print("Soon winning bonus will be credited to your BlackJack Wallet.\n") return True return False def draw(dealer, user): if dealer == user: print("The match is draw!") return True return False class Card: def __init__(self, name, value): self.suit = name self.value = value def show(self): print(f"{self.suit} of {self.value}") class Deck: def __init__(self): self.cards = [] self.build() def build(self): self.cards = [] for s in ["Spades", "Diamonds", "Hearts", "Clubs"]: for v in range(1, 14): self.cards.append(Card(s, v)) def shuffle(self): for i in range(len(self.cards) - 1, 0, -1): r = random.randint(0, i) self.cards[i], self.cards[r] = self.cards[r], self.cards[i] def show(self): for c in self.cards: c.show() def drawCard(self, points): card = self.cards.pop() if card.value > 10: card.value = 10 elif card.value == 1: if points < 11: card.value = 11 return card class Player: def __init__(self, name, balance = 0): self.user = name self.balance = balance def deposit(self, amount): self.balance += amount print(f"Amount of ${amount} is added, your current balance is ${self.balance}") def withDraw(self, amount): self.balance -= amount print(f"You've withdrawn ${amount}, the available balance in your wallet is ${self.balance}") if __name__ == "__main__": main()
11422b0078063a75e2fa014861a4d25bdc04080f
pisskidney/tc
/199_2/all.py
739
3.5
4
#!/usr/bin/python class StringMult(object): def times(self, s, k): res = "" if not s or not k: return "" if k > 0: for i in range(k): res += s else: for i in range(abs(k)): res += s[::-1] return res class TriangleCount(object): def g(self, i, j): return j - i + 1 def count(self, n): c = 0 for i in range(1, n + 1): for j in range(1, n + 1): g1 = self.g(i, j) g2 = self.g(i, j - i) g1 = g1 if g1 >= 0 else 0 g2 = g2 if g2 >= 0 else 0 c += g1 + g2 return c print TriangleCount().count(4)
fd5cad42fc0df462969bffec225a2da69fcff093
faithstill/info-security-homework
/乘法逆元.py
1,056
3.796875
4
# -*- coding: UTF-8 -*- #欧几里得算法求最大公约数 def get_gcd(a, b): k = a // b remainder = a % b while remainder != 0: a = b b = remainder k = a // b remainder = a % b return b #改进欧几里得算法求线性方程的x与y def get_(a, b): if b == 0: return 1, 0 else: k = a // b remainder = a % b x1, y1 = get_(b, remainder) x, y = y1, x1 - k * y1 return x, y if __name__ == '__main__': a=raw_input("please input the a:") b=raw_input("please input the b:") a, b = int(a), int(b) #将初始b的绝对值进行保存 if b < 0: m = abs(b) else: m = b flag = get_gcd(a, b) #判断最大公约数是否为1,若不是则没有逆元 if flag == 1: x, y = get_(a, b) x0 = x % m #对于Python '%'就是求模运算,因此不需要'+m' print(x0) #x0就是所求的逆元 else: print("Do not have!")
df3e7bb0eb16319adb5427e7744545a07fc2660e
rpask00/Data-structures
/linkedlist.py
3,320
3.578125
4
from ttictoc import TicToc class LinkedList: class Node: def __init__(self, data=None): self.data = data self.next = None def __init__(self): self.first = self.head = self.Node() def listprint(self): print_value = self.first while print_value is not None: print(print_value.data) print_value = print_value.next def addLast(self, val): if self.isEmpty(): self.first.data = val return nextnode = self.Node(val) self.head.next = nextnode self.head = nextnode def indexOf(self, value): index = 0 curent = self.first while curent.next: if curent.data == value: return index curent = curent.next index += 1 return - 1 def contains(self, value): curent = self.first while curent.next: if curent.data == value: return True curent = curent.next return False def removeFirst(self): second = self.first.next if self.isEmpty(): raise IndexError() self.first.next = None self.first = second def removeLast(self): if self.first == self.head or self.isEmpty(): raise IndexError() self.head = self.gePrevious(self.head) self.head.next = None def gePrevious(self, node): current = self.first while current.next: if current.next == node: return current current = current.next return None def isEmpty(self): if self.first.data is None: return True return False def toArray(self): result = [] current = self.first while current: result.append(current.data) current = current.next return result.copy() def reversing(self): if not self.first.next: return previous = self.first current = self.first.next while current: nxt = current.next current.next = previous previous = current current = nxt self.head = self.first self.head.next = None self.first = previous def getNode(self, index): index -= 1 one = second = self.first # get the k-th nde from the beginning try: while index: second = second.next index -= 1 except: raise IndexError while second.next: second = second.next one = one.next return one.data def getMiddle(self): one = second = self.first while True: if second and second.next and second.next.next: second = second.next.next one = one.next else: if second.next: return one.data, one.next.data return one.data list = LinkedList() for i in range(12): list.addLast(i*10) # t = TicToc() # t.tic() # list.reversing() # t.toc() # print(t.elapsed) print(list.getMiddle()) print('----------------------') list.listprint() # print(list.toArray())
54dd52ca5bb4f2113c3debbc6f631d0a79a7b215
aemerick/cloudy_tools
/smooth.py
6,630
4.0625
4
import numpy as np def simple_smooth(x, y, window = 1, interp = 1, factor = 3.0, interpolation = 'linear', mode = 'spike'): """ Very simple smoothing method meant to best handle data with occasional single spiked points, where the "spike" is defined as being a factor "factor" larger than the points on either side. Linear interpolation is used to smooth out these bad points. For example, if window = 1 and interp = 1, iterates through every point, checking if y[i]/y[i-1] and y[i]/y[i+1] are both greater than factor. If so, interpolates between y[i-1] and y[i+1] to fill this value. If window = 2 and interp = 1, looks at y[i]/y[i-2] and y[i]/y[i+2] instead, with same interpolation. In general: window size sets: y[i]/y[i-window] and y[i]/y[i+window] test values and interp sets the points to interpolate between (y[i+interp] and y[i-interp]. Suggested use is to run once with window = 1 and interp = 1 (default) and a second time with window = 2 and interp = 1 """ if interp > window: raise ValueError("Interpolation size must be less than or equal to window size") smooth_y = 1.0 * y # iterate through y, picking out spikes and smoothing them # define a spike as a point where difference on either side is # an order of magnitude or more if mode == 'spike': for i in np.arange(window, np.size(y) - window): if (( (y[i] / smooth_y[i - window]) > factor) and ((y[i]/y[i+window]) > factor)): smooth_y[i] = (((y[i+interp] - y[i-interp]) / (x[i+interp] - x[i-interp]))) * (x[i] - x[i-interp]) + y[i-interp] else: # loop through again, taking care of dips for i in np.arange(window, np.size(y) - window): if (( (y[i] / smooth_y[i-window]) < factor) and ((y[i]/y[i+window]) < factor)): smooth_y[i] = (((y[i+interp] - y[i-interp]) / (x[i+interp] - x[i-interp])))*(x[i] - x[i-interp]) + y[i-interp] return smooth_y def savitzky_golay(y, window_size, order, deriv=0, rate=1): r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter. The Savitzky-Golay filter removes high frequency noise from data. It has the advantage of preserving the original shape and features of the signal better than other types of filtering approaches, such as moving averages techniques. Parameters ---------- y : array_like, shape (N,) the values of the time history of the signal. window_size : int the length of the window. Must be an odd integer number. order : int the order of the polynomial used in the filtering. Must be less then `window_size` - 1. deriv: int the order of the derivative to compute (default = 0 means only smoothing) Returns ------- ys : ndarray, shape (N) the smoothed signal (or it's n-th derivative). Notes ----- The Savitzky-Golay is a type of low-pass filter, particularly suited for smoothing noisy data. The main idea behind this approach is to make for each point a least-square fit with a polynomial of high order over a odd-sized window centered at the point. Examples -------- t = np.linspace(-4, 4, 500) y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape) ysg = savitzky_golay(y, window_size=31, order=4) import matplotlib.pyplot as plt plt.plot(t, y, label='Noisy signal') plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal') plt.plot(t, ysg, 'r', label='Filtered signal') plt.legend() plt.show() References ---------- .. [1] A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of Data by Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8), pp 1627-1639. .. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery Cambridge University Press ISBN-13: 9780521880688 """ import numpy as np from math import factorial try: window_size = np.abs(np.int(window_size)) order = np.abs(np.int(order)) except ValueError, msg: raise ValueError("window_size and order have to be of type int") if window_size % 2 != 1 or window_size < 1: raise TypeError("window_size size must be a positive odd number") if window_size < order + 2: raise TypeError("window_size is too small for the polynomials order") order_range = range(order+1) half_window = (window_size -1) // 2 # precompute coefficients b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)]) m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv) # pad the signal at the extremes with # values taken from the signal itself firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] ) lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1]) y = np.concatenate((firstvals, y, lastvals)) return np.convolve( m[::-1], y, mode='valid') def run_on_all_data(data_dir, data_name, output_dir, iterations = 1): runs = np.arange(1, 726) for i in runs: data = np.genfromtxt(data_dir + '/' + data_name + '_run%i.dat'%(i), names = True) old_heating = data['Heating'] * 1.0 for n in np.arange(iterations): # data['Cooling'] = 10.0**(savitzky_golay(np.log10(data['Cooling']*1000.0), 37, 4)) / 1000.0 data['Heating'] = 10.0**(savitzky_golay(np.log10(data['Heating']*1000.0), 37, 4)) / 1000.0 data['Cooling'] = simple_smooth(data['Te'], data['Cooling']*1000.0 ) / 1000.0 data['Cooling'] = simple_smooth(data['Te'], data['Cooling']*1000.0, window = 2, interp = 2 ) / 1000.0 data['Cooling'] = simple_smooth(data['Te'], data['Cooling']*1000.0, factor = 5.0, window = 3, interp = 3 ) / 1000.0 data['Cooling'] = simple_smooth(data['Te'], data['Cooling']*1000.0, window = 1, interp = 1 ) / 1000.0 # now deal with dips data['Cooling'] = simple_smooth(data['Te'], data['Cooling']*1000.0, window = 1, interp = 1, mode = 'dip') / 1000.0 np.savetxt(output_dir + '/' + data_name + '_run%i.dat'%(i), data, fmt='%.6E', header = "Te Heating Cooling MMW") print 'run %i'%(i) return # # n = 7 or 11 works for number of iterations # # 31 works for window size # 4 works for poly # if __name__ == '__main__': n = 11 run_on_all_data('filled_in_subtracted_final', 'hm_2011_shield_metal_only', 'smoothing', iterations = n )
1aa890533215be3324fdc63bf9731c2db72804d7
arjunnaik/Python-Programs
/Simple_Interest.py
287
3.90625
4
principleAmount = float(input("Enter principle amount")) rateOfInterest = float(input("Enter rate of interest")) timePeriod = float(input("Enter time period")) si = principleAmount*rateOfInterest*timePeriod/100 print("Interest is",si) print("Total Amount is",si+principleAmount)
942c81b06694be9eb9ad7c003454c596ddcffe71
arjunnaik/Python-Programs
/Number_Plate_validation.py
473
3.8125
4
var = input("Enter Number Plate :") if len(var)==6: var1=var[3:] var2 = var[:3] if var1.isdigit() and var2.isupper(): print("License plate is older...") else: print("Invalid License plate...") elif len(var)==7: var1=var[:4] var2=var[4:] if var1.isdigit() and var2.isupper(): print("License plate is Newer...") else: print("Invalid License plate...") else: print("Invalid License plate...")
819ba8350496d22dcf6afbb0baf7a8fcb29ce216
Krunal91/Python_Machine_Learning_Implementation
/LeetCode/removeDuplicates.py
380
3.75
4
def removeDuplicates(nums): """ :type nums: List[int] :rtype: int """ counter = 0 change = nums[0] for i in range(1, len(nums)): if change != nums[i]: counter += 1 nums[counter] = nums[i] change = nums[i] nums = nums[:counter] return counter print(removeDuplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]))
7506f49a24259272ed77b040d1730128fb009ed2
Avithegitty81/Python_Challenge
/**PyPoll**/Main.py
1,299
3.59375
4
# Import modules for reading csv files: import os import csv csv_path= os.path.join("Resources","election_data.csv"); with open(csvpath) as csv_file: csv_reader = csv_reader(csv.file, delimiter = '.') csv_header= next(csv_reader) # Define the Variables: total_votes = 0 candidate = [] candidate_vote_counts = {} vote_percent_per_candidate = 0 # Election data analysis: for data in csv_reader: if data[2] in candidate_vote_counts.keys(): candidate_vote_counts[data[2]] = candidate_vote_counts[data[2]] + 1 else: candidate_vote_counts[data[2]] + 1 # Total vote count: total_votes += 1 print(candidate_vote_counts) # Print Election Result Summary: print("--------------------------------") print(f"Election Results") print("--------------------------------") print(f"TotalVotes:", total_votes) print("--------------------------------") print(f"Winner: ") print("--------------------------------") #Publish summary through text file: file_to_output = os.path.join("analysis", "PyPoll_analysis.txt") with open(file_to_output, "w") as txt_file: txt_file.write(output) Save print files as output = (print ..... print .... print ... )"/n"
b6f885976b3571a573bd9c55658932217d921873
WangJinxinNEU/python3_learn
/generater.py
1,204
3.578125
4
g = (x * x for x in range(10)) # print(next(g)) # print(next(g)) # print(next(g)) # print(next(g)) # print(next(g)) # print(next(g)) # print(next(g)) # print(next(g)) # print(next(g)) # print(next(g)) # a = 5 # b = 1 # a, b = b, a + b # # b = a + b # # def fabi(input): # first=1 # second=1 # index =2 # result=2 # print(first) # print(second) # while index < input: # # result=first+second # print(result) # first=second # second=result # index = index +1 # # print(fabi(6)) n=[1] n=n+[0] # for i in range(len(n)): # print(i) n=n[-1]+n[0] print(n) # 杨辉三角定义如下: # # 1 # / \ # 1 1 # / \ / \ # 1 2 1 # / \ / \ / \ # 1 3 3 1 # / \ / \ / \ / \ # 1 4 6 4 1 # / \ / \ / \ / \ / \ # 1 5 10 10 5 1 # 把每一行看做一个list,试写一个generator,不断输出下一行的list: def triangles(): N = [1] while True: yield N N = N + [0] N = [N[i-1] + N[i] for i in range(len(N))] def triangles1(): L = [1] while True: yield L L = [sum(i) for i in zip([0]+L, L+[0])]
ffb14633bfae95c03e5445919be6c0a8fa251f05
JUANPABLO99YYDUS/Pr-ctica-Complementaria
/18460609-PracticaComplementaria-1/Genarador_figuras2D.py
10,796
3.75
4
import math def main(): op = "" figuras = [] while op !="0" : print("1.-Crear figura \n2.-Listar una clasificacion de figuras\n3.-Listar todas las figuras\n4.-Mostrar suma de todas las areas\n5.-Mostrar suma de todos los perimetros\n6.-Limpiar lista\n0.-Salir") op = input("Ingresar una opcion ") #Opción 1 if (op == "1"): def menu_figuras(): fig= "" print("1.-Cuadrado\n2.-Triangulo\n3.-Circulo") fig = input("Ingresa una opcion de figura ") diccionario = "" if (fig == "1"): l = int(input("Ingresa el lado del cuadrado ")) def crear_cuadrado(l): def area_cuadrado(l): a = l * l return a a = area_cuadrado(l) def perimetro_cuadrado(l): p= l * 4 return p p = perimetro_cuadrado(l) dic ={"Tipo":"Cuadrado","Area":a,"Perimetro":p} return dic diccionario = crear_cuadrado(l) if ( fig == "2"): lado_a = int(input("Ingresa el primer lado ")) lado_b = int(input("Ingresa el segundo lado ")) lado_c = int(input("Ingresa el tercer lado ")) def crear_triangulo(lado_a,lado_b,lado_c): tip= "" a = 0 p = 0 if(lado_a == lado_b and lado_b == lado_c): tip = "Triangulo Equilatero" def area_trianguloEquilatero(lado_a): altura = (math.sqrt(3) * lado_a) / 2 a = (altura * lado_a)/2 return a a= area_trianguloEquilatero(lado_a) def perimetro_trianguloEquilatero(lado_a): p = lado_a * 3 return p p= perimetro_trianguloEquilatero if((lado_a != lado_b and lado_a == lado_c) or (lado_a != lado_c and lado_a == lado_b) or (lado_a != lado_b and lado_b == lado_c)): tip = "Triangulo Isosceles" def area_trianguloIsosceles(lado_a, lado_b, lado_c): a=0 if (lado_a != lado_b and lado_a == lado_c): altura = math.sqrt(lado_a * lado_a - (lado_b * lado_b / 4)) a = (lado_b * altura)/2 elif (lado_a != lado_c and lado_a == lado_b): altura = math.sqrt(lado_a * lado_a - (lado_c * lado_c / 4)) a = (lado_c * altura)/2 elif(lado_a != lado_b and lado_b == lado_c): altura = math.sqrt(lado_b * lado_b - (lado_a * lado_a / 4)) a = (lado_a * altura)/2 return a a= area_trianguloIsosceles(lado_a,lado_b,lado_c) def perimetro_trianguloIsosceles(lado_a,lado_b,lado_c): p = lado_a + lado_b + lado_c return p p= perimetro_trianguloIsosceles(lado_a,lado_b,lado_c) if(lado_a != lado_b and lado_a != lado_c and lado_b != lado_c): tip = "Triangulo Escaleno" def area_trianguloEscaleno(lado_a,lado_b,lado_c): sp = (lado_a + lado_b + lado_c) /2 a = math.sqrt(sp * (sp - lado_a) * (sp - lado_b) * (sp - lado_c)) return a a = area_trianguloEscaleno(lado_a,lado_b,lado_c) def perimetro_trianguloEscaleno(lado_a,lado_b,lado_c): p = lado_a + lado_b + lado_c return p p = perimetro_trianguloEscaleno(lado_a,lado_b,lado_c) dic ={"Tipo":tip,"Area":a,"Perimetro":p} return dic diccionario = crear_triangulo(lado_a,lado_b,lado_c) if(fig == "3"): r = int(input("Ingresa el radio del circulo ")) def crear_circulo(r): def area_circulo(r): a = math.pi * r * r return a a = area_circulo(r) def perimetro_circulo(r): p = 2 * math.pi * r return p p = perimetro_circulo(r) dic = {"Tipo":"Circulo","Area":a,"Perimetro":p} return dic diccionario= crear_circulo(r) return diccionario agregar = menu_figuras() figuras.append(agregar) # Opción 2 if (op == "2"): print("1.Cuadrado\n2.Circulo\n3.Triangulo\n4.Salir") x = int(input("Ingresa una opcion: ")) def listar_clasificacion(clasificar): count= 0 if(x ==1): for i in figuras: if i.get('Tipo') == "Cuadrado": count = count + 1 print(i) if (count ==0): print("La clasificación del Cuadrado está vacía") elif(x==2): for i in figuras: if i.get('Tipo') == "Circulo": count = count + 1 print(i) if (count == 0): print("La clasificación del Circulo está vacía") elif(x==3): print("1.Equilatero\n2.Isoceles\n3.Escaleno") y = int(input("Elige un tipo de triangulo: ")) if(y==1): for i in figuras: if i.get('Tipo') == "Triangulo Equilatero": count = count + 1 print(i) if (count == 0): print("La clasificación de Triangulo Equilatero está vacía") elif(y==2): for i in figuras: if i.get('Tipo') == "Triangulo Isosceles": count = count + 1 print(i) if (count == 0): print("La clasificación de Triangulo Isosceles está vacía") elif(y==3): for i in figuras: if i.get('Tipo') == "Triangulo Escaleno": count = count + 1 print(i) if (count == 0): print("La clasificación de Triangulo Escaleno está vacía") else: print("NO EXISTE ESE TRIANGULO") else: print("NO TE MANEJO MAS OPCIONES") listar_clasificacion(x) #Opción 3 if (op == "3"): for i in figuras: print(i) if (op == "4"): def sumador_areas(): a1=0 a2=0 a3=0 a4=0 a5=0 for i in figuras: if i.get('Tipo') == "Cuadrado": a1 = a1 + int(i.get('Area')) if i.get('Tipo') == "Circulo": a2 = a2 + int(i.get('Area')) if i.get('Tipo') == "Triangulo Equilatero": a3 = a3 + int(i.get('Area')) if i.get('Tipo') == "Triangulo Isosceles": a4 = a4 + int(i.get('Area')) if i.get('Tipo') == "Triangulo Escaleno": a5 = a5 + int(i.get('Area')) print(f"La suma de todas las areas de los Cuadrados es: {a1}") print(f"La suma de todas las areas de los Triangulos Equilateros es: {a2}") print(f"La suma de todas las areas de los Triangulos Isosceles es: {a3}") print(f"La suma de todas las areas de los Triangulos Escalenos es: {a4}") print(f"La suma de todas las areas de los circulos es: {a5}") sumador_areas() if (op == "5"): def sumador_perimetros(): p1 = 0 p2 = 0 p3 = 0 p4 = 0 p5 = 0 for i in figuras: if i.get('Tipo') == "Cuadrado": p1 = p1 + int(i.get('Perimetro')) if i.get('Tipo') == "Circulo": p2 = p2 + int(i.get('Perimetro')) if i.get('Tipo') == "Triangulo Equilatero": p3 = p4 + int(i.get('Perimetro')) if i.get('Tipo') == "Triangulo Isosceles": p4 = p4 + int(i.get('Perimetro')) if i.get('Tipo') == "Triangulo Escaleno": p5 = p5 + int(i.get('Perimetro')) print(f"La suma de todos los perimetros de los Cuadrados es: {p1}") print(f"La suma de todos los perimetros de los Triangulos Equilateros es: {p2}") print(f"La suma de todos los perimetros de los Triangulos Isosceles es: {p3}") print(f"La suma de todos los perimetros de los Triangulos Escalenos es: {p4}") print(f"La suma de todos los perimetros de los circulos es: {p5}") sumador_perimetros() if (op == "6"): figuras.clear() print("SE BORRÓ TODA LA LISTA") if (op == "0"): break main()
bc227425b3e569c14434c0a21e72b413adf4d09b
balajikulkarni/hackerrank
/TicTacToe.py
2,922
3.859375
4
not_full = 0 def DisplayBoard(board): print(" "+board[0]+" "+board[1]+" "+board[2]) print(" "+board[3]+" "+board[4]+" "+board[5]) print(" "+board[6]+" "+board[7]+" "+board[8]) def GetInput(): try: data = input('Enter "X" or "O" and Index> ') marker,index = data.split() return (marker,index) except: print('Invalid Input.') return def Insert_IntoBoard(board,marker,index): global not_full index = int(index) #Basic Sanity if board[index-1] != '-': print('Oops..! '+str(index)+' already taken ') return if index > 9 or index <= 0: print('Invalid Index') return #Go to Insert if marker == 'x' or marker == 'o': board[index-1] = marker not_full = not_full+1 DisplayBoard(board) else: print('Invalid Marker') return def CheckWinner(board,marker): return ((board[0] == marker and board[1] == marker and board[2] == marker) or (board[3] == marker and board[4] == marker and board[5] == marker) or (board[6] == marker and board[7] == marker and board[8] == marker) or (board[0] == marker and board[3] == marker and board[6] == marker) or (board[1] == marker and board[4] == marker and board[7] == marker) or (board[2] == marker and board[5] == marker and board[8] == marker) or (board[0] == marker and board[4] == marker and board[8] == marker) or (board[2] == marker and board[4] == marker and board[6] == marker)) def StartAgain(): print('Do you want to Play again?[yes/no] ') return input().lower().startswith('y') if __name__ == '__main__': while True: board = ['-']*10 DisplayBoard(board) prev ='' cur ='' game_on = True while(game_on and not_full<9 ): marker,index = GetInput() marker = marker.lower() cur = marker #Check one chance per player if prev!=cur: Insert_IntoBoard(board,marker,index) prev = cur else: if cur == 'x': print('Its Player "O" Turn !') else: print('Its Player "X" Turn !') #Check who's the winner if marker == 'x': if (CheckWinner(board,marker)): game_on = False print('Player X has won the game !') break else: if (CheckWinner(board,marker)): game_on = False print('Player O has won the game !') break print('Press "Y" to start again.') if not StartAgain(): print('See you soon!') break
b272382f80edeabc91c1a33ba847e34ebff32ac0
Holly-E/Matplotlib_Practice
/Dealing_with_files.py
1,051
4.125
4
# -*- coding: utf-8 -*- """ Spyder Editor Master Data Visualization with Python Course """ #open pre-existing file or create and open new file to write to # you can only write strings to txt files- must cast #'s to str( ) file = open('MyFile.txt', 'w') file.write('Hello') file.close() # can reuse file variable name after you close it. 'a' appends to file, vs 'w' which overwrites file file = open('MyFile.txt', 'a') file.write(' World') # \n makes a new line file.write('\n') file.write(str(123)) file.close() # open in reading mode file = open('MyFile.txt', 'r') # line = first line, if you call twice it will read the second line if there was one line = file.readline().split() print(line) line = file.readline() print(int(line) + 2) # .strip() to remove string .split() to make lists file.close() #The WITH method allows you to perfomr the same actions but without needing to close the file #The file is automatically closed outside the indentation with open('MyFile.txt', 'r') as file: line = file.readline() print(line)
2c69df3ebb4b2cbf13fc537db25e805c7c772250
nibbletobits/nibbletobits
/python/day 2 project 3.py
299
3.734375
4
import math MAX_SIZE=200 pi=float(3.141592) m1=int(input("type input value for m1=")) m2=int(input("type input value for m2=")) p=float(input("type input for value p=")) a=float(input("type input for value a=")) G=(4*pi**pi*a**a**a//p**p*m1+m2) print(float(G)) input("press enter to end")
0d68a4392b0bd73d031c737fd7f385f999be29c6
nibbletobits/nibbletobits
/python/camel game_rand.int in use.py
4,561
4.25
4
# ******************************************** # Program Name: Day 16, in class # Programmer: Jordan P. Nolin # CSC-119: Summer 2021 # Date: 7 26, 2021 # Purpose: program / camel Game - # Modules used: # Input Variables: # Output: print statements for purpose. # ******************************************** import random def main(): print("Welcome to Camel!\n" "You have stolen a camel to make your way across the great Mobi desert.\n" "The natives want their camel back and are chasing you down! Survive your\n" "desert trek and outrun the natives.") done = False # variables for miles traveled, thirst, camel tiredness. miles_traveled = 0 thirst = 0 camel_tiredness = 0 distance_natives_traveled = -20 drinks = 5 distance_between = 0 warning = 15 moves_made = 0 # natives_distance_behind = distance_natives_traveled - random native travel # here is the main program loop while done == False: moves_made += 1 print("A. Drink from your canteen.\n" "B. Ahead moderate speed.\n" "C. Ahead full speed.\n" "D. Stop for the night.\n" "E. Status check.\n" "Q. Quit.") if distance_between <= 0: distance_between = miles_traveled - (distance_natives_traveled*-1) elif distance_between > 0: distance_between = miles_traveled - distance_natives_traveled user_choice = input("please choose one of the above.: ") if user_choice.upper() == "Q": print("The program has ended!") done = True continue elif user_choice.upper() == "E": print("Miles traveled ", miles_traveled, "\nDrinks in canteen: ", drinks, "\nThe natives are", distance_natives_traveled - miles_traveled, "behind you.") elif user_choice.upper() == "D": print("You have chosen to stop for rest.") camel_tiredness = 0 print("the camel is now rested") distance_natives_traveled += random.randint(7, 14) # 13 elif user_choice.upper() == "C": print("Full speed ahead!") miles_moved = random.randint(10, 20) miles_traveled += miles_moved print("you moved:", miles_moved, "miles!") thirst += 1 camel_tiredness += 2 distance_natives_traveled += random.randint(7, 14) # 14 elif user_choice.upper() == "B": print("you moved at half speed") miles_traveled += random.randint(5, 12) print("you have traveled:", miles_traveled, "miles!") thirst += 1 camel_tiredness += 1 distance_natives_traveled += random.randint(7, 14) # 15 elif user_choice.upper() == "A": if drinks > 0: drinks = drinks - 1 thirst = 0 print("you have drank from your canteen, you have:", drinks, "left in the canteen") continue else: print("you do not have any drinks left") continue # 16 while thirst < 6 and thirst >= 4: if user_choice.upper() != "A": print("you are thirsty" + " your thirst levels are, ", thirst) break continue # 17 if thirst >= 6: done = True print("YOU DIED of thirst") continue # 18 if camel_tiredness >= 5 and camel_tiredness < 8: print("Your camel is getting tired") # 19 elif camel_tiredness >= 8: print("your camel has died of exhaustion") done = True continue # 20 if distance_natives_traveled >= miles_traveled: print("'GAME OVER', the natives have caught you") done = True continue # 21 elif distance_between <= warning and moves_made > 3: print("The natives are getting close hurry up!") # 22 if miles_traveled >= 200: print("!A WINNER IS YOU!") # 23 oasis = random.randint(1, 20) if oasis == 15: print("You have found an oasis ") drinks = 5 thirst = 0 camel_tiredness = 0 print("your assets have been reset") main()
b50646362428794271da3b7ee395c16167377d82
nibbletobits/nibbletobits
/python/day 11 in class main.py
534
3.6875
4
# ******************************************** # Program Name: Day 11, in class # Programmer: Jordan P. Nolin # CSC-119: Summer 2021 # Date: 7 12, 2021 # Purpose: A program that sends a word and calls a function. # Modules used: def vert_word # Input Variables: (word) # Output: print statement calls function vert_word # ******************************************** from day_11_in_class_fn import vert_word def main(): word = str(input("pleas enter a word: ")) vert_word(word) main() input("press enter to end")
39818a02bdab25b77dbfbc76cba087baecbd55d8
nibbletobits/nibbletobits
/python/day 6 in class.py
624
4.21875
4
# ******************************************** # Program Name: Day 5, in class # Programmer: Jordan P. Nolin # CSC-119: Summer 2021 # Date: June 21, 2021 # Purpose: A program to add the sum of all square roots # Modules used: # Input Variables: number() ect # Output: print statements, that output variable answer # ******************************************** def main(): myNumber = 1 stopNumber = 50 total = 0 while myNumber <= stopNumber: x = myNumber**2 total = total + x myNumber = myNumber + 1 print("the total is", total) main() input("press enter to end")
06f3cd7124324a142f42d9f3603d8db6688b3538
nibbletobits/nibbletobits
/python/day_14_1.py
1,095
3.796875
4
# ******************************************** # Program Name: Day 14, HW 1 # Programmer: Jordan P. Nolin # CSC-119: Summer 2021 # Date: 7 24, 2021 # Purpose: program that opens a file and reads than sends it to output location # Modules used: # Input Variables: none # Output: # ******************************************** def main(): while True: try: file_1 = input("What file would you like to open: ") file_2 = input("what would you like to name the output file? ") read_fi = open(file_1, "r") write_fi = open(file_2, "w") in_out(read_fi, write_fi) break except: print("pleas enter a valid read file, include .txt extention") # in_out creates files that are named in main def in_out(one, two): line_num = 0 for line in one.readlines(): line_num += 1 info = "/* " + str(line_num)+ "*/ " + line two.write(info) print(info) one.close() two.close() main() input("press enter to end")
81db4111784384152f29a88e5f21d0ac706f95a7
nibbletobits/nibbletobits
/python/day 11 home work.py
1,378
4.0625
4
# ******************************************** # Program Name: Day 11, homework # Programmer: Jordan P. Nolin # CSC-119: Summer 2021 # Date: June 30, 2021 # Purpose: A program that asks the user for two inputs [r, h] than calls the list of functions. # Modules used: spherevolume(r,h), spheresurface(r,h), cylindervolume(r,h), cylinderserface(r,h), conevolume(r,h), conesurface(r,h) # Input Variables: inputs for variables[r, h] # Output: print statements, that output function answers for main body # ******************************************** def main(): from day_11_hw_fn import spheresurvolume, spheresurface, cylindervolume,\ cylindersurface, conevolume, conesurface try: r = float(input("pleas enter the radius: ")) h = float(input("pleas enter the height: ")) print("the volume of the sphear is: %.2f" % spheresurvolume(r)) print("the surface area of the sphear is: %.2f" % spheresurface(r)) print("the volume of the cylinder is: %.2f" % cylindervolume(r, h)) print("the surface area of the cylinder is: %.2f" % cylindersurface(r, h)) print("the vloume of the cone is: %.2f" % conevolume(r, h)) print("the surface area of the cone is: %.2f" % conesurface(r, h)) except: print("'Error', please enter a Number!") main() input("press enter to end the program")
d17890d3692bfbe9c4cc25c1f6a240db48e3c774
arpartch/yogaProject
/drills.py
7,725
3.90625
4
import { map } from "ramda"; from functools import reduce; ######Map Function##### # Capitalize words def capitalize(name): return name.capitalize() x = map(capitalize, names) print(list(x)) #Max out at 350 def max_out_350(size): return size if size <= 350 else 350 sizes = [200, 400, 350, 75, 1200] x = map(max_out_350, sizes) print(list(x)) # percentage of 50? def percentage(num): return num/50 percentages = [34, 33, 1, 0, 99, 123] x = map(percentage, percentages) print(list(x)) #Max from each pair def max_num(pair): return max(pair) heartrates = [[80, 99], [120, 75], [115, 115]] x = map(max_num, heartrates) print(list(x)) ## Have several things that you want to change into something else? Reduce it fullNames = [["stradinger", "peter"], ["partch", "athena"]]; // -> ["Peter Stradinger", "Athena Partch"] scores = [34, 33, 1, 0, 99, 123]; #48.33 print (functools.reduce(lambda a,b : a+b,lis)) ## with full names (from above) -> [{firstName: "peter", lastName: "stradinger"},{firstName: "athena", lastName: "partch"}, ] # Want to test if one or more things are true? Write a predicate (or set of predicates) R.map(startsWith("a"), names); # -> [false, true, true, bob] R.map(isGreaterThan300, sizes); # -> [false, true, true, false, true] R.map(isEven, percentages); # -> [true, false, false, false?, false, false] I'm not sure if 0 is even x = map(lambda a: a.startswith('a'), names) print(list(x)) x = map(lambda a: a > 300, sizes) print(list(x)) x = map(lambda a: a % 2 == 0, percentages) print(list(x)) # Do something only if a predicate passes? Use a when # -> [true, true, false, false] animals = [{ type: "dog" }, { type: "cat" }, { type: "snake" }, { type: "shark" }] x = map(lambda ani: ani[type] == 'dog' or ani[type] == 'cat', animals) print(list(x)) # ->if the balance dips below 0 balance = [10, 0, -3, 4, 50] #["ok", "ok", "overdrawn", "ok", "ok"] x = map(lambda y: 'ok' if y>0 else 'overdrawn', balance) print(list(x)) #If a predicate passes, do something, if not something else? Use an ifThen heights = [[4, 10], [5, 10], [5, 3], [6, 2]] # ["reject", "ride", "reject", "ride"] height limit 5'5 x = map(lambda y: 'ride' if y[0]*12 + y[1] >= 5.5*12 else 'reject', heights) print(list(x)) configs = [{ type: "text" }, { type: "date" }, { type: "datetime" }, { type: "text" }]; #-> ["Text", "Default", "Default", "Text"] use default unless text x = x = map(lambda conf: 'Text' if conf[type] == 'text' else 'Default', configs) print(list(x)) #Have branching cases where you're looking for the first predicate that passes? Do a cond betterConfigs = [ { type: "text" }, { type: "date" }, { type: "datetime" }, { type: "text" }, { type: "textarea" }, ]; # -> ["Text", "Date", "Date", "Text", "TextArea"] use default unless text def predicate(x): if x[type] == 'text': return 'Text' elif x[type] == 'date' or x[type] == 'datetime': return 'Date' elif x[type] == 'textarea': return 'TextArea' x = map(predicate, betterConfigs) print(list(x)) #Want only part of a list that passes a predicate? use Filter (or reject) const evenBetterConfigs = [ { name: "Field A", type: "text", isEnabled: true }, { name: "Field B", type: "date", isEnabled: false }, { name: "Field C", type: "datetime", isEnabled: false }, { name: "Field D", type: "text", isEnabled: true }, { name: "Field E", type: "textarea", isEnabled: true }, ]; # all enabled # all disabled # all enabled text fields # all where the type starts with date #Need to do a bunch of behaviors where you pass the result of one into another? Make a pipe # for even better configs # convertTypeToComponent, filterEnabled, sortByName, removeType # Need to see what's happening at a step in the pipe? Use tap # R.pipe(step1, R.tap(console.log), step2)(context) -> Tap will allow you to log out the result without interrupting the pipe # Too much complexity? Refactor to a function (or several) context = { cards: [ { id: 1, pose: "downward facing dog" }, { id: 2, pose: "upward facing dog" }, { id: 3, pose: "shivasana" }, { id: 4, pose: "cat" }, { id: 5, pose: "cow" }, { id: 6, pose: "new pose" }, ], default: "default", }; # this is an ugly spaghetti function. function formatCards(context) { configs = R.prop("configs", context); cards = R.map(config => { id = R.prop("id", config); card = { id }; pose = R.prop("pose", config); # format Label -> This should be refactored labelWords = R.split(" ", pose); capitalizedWords = R.map(word => { firstLetter = R.head(word); rest = R.tail(word); capFirstLetter = R.toUpper(firstLetter); capitalizedWord = R.concat(capFirstLetter, rest); return capitalizedWord; }, labelWords); label = R.join(" ", capitalizedWords); # format image src -> this should also be refactored srcWords = R.split(" ", pose); capitalizedSrcTailWords = R.map(word => { firstLetter = R.head(word); rest = R.tail(word); capFirstLetter = R.toUpper(firstLetter); capitalizedWord = R.concat(capFirstLetter, rest); return capitalizedWord; }, R.tail(labelWords)); srcHead = R.head(srcWords); srcWordsFormatted = R.prepend(srcHead, capitalizedSrcTailWords); srcName = R.join("", srcWordsFormatted); src = R.concat(srcName, ".jpg"); cardWithLabel = R.assoc("label", label, card); cardWithSrc = R.assoc("src", src, cardWithLabel); fullCard = cardWithSrc; return fullCard; }, configs); return cards; } const cards = [ { id: 1, label: "Downward Facing Dog", src: "downwardFacingDog.jpg" }, { id: 2, label: "Upward Facing Dog", src: "upwardFacingDog.jpg" }, { id: 3, label: "Shivasana", src: "shivasana.jpg" }, { id: 4, label: "Cat", src: "cat.jpg" }, { id: 5, label: "Cow", src: "cow.jpg" }, { id: 6, label: "New Pose", src: "default.jpg" }, ]; # this is the first step of refactoring. Separating things out into functions # see how this same function is used twice? function capitalizeWords(words) { firstLetter = R.head(word); rest = R.tail(word); capFirstLetter = R.toUpper(firstLetter); capitalizedWord = R.concat(capFirstLetter, rest); return capitalizedWord; } # now see if you can also refactor format label and format image src into their own functions function formatCards(context) { configs = R.prop("configs", context); cards = R.map(config => { id = R.prop("id", config); card = { id }; pose = R.prop("pose", config); # format Label -> This should be refactored labelWords = R.split(" ", pose); capitalizedWords = R.map(capitalizeWords, labelWords); label = R.join(" ", capitalizedWords); def format_label(x): splitted = x.split(' ') splitted = map(lambda y: y.capitalize(), splitted) return ' '.join(list(splitted)) # format image src -> this should also be refactored srcWords = R.split(" ", pose); capitalizedSrcTailWords = R.map(capitalizeWords, R.tail(labelWords)); srcHead = R.head(srcWords); srcWordsFormatted = R.prepend(srcHead, capitalizedSrcTailWords); srcName = R.join("", srcWordsFormatted); src = R.concat(srcName, ".jpg"); cardWithLabel = R.assoc("label", label, card); cardWithSrc = R.assoc("src", src, cardWithLabel); fullCard = cardWithSrc; return fullCard; }, configs); return cards; def format_img_src(x): splitted = x.split(' ') splitted = map(lambda y: y.capitalize(), splitted) return ' '.join(list(splitted)) def formater(x): x['label'] = format_label(x['label']) x['src'] = format_img_src(x['src']) return x x = map(formater, cards) print(list(x))
b5996faa9054b9df8af5c050b2f49610826577dc
liyi0206/leetcode-python
/110 balanced binary tree.py
2,063
3.75
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ return self.dfs(root) != -1 # given -1, it is good for early return, if already -1 def dfs(self, root): if root == None: return 0 h1 = self.dfs(root.left) if h1 ==-1: return -1 h2= self.dfs(root.right) if h2 ==-1 or abs(h1-h2)>1: return -1 return max(h1,h2) + 1 #logging version #def dfs(self, root): # print "another dfs with",root.val if root is not None else None # if root == None: return 0 # h1 = self.dfs(root.left) # print "done with left of",root.val,"h1=",h1 # if h1<0: # print "return -1" # return -1 # h2= self.dfs(root.right) # print "done with right of",root.val,"h2=",h2 # if h2 < 0 or abs(h1-h2) > 1: # print "done with compare, return -1" # return -1 # print "done with compare, return",max(h1, h2)+1,"\n" # return max(h1, h2) + 1 # a clear solution that set flag and height apart - but no early return! #def isBalanced(self, root): # self.flag=True # print self.dfs(root) # return self.flag # #def dfs(self, root): # if root == None: return 0 # h1,h2 = 0,0 # if root.left: h1=self.dfs(root.left) # print "done with left of",root.val # if root.right:h2=self.dfs(root.right) # print "done with right of",root.val # if abs(h1-h2)>1: # print h1,h2,"flag false" # self.flag=False # return max(h1,h2)+1 root=TreeNode(1) root.left=TreeNode(21) root.right=TreeNode(22) root.left.left=TreeNode(31) root.left.right=TreeNode(32) root.right.left=TreeNode(33) root.left.left.left=TreeNode(41) a=Solution() print a.isBalanced(root)
8935772ff86c73b7a42e8e2d002bdf755ef28529
liyi0206/leetcode-python
/116 populating next right pointers in each node.py
1,589
3.84375
4
# Definition for binary tree with next pointer. class TreeLinkNode(object): def __init__(self, x): self.val = x self.left = None self.right = None self.next = None # perfect binary tree (ie, all leaves are at the same level, # and every parent has two children). class Solution(object): def connect(self, root): """ :type root: TreeLinkNode :rtype: nothing """ if root is None: return cur= [root] while cur: nxt=[] while cur: node = cur.pop(0) if cur: node.next = cur[0] if node.left: nxt.append(node.left) if node.right:nxt.append(node.right) cur=nxt # You may only use constant extra space. class Solution2(object): def connect(self, root): cur = root while cur: pre = cur ### while cur: if cur.left: cur.left.next = cur.right if cur.right and cur.next: cur.right.next = cur.next.left cur = cur.next # at last, right most is none (not exist) cur = pre.left ### root=TreeLinkNode(1) root.left=TreeLinkNode(2) root.right=TreeLinkNode(3) root.left.left=TreeLinkNode(4) root.left.right=TreeLinkNode(5) root.right.left=TreeLinkNode(6) root.right.right=TreeLinkNode(7) a=Solution() a.connect(root) print root.left.next.val #3 print root.left.left.next.val #5 print root.left.right.next.val#6 print root.right.left.next.val#7
9168d9fffbbec024bb3a9859f67582f5221e2f31
liyi0206/leetcode-python
/348 design tic-tac-toe.py
3,497
3.875
4
class TicTacToe(object): def __init__(self, n): """ Initialize your data structure here. :type n: int """ self.n=n self.board=[[None]*n for i in range(n)] self.rows,self.cols=[0]*n,[0]*n self.diag,self.anti=0,0 def move(self, row, col, player): """ Player {player} makes a move at ({row}, {col}). @param row The row of the board. @param col The column of the board. @param player The player, can be either 1 or 2. @return The current winning condition, can be either: 0: No one wins. 1: Player 1 wins. 2: Player 2 wins. :type row: int :type col: int :type player: int :rtype: int """ self.board[row][col]=player #for l in self.board: print l #print self.rows,self.cols,self.diag,self.anti if self.check_winner(row,col,player): return player else: return 0 # rows and cols are initiated as 0, once added 1 or 2 at [i,j], make rows[i], # cols[j] to be 1 or 2, and once a conflict, make rows[i], cols[j] to be 8 and return. # to know the row/col is full, still need self.board[i]==[num]*self.n. def check_winner(self,x,y,num): if self.rows[x]==0: self.rows[x]=num elif self.rows[x]==num: if [self.board[x][i] for i in range(self.n)]==[num]*self.n: return True elif self.rows[x]==3-num: self.rows[x]=8 if self.cols[y]==0: self.cols[y]=num elif self.cols[y]==num: if [self.board[i][y] for i in range(self.n)]==[num]*self.n: return True elif self.cols[y]==3-num: self.cols[y]=8 if x==y: if self.diag==0: self.diag=num elif self.diag==3-num: self.diag=8 elif self.diag==num: if [self.board[i][i] for i in range(self.n)]==[num]*self.n: return True if x==self.n-1-y: if self.anti==0: self.anti=num elif self.anti==3-num: self.anti=8 elif self.anti==num: if [self.board[i][self.n-1-i] for i in range(self.n)]==[num]*self.n: return True return False class TicTacToe2(object): #better solution, same time complexity, o(n) space def __init__(self,n):#solution1 need o(n^2) space. also check and add use same time. self.n=n self.rows,self.cols=[0]*n,[0]*n self.diag,self.anti=0,0 def move(self,x,y, player): num=1 if player==1 else -1 self.rows[x]+=num self.cols[y]+=num if x==y: self.diag+=num if x==self.n-1-y: self.anti+=num for i in range(self.n): if abs(self.rows[i])==self.n or abs(self.cols[i])==self.n or \ abs(self.diag)==self.n or abs(self.anti)==self.n: return player return 0 a=TicTacToe2(3) print a.move(0,0,1) print a.move(0,2,2) print a.move(2,2,1) print a.move(1,1,2) print a.move(2,0,1) print a.move(1,0,2) print a.move(2,1,1) #return 1 a=TicTacToe2(2) print a.move(0,1,1) print a.move(1,1,2) print a.move(1,0,1) #return 1 #def check_winner(self,num): # for i in range(self.n): # if self.board[i]==[num]*self.n: return True # for j in range(self.n): # if [self.board[i][j] for i in range(self.n)]==[num]*self.n: return True # if [self.board[i][i] for i in range(self.n)]==[num]*self.n: return True # return False
e7565cac69265885bd7eeeb8384955302b273adf
liyi0206/leetcode-python
/156 binary tree upside down.py
1,136
4.0625
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def upsideDownBinaryTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if not root or not root.left or not root.right: return root newRoot=self.upsideDownBinaryTree(root.left) root.left.left=root.right root.left.right=root root.left=None root.right=None return newRoot def upsideDownBinaryTree2(self,root): cur=root pre=None nxt=None tmp=None while cur: nxt=cur.left cur.left=tmp cur.right=pre pre=cur cur=nxt return pre root=TreeNode(1) root.left=TreeNode(2) root.right=TreeNode(3) root.left.left=TreeNode(4) root.left.right=TreeNode(5) a=Solution() new=a.upsideDownBinaryTree2(root) print new.val print new.left.val print new.right.val print new.right.left.val print new.right.right.val
7ff50d199e169ce80b69489ef47ce3e4081ec1b5
liyi0206/leetcode-python
/23 merge k sorted lists.py
1,084
3.828125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ import heapq dummy = ListNode(0) current = dummy heap = [] for sorted_list in lists: if sorted_list: heapq.heappush(heap, (sorted_list.val, sorted_list)) while heap: smallest = heapq.heappop(heap)[1] current.next = smallest current = current.next if smallest.next: heapq.heappush(heap, (smallest.next.val, smallest.next)) return dummy.next l1=ListNode(1) l1.next=ListNode(3) l1.next.next=ListNode(5) l1.next.next.next=ListNode(7) l2=ListNode(2) l2.next=ListNode(8) l2.next.next=ListNode(9) l3=ListNode(4) l3.next=ListNode(6) l3.next.next=ListNode(10) a=Solution() l=a.mergeKLists([l1,l2,l3]) cur = l while cur: print cur.val, cur=cur.next
a27fb4c09334810b39a3d09690e4afc980ae3c9e
liyi0206/leetcode-python
/236 lowest common ancestor of a binary tree.py
1,958
3.765625
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): #def lowestCommonAncestor(self, root, p, q): # """ # :type root: TreeNode # :type p: TreeNode # :type q: TreeNode # :rtype: TreeNode # """ # self.p,self.q = p,q # self.pathp,self.pathq=[],[] # self.dfs(root,[]) # #print [a.val for a in self.pathp],[b.val for b in self.pathq] # lp,lq=len(self.pathp),len(self.pathq) # for i in range(min(lp,lq)): # if self.pathp[i]!=self.pathq[i]: # return self.pathp[i-1] # return self.pathp[i] # #def dfs(self,node,path): # if node is None: return # if node==self.p: # self.pathp = path+[node] # elif node==self.q: # self.pathq = path+[node] # self.dfs(node.left, path+[node]) # self.dfs(node.right,path+[node]) def lowestCommonAncestor(self, root, p, q): #print "another dfs",root.val if root else None if not root or root==p or root==q: return root left =self.lowestCommonAncestor(root.left, p,q) #print "left", left.val if left else None right=self.lowestCommonAncestor(root.right,p,q) #print "right",right.val if right else None,"\n" if not left: return right elif not right: return left else: return root node0,node1,node2 = TreeNode(0),TreeNode(1),TreeNode(2) node3,node4,node5 = TreeNode(3),TreeNode(4),TreeNode(5) node6,node7,node8 = TreeNode(6),TreeNode(7),TreeNode(8) root=node3 root.left=node5 root.left.left =node6 root.left.right=node2 root.left.right.left =node7 root.left.right.right=node4 root.right=node1 root.right.left =node0 root.right.right=node8 a=Solution() res=a.lowestCommonAncestor(root,node7,node4) print res.val
d05eae952e0adb41ce31d22266f431b031498231
liyi0206/leetcode-python
/237 delete node in a linked list.py
732
3.84375
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.next = node.next.next node1,node2,node3,node4 = ListNode(1),ListNode(2),ListNode(3),ListNode(4) nodes = [node1,node2,node3,node4] for i in range(len(nodes)-1): nodes[i].next = nodes[i+1] cur = node1 while cur: print cur.val, cur=cur.next print a=Solution() a.deleteNode(node3) cur = node1 while cur: print cur.val, cur=cur.next
3431a14f55b66f3f0c4f9a2010534957f510bd2f
liyi0206/leetcode-python
/225 implement stack using queues.py
821
4.15625
4
class Stack(object): def __init__(self): """ initialize your data structure here. """ self.queue=[] def push(self, x): """ :type x: int :rtype: nothing """ self.queue.append(x) def pop(self): """ :rtype: nothing """ for i in range(len(self.queue)-1): tmp = self.queue.pop(0) self.queue.append(tmp) return self.queue.pop(0) def top(self): """ :rtype: int """ for i in range(len(self.queue)): top = self.queue.pop(0) self.queue.append(top) return top def empty(self): """ :rtype: bool """ return len(self.queue)==0 a=Stack() a.push(1) a.push(2) print a.top()
9fb84cef730806c5dbdba33cd359e9a13aeaec50
liyi0206/leetcode-python
/290 word pattern.py
968
3.71875
4
class Solution(object): def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ map1,map2 = dict(),dict() for i in range(len(pattern)): if pattern[i] not in map1: map1[pattern[i]]=[i] else: map1[pattern[i]].append(i) string = str.split() for i in range(len(string)): if string[i] not in map2: map2[string[i]]=[i] else: map2[string[i]].append(i) set1,set2 = set(),set() for k,v in map1.iteritems(): set1.add(tuple(v)) for k,v in map2.iteritems(): set2.add(tuple(v)) return set1==set2 a = Solution() print a.wordPattern(pattern = "abba", str = "dog cat cat dog") print a.wordPattern(pattern = "abba", str = "dog cat cat fish") print a.wordPattern(pattern = "aaaa", str = "dog cat cat dog") print a.wordPattern(pattern = "abba", str = "dog dog dog dog")
306f7459acc5adb3d1901a57c0b064eb1d99ce95
liyi0206/leetcode-python
/173 binary search tree iterator.py
960
3.984375
4
# Definition for a binary tree node class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class BSTIterator(object): def __init__(self, root): """ :type root: TreeNode """ self.stack=[] self.cur=root def hasNext(self): """ :rtype: bool """ return self.stack or self.cur def next(self): """ :rtype: int """ while self.cur or self.stack: if self.cur: self.stack.append(self.cur) self.cur=self.cur.left else: parent = self.stack.pop() self.cur = parent.right return parent.val root=TreeNode(2) root.left=TreeNode(1) root.right=TreeNode(4) root.right.left=TreeNode(3) root.right.right=TreeNode(5) i,v = BSTIterator(root),[] while i.hasNext(): v.append(i.next()) print v
e1836e6b0a4f5697bf0b4e6e9ee5ffa093612ed5
liyi0206/leetcode-python
/266 palindrome permutation.py
494
3.578125
4
class Solution(object): def canPermutePalindrome(self, s): """ :type s: str :rtype: bool """ mp={} for c in s: if c not in mp: mp[c]=1 else: mp[c]+=1 odd=0 for k in mp: if mp[k]%2==1: odd+=1 if odd==2: return False return True a=Solution() print a.canPermutePalindrome("code") #F print a.canPermutePalindrome("aab") #T print a.canPermutePalindrome("carerac") #T
0a8fa08729ef1018279ff48292fa916da4c47a07
liyi0206/leetcode-python
/43 multiply strings.py
765
3.53125
4
class Solution(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ return str(int(num1)*int(num2)) def multiply2(self,num1,num2): num1, num2 = num1[::-1], num2[::-1] tmp = [0 for i in range(len(num1) + len(num2))] for i in range(len(num1)): for j in range(len(num2)): tmp[i+j] += int(num1[i]) * int(num2[j]) carry, res = 0, [] for digit in tmp: sum = carry+digit carry = sum/10 res.insert(0, str(sum%10)) while len(res)>1 and res[0]=="0": del res[0] return ''.join(res) a=Solution() print a.multiply("36","16") #"576"
663a59c450aa1d732aa19da8b05d13260ad2b2ae
liyi0206/leetcode-python
/145 binary tree postorder traversal.py
3,220
4.15625
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): #def postorderTraversal(self, root): # """ # :type root: TreeNode # :rtype: List[int] # """ # self.res=[] # self.postorder(root) # return self.res #def postorder(self,root): # if root is None: # return # self.postorder(root.left) # self.postorder(root.right) # self.res.append(root.val) #iteration from wikipedia - logging version #def postorderTraversal(self, root): # res, stack, node = [], [], root # lastNodeVisited = None # while stack or node: # print "*** another round ***" # if node is not None: # stack.append(node) # print "stack append ",node.val # print "node.left ",node.left.val if node.left is not None else None # node=node.left # print "node ",node.val if node is not None else None # else: # peeknode=stack[-1] # print "peeknode ",peeknode.val # print "peeknode.right ",peeknode.right.val if peeknode.right is not None else None,", ", # print "lastNodeVisited ",lastNodeVisited.val if lastNodeVisited is not None else None # if peeknode.right is not None and lastNodeVisited is not peeknode.right: # node=peeknode.right # print "node ",node.val if node is not None else None # else: # res.append(peeknode.val) # print "stack pop ",stack[-1].val # lastNodeVisited = stack.pop() # print "node not change ",node.val if node is not None else None,", ", # print "lastNodeVisited ",lastNodeVisited.val if lastNodeVisited is not None else None # return res #iteration from wikipedia #def postorderTraversal(self, root): # res, stack, node = [], [], root # lastNodeVisited = None # while stack or node: # if node: # stack.append(node) # node=node.left # else: # peeknode=stack[-1] # if peeknode.right and lastNodeVisited != peeknode.right: # node=peeknode.right # else: # res.append(peeknode.val) # lastNodeVisited = stack.pop() # return res #iteration from leetcode-py def postorderTraversal(self, root): res, stack, current, prev = [], [], root, None while stack or current: if current: stack.append(current) current = current.left else: parent = stack[-1] if parent.right in (None, prev): prev = stack.pop() res.append(prev.val) else: current = parent.right return res root=TreeNode(1) root.right=TreeNode(2) root.right.left=TreeNode(3) a=Solution() print a.postorderTraversal(root)
8d22226a37715e00a378c2ec6496ded100d8ce04
liyi0206/leetcode-python
/152 maximum product subarray.py
562
3.515625
4
class Solution(object): def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ res = nums[0] minp,maxp = nums[0],nums[0] for a in nums[1:]: tmp_maxp = maxp tmp_minp = minp maxp = max(tmp_maxp*a, tmp_minp*a, a) minp = min(tmp_maxp*a, tmp_minp*a, a) res = max(res, maxp) return res a=Solution() #print a.maxProduct([2,3,-2,4]) #6 from [2,3] print a.maxProduct([2,3,-2,4,5]) print a.maxProduct([-2,0,-1])
0275fb0a9d6b1725b95058ce03026d3d44b2d69b
liyi0206/leetcode-python
/341 flatten nested list iterator.py
4,239
4.1875
4
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class NestedIterator(object): # input is list, using index def __init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ self.stack = [[nestedList, 0]] def hasNext(self): """ :rtype: bool """ while self.stack: nestedList,i = self.stack[-1] if i==len(nestedList): self.stack.pop() else: x =nestedList[i] if x.isInteger(): return True self.stack[-1][1]+=1 #for next round self.stack.append([x.getList(), 0]) return False def next(self): """ :rtype: int """ if self.hasNext(): nestedList,i = self.stack[-1] self.stack[-1][1]+=1 return nestedList[i].getInteger() # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] # while i.hasNext(): v.append(i.next()) class DeepIterator2(): # input is list of numbers, keep stack of array and index def __init__(self,nestedList): self.stack = [[nestedList,0]] # only reference, o(1) space def hasnext(self): while self.stack: nestedList,i = self.stack[-1] if i==len(nestedList): self.stack.pop() if self.stack: self.stack[-1][1]+=1 else: return False else: x=nestedList[i] if type(x)==int: return True else: self.stack.append([x,0]) def next(self): if not self.hasnext(): return None nestedList,i = self.stack[-1] self.stack[-1][1]+=1 # prep for next, only actual change return nestedList[i] #nums=[1,2,[3,4,5,[],[6,7,[8,9],10]],[[]],11,12] #di=DeepIterator2(nums) #for i in range(12): print di.next() ### input is iterator class IteratorWrapper(object): def __init__(self, it): self.it = iter(it) self._hasnext = None self._thenext = None def __iter__(self): return self def next(self): if self._hasnext: res = self._thenext else: res= next(self.it) self._hasnext = None return res def hasnext(self): if self._hasnext is None: try: self._thenext = next(self.it) except StopIteration: self._hasnext = False else: self._hasnext = True return self._hasnext class DeepIterator3(): # input is list of numbers, keep stack of array and index def __init__(self,nestedList): # the problem with it is there is a hasnext self.stack = [nestedList] # True at last element def hasNext(self): if self.stack: return True else: return False def next(self): while self.stack: cur=self.stack[-1] if cur.hasnext(): x=cur.next() if type(x)==int: return x else: self.stack.append(x) else: self.stack.pop() nestedList = IteratorWrapper([1,2,IteratorWrapper([3,4,5,IteratorWrapper([]), IteratorWrapper([6,7,IteratorWrapper([8,9]),10])]), IteratorWrapper([IteratorWrapper([])]),11,12]) i = DeepIterator3(nestedList) while i.hasNext(): print i.next()
a11a9fddd142caea65dd5da517f221553bc1ee65
liyi0206/leetcode-python
/278 first bad version.py
675
3.5625
4
# The isBadVersion API is already defined for you. # @param version, an integer # @return a bool #def isBadVersion(version): class Solution(object): def firstBadVersion(self, n): """ :type n: int :rtype: int """ if n==1: return 1 if isBadVersion(n) else 0 l,h=1,n while l<h: m=l+(h-l)/2 if isBadVersion(m): h=m else: l=m+1 return l def isBadVersion(version): if version>3: return True else: return False a=Solution() print a.firstBadVersion(10) #4 #def isBadVersion(version): # return True #a=Solution() #print a.firstBadVersion(1) #1
4e1697c09cfd81f80816c8be6e9fab65a2df8518
liyi0206/leetcode-python
/88 merge sorted array.py
783
3.859375
4
class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ p1,p2,p = m-1,n-1,m+n-1 while p1>=0 and p2>=0: if nums1[p1]>=nums2[p2]: nums1[p]=nums1[p1] p,p1=p-1,p1-1 else: nums1[p]=nums2[p2] p,p2=p-1,p2-1 if p2>=0: nums1[0:p2+1]=nums2[0:p2+1] a=Solution() nums1,nums2=[1,3,5,0,0],[2,4] a.merge(nums1,3,nums2,2) print nums1 nums1,nums2=[2,4,0,0,0],[1,3,5] a.merge(nums1,2,nums2,3) print nums1 nums1,nums2=[0],[1] a.merge(nums1,0,nums2,1) print nums1
06e8e14c3a3913bcf99df55c07893b761664be4a
liyi0206/leetcode-python
/17 letter combination of a phone number.py
615
3.546875
4
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ self.lookup=["", "", "abc", "def", "ghi", "jkl", \ "mno", "pqrs", "tuv", "wxyz"] #self.nums self.res=[] self.bt(digits,"") #word, or n return self.res def bt(self,digits,tmp): #void if digits == "": self.res.append(tmp) return for letter in self.lookup[int(digits[0])]: self.bt(digits[1:],tmp+letter) a=Solution() print a.letterCombinations("23")
4dbf4aeffc23b7825388ddc6a20959a9e0efa2d6
liyi0206/leetcode-python
/19 remove nth node from end of list.py
949
3.8125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ if head == None: return None dummy = ListNode(0) dummy.next = head p,l = dummy,0 while p.next: p,l = p.next,l+1 start = dummy for i in range(l-n): start = start.next start.next = start.next.next return dummy.next head=ListNode(1) head.next=ListNode(2) head.next.next=ListNode(3) head.next.next.next=ListNode(4) head.next.next.next.next=ListNode(5) cur = head while cur: print cur.val, cur=cur.next print a=Solution() new=a.removeNthFromEnd(head,2) cur = new while cur: #for i in range(10): print cur.val, cur=cur.next
5fcb4db7af96c641d93766e1c69a3dd94311def8
liyi0206/leetcode-python
/139 word break.py
625
3.5
4
class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: Set[str] :rtype: bool """ dp = [True]+[False]*len(s) s = '0'+s for i in range(len(s)): if dp[i]: for word in wordDict: if i+len(word)<=len(s) and word==s[i+1:i+1+len(word)]: if i+len(word)==len(s)-1: return True else: dp[i+len(word)]=True #print dp return dp[-1] a=Solution() print a.wordBreak("catsanddog",["cat", "cats", "and", "sand", "dog"])
ad0a004abeef6d79466a709e7f40f8de7b7e77ec
jophy-mj/python
/sample/p20.py
221
4.03125
4
n=int(input("enter no:")) rev=0 temp=n while(temp>0): r=temp%10 rev=(rev*10)+r temp=temp//10 print("reverse of",n,"is",rev) if(n==rev): print(n,"is palindrome") else: print(n,"is not palindrome")
eccad250bb9bdce796b545e9918cbfcebffd1537
jophy-mj/python
/c2/p15.py
129
3.53125
4
color_list1=["red","green","yellow"] color_list2=["blue","green","purple","red"] for i in color_list1: print(color_list1[i])
390cd9ce71f14b42e64831014f4a84d88b9e8207
jophy-mj/python
/c2/p11.py
226
4.03125
4
a=int(input("Enter 1st no:")) b=int(input("Enter 2st no:")) c=int(input("Enter 3st no:")) if((a>b)and(a>c)): print("Largest no is ",a) elif((b>a)and(b>c)): print("Largest no is ",b) else: print("Largest no is ",c)
2a3fcb8dbe6c8ffcd2df87373fb451840522e479
jophy-mj/python
/c4/p3.py
552
4.0625
4
class rectangle: def __init__(self,length,breadth): self.length=length self.breadth=breadth def area(self): return self.length*self.breadth def __lt__(self): if rect1<rect2: print("second rectangle is greater than first!") else: print("first rectangle is greater than second") obj1=rectangle(2,4) obj2=rectangle(3,4) print("Area of rectangle1:",obj1.area()) print("Area of rectangle1:",obj2.area()) rect1=obj1.area() rect2=obj2.area() rect=rectangle(rect1,rect2) rect.__lt__()
8de62638b39f63bc6186688a3562b6967494ff03
jophy-mj/python
/c3/p11.py
226
3.875
4
import math sq_area=lambda a:a*a rec_area=lambda l,b:l*b tri_area=lambda b,h:.5*b*h print("Area of square(5) is:",sq_area(5)) print("Area of rectangle(5,4) is:",rec_area(5,4)) print("Area of triangle(5,8) is:",tri_area(5,8))
7aa5b051e9b75e76aca01f1f8a24fc3cd5fccf7d
jophy-mj/python
/c4/p5.py
631
3.875
4
class publisher: def __init__(self): print("parent class") class book(publisher): def __init__(self,title,author): self.title=title self.author=author def display(self): print("The title of the book is",self.title) print("The author of the book is ",self.author) class pyton(book): def __init__(self,price,pages): self.price=price self.pages=pages def display(self): print("price of the book : ",self.price) print("Total pages of the book :",self.pages) c=book("python Learning","Jason.R.Briggs") c.display() c=pyton(600,987) c.display()
3e7a3f93810ab6574011e00a653b9abe7ad4dbe9
tuthimi/learn-python
/RunooShili/4.py
463
3.890625
4
__author__ = 'Administrator' year = int(raw_input("YEAR:\n")) month = int(raw_input("MONTH:\n")) day = int(raw_input("DAY:\n")) months = (0,31,59,90,120,151,181,212,243,273,304,334) if 1<=month<=12: sum = months[month-1] else: print("MONTH input error!\n") if 1<=day<=31: sum += day; else: print("DAY input error!\n") if ((year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)))and month>=2: sum += 1 print ("The day num is %d" %sum)
b7fe6cd8a510170a0da743aebf6e9b65c633dc8a
tuthimi/learn-python
/RunooShili/78.py
277
3.5
4
#!/usr/bin/python # -*- coding: UTF-8 -*- __author__ = 'Administrator' if __name__ == '__main__': person = {"li":18,"wang":50,"zhang":20,"sun":212} mm='li' for m in person: if person[mm] < person[m]: mm = m print '%s,%d' % (mm,person[mm])
c7da97340adedb28ab16e58cc5770f64fef5894c
jordan-stone/Telluric-Fitter
/src/TelluricFitter.py
43,817
3.703125
4
""" Telluric Fitter "TelFit" ===================================================== This module provides the 'TelluricFitter' class, used to fit the telluric lines in data. Usage: - Initialize fitter: fitter = TelluricFitter() - Define variables to fit: must provide a dictionary where the key is the name of the variable, and the value is the initial guess value for that variable. Example: fitter.FitVariable({"ch4": 1.6, "h2o": 45.0}) - Edit values of constant parameters: similar to FitVariable, but the variables given here will not be fit. Useful for settings things like the telescope pointing angle, temperature, and pressure, which will be very well-known. Example: fitter.AdjustValue({"angle": 50.6}) - Set bounds on fitted variables (fitter.SetBounds): Give a dictionary where the key is the name of the variable, and the value is a list of size 2 of the form [lower_bound, upper_bound] - Import data (fitter.ImportData): Copy data as a class variable. Must be given as a DataStructures.xypoint instance - Perform the fit: (fitter.Fit): Returns a DataStructures.xypoint instance of the model. The x-values in the returned array are the same as the data. - Optional: retrieve a new version of the data, which is wavelength-calibrated using the telluric lines and with a potentially better continuum fit using data2 = fitter.data This file is part of the TelFit program. TelFit is free software: you can redistribute it and/or modify it under the terms of the MIT license. TelFit is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. You should have received a copy of the MIT license along with TelFit. If not, see <http://opensource.org/licenses/MIT>. """ import matplotlib.pyplot as plt import numpy import sys import os import subprocess import scipy from scipy.interpolate import UnivariateSpline from scipy.optimize import leastsq, minimize, fminbound from scipy.linalg import svd, diagsvd from scipy import mat import MakeModel import DataStructures import FittingUtilities class TelluricFitter: def __init__(self, debug=False, debug_level=2): #Set up parameters self.parnames = ["pressure", "temperature", "angle", "resolution", "wavestart", "waveend", "h2o", "co2", "o3", "n2o", "co", "ch4", "o2", "no", "so2", "no2", "nh3", "hno3"] self.const_pars = [795.0, 273.0, 45.0, 50000.0, 2200.0, 2400.0, 50.0, 368.5, 3.9e-2, 0.32, 0.14, 1.8, 2.1e5, 1.1e-19, 1e-4, 1e-4, 1e-4, 5.6e-4] self.bounds = [[0.0, 1e30] for par in self.parnames] #Basically just making sure everything is > 0 self.fitting = [False]*len(self.parnames) #Latitude and altitude (to nearest km) of the observatory # Defaults are for McDonald Observatory self.observatory = {"latitude": 30.6, "altitude": 2.0} self.data = None self.resolution_bounds = [10000.0, 100000.0] homedir = os.environ['HOME'] self.resolution_fit_mode="gauss" self.fit_primary = False self.fit_source = False self.adjust_wave = "model" self.first_iteration=True self.continuum_fit_order = 7 self.wavelength_fit_order = 3 self.debug = debug self.debug_level = debug_level #Number from 1-5, with 5 being the most verbose self.Modeler = MakeModel.Modeler(debug=self.debug) self.parvals = [[] for i in range(len(self.parnames))] self.chisq_vals = [] self.ignore = [] self.shift = 0 #The wavelength shift to make the model and data align #Just open and close chisq_summary, to clear anything already there outfile = open("chisq_summary.dat", "w") outfile.close() ### ----------------------------------------------- def DisplayVariables(self, fitonly=False): """ Display the value of each of the parameters, and show whether it is being fit or not -fitonly: bool variable. If true, it only shows the variables being fit. Otherwise, it shows all variables. """ print "%.15s\tValue\t\tFitting?\tBounds" %("Parameter".ljust(15)) print "-------------\t-----\t\t-----\t\t-----" for i in range(len(self.parnames)): if (fitonly and self.fitting[i]) or not fitonly: if len(self.bounds[i]) == 2: print "%.15s\t%.5E\t%s\t\t%g - %g" %(self.parnames[i].ljust(15), self.const_pars[i], self.fitting[i], self.bounds[i][0], self.bounds[i][1]) else: print "%.15s\t%.5g\t\t%s" %(self.parnames[i].ljust(15), self.const_pars[i], self.fitting[i]) ### ----------------------------------------------- def FitVariable(self, vardict): """ Add one or more variables to the list being fit. - vardict: a dictionary where the key is the parameter name and the value is the value of that parameter. """ for par in vardict.keys(): try: idx = self.parnames.index(par) self.const_pars[idx] = vardict[par] self.fitting[idx] = True except ValueError: print "Error! Bad parameter name given. Currently available are: " self.DisplayVariables() raise ValueError ### ----------------------------------------------- def AdjustValue(self, vardict): """ Similar to FitVariable, but this just adjusts the value of a constant parameter. Warning! If the variable will be removed from the fitting list, so DO NOT use this to adjust the value of a parameter you want fitted. """ for par in vardict.keys(): try: idx = self.parnames.index(par) self.const_pars[idx] = vardict[par] self.fitting[idx] = False except ValueError: print "Error! Bad parameter name given. Currently available are: " self.DisplayVariables() raise ValueError ### ----------------------------------------------- def GetValue(self, variable): """ Returns the value of the variable given. Useful to get the fitted value of the parameters """ if variable in self.parnames: idx = self.parnames.index(variable) return self.const_pars[idx] else: print "Error! Bad parameter name given (%s)." %(variable) print "Currently available parameter names are: " self.DisplayVariables() ### ----------------------------------------------- def SetBounds(self, bounddict): """ Similar to FitVariable, but it sets bounds on the variable. This can technically be done for any variable, but is only useful to set bounds for those variables being fit (and detector resolution) """ for par in bounddict.keys(): try: idx = self.parnames.index(par) self.bounds[idx] = bounddict[par] if par == "resolution": self.resolution_bounds = bounddict[par] except ValueError: print "Error! Bad parameter name given. Currently available are: " self.DisplayVariables() raise ValueError ### ----------------------------------------------- def SetObservatory(self, observatory): """ Set the observatory. Can either give a dictionary with the latitude and altitude, or give the name of the observatory. Some names are hard-coded in here. """ if type(observatory) == str: if observatory.lower() == "ctio": self.observatory["latitude"] = -30.6 self.observatory["altitude"] = 2.2 if observatory.lower() == "la silla": self.observatory["latitude"] = -29.3 self.observatory["altitude"] = 2.4 if observatory.lower() == "paranal": self.observatory["latitude"] = -24.6 self.observatory["altitude"] = 2.6 if observatory.lower() == "mauna kea": self.observatory["latitude"] = 19.8 self.observatory["altitude"] = 4.2 if observatory.lower() == "mcdonald": self.observatory["latitude"] = 30.7 self.observatory["altitude"] = 2.1 elif type(observatory) == dict: if "latitude" in observatory.keys() and "altitude" in observatory.keys(): self.observatory = observatory else: print "Error! Wrong keys in observatory dictionary! Keys must be" print "'latitude' and 'altitude'. Yours are: ", observatory.keys() raise KeyError else: raise ValueError("Error! Unrecognized input to TelluricFitter.SetObservatory()") ### ----------------------------------------------- def ImportData(self, data): """ Function for the user to give the data. The data should be in the form of a DataStructures.xypoint structure. """ if not isinstance(data, DataStructures.xypoint): raise TypeError( "ImportData Error! Given data is not a DataStructures.xypoint structure!" ) self.data = data.copy() return ### ----------------------------------------------- def EditAtmosphereProfile(self, profilename, profile_height, profile_value): """ Edits the atmosphere profile for a given parameter. This is just a wrapper for the MakeModel.Modeler method, but the docstring is replicated below: -profilename: A string with the name of the profile to edit. Should be either 'pressure', 'temperature', or one of the molecules given in the MakeModel.MoleculeNumbers dictionary -profile_height: A numpy array with the height in the atmosphere (in km) -profile_value: A numpy array with the value of the profile parameter at each height given in profile_height. """ self.Modeler.EditProfile(profilename, profile_height, profile_value) ### ----------------------------------------------- def IgnoreRegions(self, region): """ Tells the fitter to ignore certain regions of the spectrum in the chi-squared calculation. Useful for stellar or interstellar lines. -region: Can be either a list of size 2 with the beginning and ending wavelength range to ignore, or a list of lists giving several wavelength ranges at once. """ if not isinstance(region, list) or len(region) == 0: raise TypeError("Must give a non-empty list to TelluricFitter.IgnoreRegions") if isinstance(region[0], list): #The user gave a list of lists. Append each one to self.ignore for r in region: self.ignore.append(r) elif isinstance(region[0], int): #The user gave a single region. Append to self.ignore self.ignore.append(region) else: raise TypeError("Unrecognized variable type for region given in TelluricFitter.IgnoreRegions") return ### ----------------------------------------------- ### Main Fit Function! ### ----------------------------------------------- def Fit(self, data=None, resolution_fit_mode="gauss", fit_primary=False, fit_source=False, return_resolution=False, adjust_wave="model", continuum_fit_order=7, wavelength_fit_order=3): """ The main fitting function. Before calling this, the user MUST 1: call FitVariable at least once, specifying which variables will be fit 2: Set resolution bounds (any other bounds are optional) -data: If given, this should be a DataStructures.xypoint instance giving the data you wish to fit. In previous versions, this had to be given separately in the 'ImportData' method. -resolution_fit_mode: controls which function is used to estimate the resolution. "SVD" is for singlular value decomposition, while "gauss" is for convolving with a gaussian (and fitting the width of the guassian to give the best fit) -fit_source: determines whether an iterative smoothing is applied to the data to approximate the source spectrum. Only works if the source spectrum has broad lines. If true, this function returns both the best-fit model and the source estimate. -return_resolution: controls whether the best-fit resolution is returned to the user. One case I have used this for is to fit echelle data of late-type stars by getting all the best-fit parameters from redder orders, and then applying those atmospheric parameters to the rest of the orders. -adjust_wave: can be set to either 'data' or 'model'. To wavelength calibrate the data to the telluric lines, set to 'data'. If you think the wavelength calibration is good on the data (such as Th-Ar lines in the optical), then set to 'model' Note that currently, the vacuum --> air conversion for the telluric model is done in a very approximate sense, so adjusting the data wavelengths may introduce a small (few km/s) offset from what it should be. -continuum_fit_order: The polynomial order with which to fit the continuum. It uses a sigma-clipping algorithm so that the continuum is not strongly affected by stellar lines (either absorption or emission) -wavelength_fit_order: The polynomial order with which to adjust the wavelength fit. Note that the 'adjust_wave' input will determine whether the data or the telluric model is wavelength-adjusted. """ self.resolution_fit_mode=resolution_fit_mode self.fit_source = fit_primary self.fit_source = fit_source self.adjust_wave = adjust_wave self.continuum_fit_order = continuum_fit_order self.wavelength_fit_order = wavelength_fit_order self.return_resolution=return_resolution #Check if the user gave data to fit if data != None: self.ImportData(data) elif self.data == None: raise AttributeError ("\n\nError! Must supply data to fit\n\n!") #Make sure resolution bounds are given (resolution is always fit) idx = self.parnames.index("resolution") if len(self.bounds[idx]) < 2 and self.resolution_fit_mode != "SVD": print "Must give resolution bounds!" inp = raw_input("Enter the lowest and highest possible resolution, separated by a space: ") self.resolution_bounds = [float(inp.split()[0]), float(inp.split()[1])] #Make fitpars array fitpars = [self.const_pars[i] for i in range(len(self.parnames)) if self.fitting[i] ] if len(fitpars) < 1: print "\n\nError! Must fit at least one variable!\n\n" return #Set up the fitting logfile and logging arrays self.parvals = [[] for i in range(len(self.parnames))] self.chisq_vals = [] outfile = open("chisq_summary.dat", "a") outfile.write("\n\n\n\n") for i in range(len(self.parnames)): if self.fitting[i]: outfile.write("%s\t" %self.parnames[i]) outfile.write("X^2\n") outfile.close() #Perform the fit self.first_iteration = True errfcn = lambda pars: numpy.sum(self.FitErrorFunction(pars)) bounds = [self.bounds[i] for i in range(len(self.parnames)) if self.fitting[i]] optdict = {"rhobeg": [1,5,1000.0]} optdict = {"eps": 5} fitpars, success = leastsq(self.FitErrorFunction, fitpars, diag=1.0/numpy.array(fitpars), epsfcn=0.001) #Save the best-fit values idx = 0 for i in range(len(self.parnames)): if self.fitting[i]: self.const_pars[i] = fitpars[idx] idx += 1 #Finally, return the best-fit model if self.fit_source: return self.GenerateModel(fitpars, separate_primary=True, return_resolution=return_resolution) else: return self.GenerateModel(fitpars, return_resolution=return_resolution) ### ----------------------------------------------- def FitErrorFunction(self, fitpars): """ The error function for the fitter. This should never be called directly! """ if self.return_resolution: model, resolution = self.GenerateModel(fitpars, return_resolution=True) else: model = self.GenerateModel(fitpars) outfile = open("chisq_summary.dat", 'a') weights = 1.0 / self.data.err**2 #Find the regions to use (ignoring the parts that were defined as bad) good = numpy.arange(self.data.x.size, dtype=numpy.int32) for region in self.ignore: x0 = min(region) x1 = max(region) tmp1 = [self.data.x[i] in self.data.x[good] for i in range(self.data.x.size)] tmp2 = numpy.logical_or(self.data.x<x0, self.data.x>x1) good = numpy.where(numpy.logical_and(tmp1, tmp2))[0] return_array = (self.data.y - self.data.cont*model.y)[good]**2 * weights[good] #Evaluate bound conditions and output the parameter value to the logfile. fit_idx = 0 for i in range(len(self.bounds)): if self.fitting[i]: if len(self.bounds[i]) == 2: return_array += FittingUtilities.bound(self.bounds[i], fitpars[fit_idx]) outfile.write("%.12g\t" %fitpars[fit_idx]) self.parvals[i].append(fitpars[fit_idx]) fit_idx += 1 elif len(self.bounds[i]) == 2 and self.parnames[i] != "resolution": return_array += FittingUtilities.bound(self.bounds[i], self.const_pars[i]) outfile.write("%g\n" %(numpy.sum(return_array)/float(weights.size))) self.chisq_vals.append(numpy.sum(return_array)/float(weights.size)) print "X^2 = ", numpy.sum(return_array)/float(weights.size) outfile.close() return return_array ### ----------------------------------------------- def GenerateModel(self, pars, nofit=False, separate_primary=False, return_resolution=False): """ This function does the actual work of generating a model with the given parameters, fitting the continuum, making sure the model and data are well aligned in wavelength, and fitting the detector resolution. In general, it is not meant to be called directly by the user. However, the 'nofit' keyword turns this into a wrapper to MakeModel.Modeler().MakeModel() with all the appropriate parameters. """ data = self.data #Update self.const_pars to include the new values in fitpars # I know, it's confusing that const_pars holds some non-constant parameters... fit_idx = 0 for i in range(len(self.parnames)): if self.fitting[i]: self.const_pars[i] = pars[fit_idx] fit_idx += 1 self.DisplayVariables(fitonly=True) #Extract parameters from pars and const_pars. They will have variable # names set from self.parnames fit_idx = 0 for i in range(len(self.parnames)): #Assign to local variables by the parameter name if self.fitting[i]: exec("%s = %g" %(self.parnames[i], pars[fit_idx])) fit_idx += 1 else: exec("%s = %g" %(self.parnames[i], self.const_pars[i])) #Make sure everything is within its bounds if len(self.bounds[i]) > 0: lower = self.bounds[i][0] upper = self.bounds[i][1] exec("%s = %g if %s < %g else %s" %(self.parnames[i], lower, self.parnames[i], lower, self.parnames[i])) exec("%s = %g if %s > %g else %s" %(self.parnames[i], upper, self.parnames[i], upper, self.parnames[i])) wavenum_start = 1e7/waveend wavenum_end = 1e7/wavestart lat = self.observatory["latitude"] alt = self.observatory["altitude"] #Generate the model: model = self.Modeler.MakeModel(pressure, temperature, wavenum_start, wavenum_end, angle, h2o, co2, o3, n2o, co, ch4, o2, no, so2, no2, nh3, hno3, lat=lat, alt=alt, wavegrid=None, resolution=None) #Shift the x-axis, using the shift from previous iterations if self.debug: print "Shifting by %.4g before fitting model" %self.shift if self.adjust_wave == "data": data.x += self.shift elif self.adjust_wave == "model": model.x -= self.shift #Save each model if debugging if self.debug and self.debug_level >= 5: FittingUtilities.ensure_dir("Models/") model_name = "Models/transmission"+"-%.2f" %pressure + "-%.2f" %temperature + "-%.1f" %h2o + "-%.1f" %angle + "-%.2f" %(co2) + "-%.2f" %(o3*100) + "-%.2f" %ch4 + "-%.2f" %(co*10) numpy.savetxt(model_name, numpy.transpose((model.x, model.y)), fmt="%.8f") #Interpolate to constant wavelength spacing xgrid = numpy.linspace(model.x[0], model.x[-1], model.x.size) model = FittingUtilities.RebinData(model, xgrid) #Use nofit if you want a model with reduced resolution. Probably easier # to go through MakeModel directly though... if data == None or nofit: return FittingUtilities.ReduceResolution(model, resolution) model_original = model.copy() #Reduce to initial guess resolution if (resolution - 10 < self.resolution_bounds[0] or resolution+10 > self.resolution_bounds[1]): resolution = numpy.mean(self.resolution_bounds) model = FittingUtilities.ReduceResolution(model, resolution) model = FittingUtilities.RebinData(model, data.x) #Shift the data (or model) by a constant offset. This gets the wavelength calibration close shift = FittingUtilities.CCImprove(data, model, tol=0.1) if self.adjust_wave == "data": data.x += shift elif self.adjust_wave == "model": model_original.x -= shift # In this case, we need to adjust the resolution again model = FittingUtilities.ReduceResolution(model_original.copy(), resolution) model = FittingUtilities.RebinData(model, data.x) else: sys.exit("Error! adjust_wave parameter set to invalid value: %s" %self.adjust_wave) self.shift += shift resid = data.y/model.y nans = numpy.isnan(resid) resid[nans] = data.cont[nans] #As the model gets better, the continuum will be less affected by # telluric lines, and so will get better data.cont = FittingUtilities.Continuum(data.x, resid, fitorder=self.continuum_fit_order, lowreject=2, highreject=3) if separate_primary or self.fit_source: print "Generating Primary star model" primary_star = data.copy() primary_star.y = FittingUtilities.Iterative_SV(resid/data.cont, 61, 4, lowreject=2, highreject=3) data.cont *= primary_star.y if self.debug and self.debug_level >= 4: print "Saving data and model arrays right before fitting the wavelength" print " and resolution to Debug_Output1.log" numpy.savetxt("Debug_Output1.log", numpy.transpose((data.x, data.y, data.cont, model.x, model.y))) #Fine-tune the wavelength calibration by fitting the location of several telluric lines modelfcn, mean = self.FitWavelength(data, model.copy(), fitorder=self.wavelength_fit_order) if self.adjust_wave == "data": test = data.x - modelfcn(data.x - mean) xdiff = [test[j] - test[j-1] for j in range(1, len(test)-1)] if min(xdiff) > 0 and numpy.max(numpy.abs(test - data.x)) < 0.1 and min(test) > 0: print "Adjusting data wavelengths by at most %.8g nm" %numpy.max(test - model.x) data.x = test.copy() else: print "Warning! Wavelength calibration did not succeed!" elif self.adjust_wave == "model": test = model_original.x + modelfcn(model_original.x - mean) test2 = model.x + modelfcn(model.x - mean) xdiff = [test[j] - test[j-1] for j in range(1, len(test)-1)] if min(xdiff) > 0 and numpy.max(numpy.abs(test2 - model.x)) < 0.1 and min(test) > 0 and abs(test[0] - data.x[0]) < 50 and abs(test[-1] - data.x[-1]) < 50: print "Adjusting wavelength calibration by at most %.8g nm" %max(test2 - model.x) model_original.x = test.copy() model.x = test2.copy() else: print "Warning! Wavelength calibration did not succeed!" else: sys.exit("Error! adjust_wave set to an invalid value: %s" %self.adjust_wave) if self.debug and self.debug_level >= 4: print "Saving data and model arrays after fitting the wavelength" print " and before the resolution fit to Debug_Output2.log" numpy.savetxt("Debug_Output2.log", numpy.transpose((data.x, data.y, data.cont, model.x, model.y))) #Fit instrumental resolution done = False while not done: done = True if "SVD" in self.resolution_fit_mode and min(model.y) < 0.95: model, self.broadstuff = self.Broaden(data.copy(), model_original.copy(), full_output=True) elif "gauss" in self.resolution_fit_mode: model, resolution = self.FitResolution(data.copy(), model_original.copy(), resolution) else: done = False print "Resolution fit mode set to an invalid value: %s" %self.resolution_fit_mode self.resolution_fit_mode = raw_input("Enter a valid mode (SVD or guass): ") self.data = data self.first_iteration = False if separate_primary: if return_resolution: return primary_star, model, resolution else: return primary_star, model else: #if self.fit_source: # data.cont /= primary_star.y if return_resolution: return model, resolution return model ### ----------------------------------------------- ### Several functions for refining the wavelength calibration ### ----------------------------------------------- def WavelengthErrorFunction(self, shift, data, model): """ Error function for the scipy.minimize fitters. Not meant to be called directly by the user! """ modelfcn = UnivariateSpline(model.x, model.y, s=0) weight = 1e9 * numpy.ones(data.x.size) weight[data.y > 0] = 1.0/numpy.sqrt(data.y[data.y > 0]) weight[weight < 0.01] = 0.0 newmodel = modelfcn(model.x + float(shift)) if shift < 0: newmodel[model.x - float(shift) < model.x[0]] = 0 else: newmodel[model.x - float(shift) > model.x[-1]] = 0 returnvec = (data.y - newmodel)**2*weight return returnvec ### ----------------------------------------------- def GaussianFitFunction(self, x,params): """ Generate a gaussian absorption line. Not meant to be called directly by the user! """ cont = params[0] depth = params[1] mu = params[2] sig = params[3] return cont - depth*numpy.exp(-(x-mu)**2/(2*sig**2)) ### ----------------------------------------------- def GaussianErrorFunction(self, params, x, y): """ Error function for the scipy.minimize fitters. Not meant to be called directly by the user! """ return self.GaussianFitFunction(x,params) - y ### ----------------------------------------------- def FitGaussian(self, data): """ This function fits a gaussian to a line. The input should be a small segment (~0.1 nm or so), in an xypoint structure Not meant to be called directly by the user! """ cont = 1.0 sig = 0.004 minidx = numpy.argmin(data.y/data.cont) mu = data.x[minidx] depth = 1.0 - min(data.y/data.cont) pars = [cont, depth, mu, sig] pars, success = leastsq(self.GaussianErrorFunction, pars, args=(data.x, data.y/data.cont), diag=1.0/numpy.array(pars), epsfcn=1e-10) return pars, success ### ----------------------------------------------- def FitWavelength(self, data_original, telluric, tol=0.05, oversampling=4, fitorder=3, numiters=10): """ Function to fine-tune the wavelength solution of a generated model It does so by looking for telluric lines in both the data and the telluric model. For each line, it finds the shift needed to make them line up, and then fits a function to that fit over the full wavelength range of the data. Wavelength calibration MUST already be very close for this algorithm to succeed! NOT MEANT TO BE CALLED DIRECTLY BY THE USER! """ print "Fitting Wavelength" old = [] new = [] #Find lines in the telluric model linelist = FittingUtilities.FindLines(telluric, debug=self.debug, tol=0.995) if len(linelist) < fitorder: fit = lambda x: x mean = 0.0 return fit, mean linelist = telluric.x[linelist] if self.debug and self.debug_level >= 5: logfilename = "FitWavelength.log" print "Outputting data and telluric model to %s" %logfilename numpy.savetxt(logfilename, numpy.transpose((data_original.x, data_original.y, data_original.cont, data_original.err)), fmt="%.8f") infile = open(logfilename, "a") infile.write("\n\n\n\n\n") numpy.savetxt(infile, numpy.transpose((telluric.x, telluric.y)), fmt="%.8f") infile.close() #Interpolate to finer spacing xgrid = numpy.linspace(data_original.x[0], data_original.x[-1], data_original.x.size*oversampling) data = FittingUtilities.RebinData(data_original, xgrid) model = FittingUtilities.RebinData(telluric, xgrid) #Begin loop over the lines numlines = 0 model_lines = [] dx = [] for line in linelist: if line-tol > data.x[0] and line+tol < data.x[-1]: numlines += 1 #Find line center in the model left = numpy.searchsorted(model.x, line - tol) right = numpy.searchsorted(model.x, line + tol) #Don't use lines that are saturated if min(model.y[left:right]) < 0.05: continue pars, model_success = self.FitGaussian(model[left:right]) if model_success < 5 and pars[1] > 0 and pars[1] < 1: model_lines.append(pars[2]) else: continue #Do the same for the data left = numpy.searchsorted(data.x, line - tol) right = numpy.searchsorted(data.x, line + tol) if min(data.y[left:right]/data.cont[left:right]) < 0.05: model_lines.pop() continue pars, data_success = self.FitGaussian(data[left:right]) if data_success < 5 and pars[1] > 0 and pars[1] < 1: dx.append(pars[2] - model_lines[-1]) else: model_lines.pop() #Convert the lists to numpy arrays model_lines = numpy.array(model_lines) dx = numpy.array(dx) #Remove any points with very large shifts: badindices = numpy.where(numpy.abs(dx) > 0.015)[0] model_lines = numpy.delete(model_lines, badindices) dx = numpy.delete(dx, badindices) if self.debug and self.debug_level >= 5: plt.figure(2) plt.plot(model_lines, dx, 'ro') plt.title("Fitted Line shifts") plt.xlabel("Old Wavelength") plt.ylabel("New Wavelength") numlines = len(model_lines) print "Found %i lines in this order" %numlines fit = lambda x: x mean = 0.0 if numlines < fitorder: return fit, mean #Check if there is a large gap between the telluric lines and the end of the order (can cause the fit to go crazy) keepfirst = False keeplast = False if min(model_lines) - data.x[0] > 1: model_lines = numpy.r_[data.x[0], model_lines] dx = numpy.r_[0.0, dx] keepfirst = True if data.x[-1] - max(model_lines) > 1: model_lines = numpy.r_[model_lines, data.x[-1]] dx = numpy.r_[dx, 0.0] keeplast = True #Iteratively fit with sigma-clipping done = False iternum = 0 mean = numpy.mean(data.x) while not done and len(model_lines) >= fitorder and iternum < numiters: iternum += 1 done = True fit = numpy.poly1d(numpy.polyfit(model_lines - mean, dx, fitorder)) residuals = fit(model_lines - mean) - dx std = numpy.std(residuals) badindices = numpy.where(numpy.abs(residuals) > 3*std)[0] if 0 in badindices and keepfirst: idx = numpy.where(badindices == 0)[0] badindices = numpy.delete(badindices, idx) if data.size()-1 in badindices and keeplast: idx = numpy.where(badindices == data.size()-1)[0] badindices = numpy.delete(badindices, idx) if badindices.size > 0 and model_lines.size - badindices.size > 2*fitorder: done = False model_lines = numpy.delete(model_lines, badindices) dx = numpy.delete(dx, badindices) if self.debug and self.debug_level >= 5: plt.figure(3) plt.plot(model_lines, fit(model_lines - mean) - dx, 'ro') plt.title("Residuals") plt.xlabel("Wavelength") plt.ylabel("Delta-lambda") plt.show() return fit, mean ### ----------------------------------------------- def Poly(self, pars, x): """ Generates a polynomial with the given parameters for all of the x-values. x is assumed to be a numpy.ndarray! Not meant to be called directly by the user! """ retval = numpy.zeros(x.size) for i in range(len(pars)): retval += pars[i]*x**i return retval ### ----------------------------------------------- def WavelengthErrorFunctionNew(self, pars, data, model, maxdiff=0.05): """ Cost function for the new wavelength fitter. Not meant to be called directly by the user! """ dx = self.Poly(pars, data.x) penalty = numpy.sum(numpy.abs(dx[numpy.abs(dx) > maxdiff])) return (data.y/data.cont - model(data.x + dx))**2 + penalty ### ----------------------------------------------- def FitWavelengthNew(self, data_original, telluric, fitorder=3): """ This is a vastly simplified version of FitWavelength. It takes the same inputs and returns the same thing, so is a drop-in replacement for the old FitWavelength. Instead of finding the lines, and generating a polynomial to apply to the axis as x --> f(x), it fits a polynomial to the delta-x. So, it fits the function for x --> x + f(x). This way, we can automatically penalize large deviations in the wavelength. """ modelfcn = UnivariateSpline(telluric.x, telluric.y, s=0) pars = numpy.zeros(fitorder + 1) output = leastsq(self.WavelengthErrorFunctionNew, pars, args=(data_original, modelfcn), full_output=True) pars = output[0] return lambda x: x - self.Poly(pars, x), 0 ### ----------------------------------------------- ### Detector Resolution Fitter ### ----------------------------------------------- def FitResolution(self, data, model, resolution=75000.0): """ Fits the instrumental resolution with a Gaussian. This method is called by GenerateModel, and is not meant to be called by the user! """ print "Fitting Resolution" #Subsample the model to speed this part up (it doesn't affect the accuracy much) dx = (data.x[1] - data.x[0])/3.0 xgrid = numpy.arange(model.x[0], model.x[-1]+dx, dx) #xgrid = numpy.linspace(model.x[0], model.x[-1], model.size()/5) newmodel = FittingUtilities.RebinData(model, xgrid) ResolutionFitErrorBrute = lambda resolution, data, model: numpy.sum(self.ResolutionFitError(resolution, data, model)) resolution = fminbound(ResolutionFitErrorBrute, self.resolution_bounds[0], self.resolution_bounds[1], xtol=1, args=(data,newmodel)) print "Optimal resolution found at R = ", float(resolution) newmodel = FittingUtilities.ReduceResolution(newmodel, float(resolution)) return FittingUtilities.RebinData(newmodel, data.x), float(resolution) ### ----------------------------------------------- def ResolutionFitError(self, resolution, data, model): """ This function gets called by scipy.optimize.fminbound in FitResolution. Not meant to be called directly by the user! """ resolution = max(1000.0, float(int(float(resolution) + 0.5))) if self.debug and self.debug_level >= 5: print "Saving inputs for R = ", resolution print " to Debug_ResFit.log and Debug_ResFit2.log" numpy.savetxt("Debug_ResFit.log", numpy.transpose((data.x, data.y, data.cont))) numpy.savetxt("Debug_Resfit2.log", numpy.transpose((model.x, model.y))) newmodel = FittingUtilities.ReduceResolution(model, resolution, extend=False) newmodel = FittingUtilities.RebinData(newmodel, data.x, synphot=False) #Find the regions to use (ignoring the parts that were defined as bad) good = numpy.arange(self.data.x.size, dtype=numpy.int32) for region in self.ignore: x0 = min(region) x1 = max(region) tmp1 = [self.data.x[i] in self.data.x[good] for i in range(self.data.x.size)] tmp2 = numpy.logical_or(self.data.x<x0, self.data.x>x1) good = numpy.where(numpy.logical_and(tmp1, tmp2))[0] weights = 1.0/data.err**2 returnvec = (data.y - data.cont*newmodel.y)[good]**2 * weights[good] + FittingUtilities.bound(self.resolution_bounds, resolution) if self.debug: print "Resolution-fitting X^2 = ", numpy.sum(returnvec)/float(good.size), "at R = ", resolution if numpy.isnan(numpy.sum(returnvec**2)): print "Error! NaN found in ResolutionFitError!" outfile=open("ResolutionFitError.log", "a") outfile.write("#Error attempting R = %g\n" %(resolution)) numpy.savetxt(outfile, numpy.transpose((data.x, data.y, data.cont, newmodel.x, newmodel.y)), fmt="%.10g") outfile.write("\n\n\n\n") numpy.savetxt(outfile, numpy.transpose((model.x, model.y)), fmt="%.10g") outfile.write("\n\n\n\n") outfile.close() raise ValueError return returnvec ### ----------------------------------------------- def Broaden(self, data, model, oversampling = 5, m = 101, dimension = 20, full_output=False): """ Fits the broadening profile using singular value decomposition. This function is called by GenerateModel, and is not meant to be called directly! -oversampling is the oversampling factor to use before doing the SVD -m is the size of the broadening function, in oversampled units -dimension is the number of eigenvalues to keep in the broadening function. (Keeping too many starts fitting noise) -NOTE: This function works well when there are strong telluric lines and a flat continuum. If there are weak telluric lines, it's hard to not fit noise. If the continuum is not very flat (i.e. from the spectrum of the actual object you are trying to telluric correct), the broadening function can become multiply-peaked and oscillatory. Use with care! """ n = data.x.size*oversampling #n must be even, and m must be odd! if n%2 != 0: n += 1 if m%2 == 0: m += 1 #resample data Spectrum = UnivariateSpline(data.x, data.y/data.cont, s=0) Model = UnivariateSpline(model.x, model.y, s=0) xnew = numpy.linspace(data.x[0], data.x[-1], n) ynew = Spectrum(xnew) model_new = FittingUtilities.RebinData(model, xnew).y #Make 'design matrix' design = numpy.zeros((n-m,m)) for j in range(m): for i in range(m/2,n-m/2-1): design[i-m/2,j] = model_new[i-j+m/2] design = mat(design) #Do Singular Value Decomposition try: U,W,V_t = svd(design, full_matrices=False) except numpy.linalg.linalg.LinAlgError: outfilename = "SVD_Error.log" outfile = open(outfilename, "a") numpy.savetxt(outfile, numpy.transpose((data.x, data.y, data.cont))) outfile.write("\n\n\n\n\n") numpy.savetxt(outfile, numpy.transpose((model.x, model.y, model.cont))) outfile.write("\n\n\n\n\n") outfile.close() sys.exit("SVD did not converge! Outputting data to %s" %outfilename) #Invert matrices: # U, V are orthonormal, so inversion is just their transposes # W is a diagonal matrix, so its inverse is 1/W W1 = 1.0/W U_t = numpy.transpose(U) V = numpy.transpose(V_t) #Remove the smaller values of W W1[dimension:] = 0 W2 = diagsvd(W1,m,m) #Solve for the broadening function spec = numpy.transpose(mat(ynew[m/2:n-m/2-1])) temp = numpy.dot(U_t, spec) temp = numpy.dot(W2,temp) Broadening = numpy.dot(V,temp) #Make Broadening function a 1d array spacing = xnew[2] - xnew[1] xnew = numpy.arange(model.x[0], model.x[-1], spacing) model_new = Model(xnew) Broadening = numpy.array(Broadening)[...,0] #Ensure that the broadening function is appropriate: maxindex = Broadening.argmax() if maxindex > m/2.0 + m/10.0 or maxindex < m/2.0 - m/10.0: #The maximum should be in the middle because we already did wavelength calibration! outfilename = "SVD_Error2.log" numpy.savetxt(outfilename, numpy.transpose((Broadening, )) ) print "Warning! SVD Broadening function peaked at the wrong location! See SVD_Error2.log for the broadening function" idx = self.parnames.index("resolution") resolution = self.const_pars[idx] model = FittingUtilities.ReduceResolution(model, resolution) #Make broadening function from the gaussian centralwavelength = (data.x[0] + data.x[-1])/2.0 FWHM = centralwavelength/resolution; sigma = FWHM/(2.0*numpy.sqrt(2.0*numpy.log(2.0))) left = 0 right = numpy.searchsorted(xnew, 10*sigma) x = numpy.arange(0,10*sigma, xnew[1] - xnew[0]) gaussian = numpy.exp(-(x-5*sigma)**2/(2*sigma**2)) return FittingUtilities.RebinData(model, data.x), [gaussian/gaussian.sum(), xnew] elif numpy.mean(Broadening[maxindex-int(m/10.0):maxindex+int(m/10.0)]) < 3* numpy.mean(Broadening[int(m/5.0):]): outfilename = "SVD_Error2.log" numpy.savetxt(outfilename, numpy.transpose((Broadening, )) ) print "Warning! SVD Broadening function is not strongly peaked! See SVD_Error2.log for the broadening function" idx = self.parnames.index("resolution") resolution = self.const_pars[idx] model = FittingUtilities.ReduceResolution(model, resolution) #Make broadening function from the gaussian centralwavelength = (data.x[0] + data.x[-1])/2.0 FWHM = centralwavelength/resolution; sigma = FWHM/(2.0*numpy.sqrt(2.0*numpy.log(2.0))) left = 0 right = numpy.searchsorted(xnew, 10*sigma) x = numpy.arange(0,10*sigma, xnew[1] - xnew[0]) gaussian = numpy.exp(-(x-5*sigma)**2/(2*sigma**2)) return FittingUtilities.RebinData(model, data.x), [gaussian/gaussian.sum(), xnew] #If we get here, the broadening function looks okay. #Convolve the model with the broadening function model = DataStructures.xypoint(x=xnew) Broadened = UnivariateSpline(xnew, numpy.convolve(model_new,Broadening, mode="same"),s=0) model.y = Broadened(model.x) #Fit the broadening function to a gaussian params = [0.0, -Broadening[maxindex], maxindex, 10.0] params,success = leastsq(self.GaussianErrorFunction, params, args=(numpy.arange(Broadening.size), Broadening)) sigma = params[3] * (xnew[1] - xnew[0]) FWHM = sigma * 2.0*numpy.sqrt(2.0*numpy.log(2.0)) resolution = numpy.median(data.x) / FWHM #idx = self.parnames.index("resolution") #self.const_pars[idx] = resolution print "Approximate resolution = %g" %resolution #x2 = numpy.arange(Broadening.size) if full_output: return FittingUtilities.RebinData(model, data.x), [Broadening, xnew] else: return FittingUtilities.RebinData(model, data.x)
6c62049cb5f2edf0f3dcadae97b5d53b59885642
airt1me/first_text_game
/text game attempt 31-7-16.py
3,276
4.09375
4
import random import time def start_intro(): print('You have just woken up and are not sure where you are. \n' 'You look around the room you are in, it is wooden, unremarkable, \n' 'and dirty, there is a door leading out of the room to your left \n' 'and a window to your right \n' ' ') time.sleep(5) def first_decision(): print('You stand up, what do you want to 1) open the door 2) go look out \n' 'the window or 3) search the room? Please choose 1, 2 or 3.') action = '' while action != '1' and action != '2' and action != '3': print('Please choose 1, 2 or 3') action = input() if action == '1': # need to add whatever item is collected to a data structure print('You open the door, you see that you are in a forest and you \n' 'step outside for a better look and realise you were in a wooden \n' 'cabin, there is an axe leaning against the cabin, you pick \n' 'it up as it may be useful') elif action == '2': print('You go to the window, you see you are in a forest, you notice \n' 'a knife by the window, it might prove useful so you take it and \n' 'then head out the door') elif action == '3': print('You search the room, in a drawer you find some money, 10 gold \n' 'pieces, most like currency, you put them in your pocket then head \n' 'out the door') def storyline_one(): time.sleep(5) print('\n' 'As you take a step away from the cabin you hear a shout, to your right \n' 'there are four men running towards you looking angry, you start running \n' 'in the opposite direction. You run as fast as you can for some time, then \n' 'slow down, you can\'t hear them behind you anymore and you notice there are \n' 'buildings up ahead, it looks like a small village or a town, you approach \n' 'it cautiously...') time.sleep(8) print('A voice calls out, the men pursuing you have caught up and they don\'t sound \n' 'far behind you, you move up to the nearest house...') time.sleep(3) def second_decision(): print('\n' 'What do you want to do next either 1) knock on the door to try and talk the \n' 'person inside into letting you in and hiding you or 2) if you have a knife \n' 'use it to jimmy open the lock and let yourself in') action = '' while action != '1' and action != '2': print('Please choose 1 or 2') action = input() if action == '1': print('You knock on the door after a minute a man answers, he is unwilling \n' 'to let you in') elif action == '2': # add if statement to check if you have a knife print('You quietly move to the door and manage to open it, there is a man \n' 'sleeping in a chair in front of you, you close the door and sneak \n' 'into the bedroom and slide under the bed') start_intro() first_decision() storyline_one() second_decision()
90153f9040fcb8bec89172512a7aa5986bf16d84
shinji0215/programming
/python/fukusyu_list.py
4,116
3.65625
4
#リスト・・一度セットした値を変更可能 [] #タプル・・一度セットした値は変更不可 () #range・・連続した数値 #これら3つはイテレート可能なオブジェクト #リスト l_data1 = ['aa', 'bb', 'cc', 'dd', 'ee'] print(l_data1[0]) #aa print(l_data1[-1]) #ee 最後の要素 print(l_data1[0:3]) #['aa', 'bb', 'cc'] スライス index=0~2 print(l_data1[-3:-1]) #['cc', 'dd'] print(l_data1[::2]) #['aa', 'cc', 'ee'] 2つおきにスライス print(l_data1[::-1]) #['ee', 'dd', 'cc', 'bb', 'aa'] -1だと逆順でスライス #リストの更新 l_data1[0] = '11' print(l_data1) #['11', 'bb', 'cc', 'dd', 'ee'] l_data1.append('ff') #最後に追加 print(l_data1) #['11', 'bb', 'cc', 'dd', 'ee', 'ff'] l_data1.pop() #最後のデータを取り出す print(l_data1) #['11', 'bb', 'cc', 'dd', 'ee'] ret = l_data1.pop(0) #最初のデータを取り出す print(l_data1) #['bb', 'cc', 'dd', 'ee'] print(ret) #11 #list関数 リストを作成 print(list(range(10))) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(list(range(1, 11))) #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(list('book')) #['b', 'o', 'o', 'k'] #len関数 長さを返す print(len(l_data1)) #4 #リストのリスト(多重リスト) l_x = [1, 2, 3, 4, 5, 6] l_y = [10, 20, 30, 40, 50] l_area = [l_x, l_y] print(l_area) #[[1, 2, 3, 4, 5, 6], [10, 20, 30, 40, 50]] print(l_area[0]) #[1, 2, 3, 4, 5, 6] print(l_area[1][3]) #40 #2次元配列 l_ban = [] for i in range(3): l_ban.append(list(range(3))) print(l_ban) #3x3 [[0, 1, 2], [0, 1, 2], [0, 1, 2]] ##リストの操作 l_data2 = list('abc') l_data3 = list('def') l_data2.extend(l_data3) #別のリスト要素を追加 #l_data2 += l_data3 # +=でも同じ print(l_data2) #['a', 'b', 'c', 'd', 'e', 'f'] l_data3.insert(1, 'Z') #指定indexに要素を追加 print(l_data3) #['d', 'Z', 'e', 'f'] del l_data3[1] #指定indexの要素を削除 print(l_data3) #['d', 'e', 'f'] l_data2.remove('d') #値を指定して削除 indexがわからない時に使用 print(l_data2) #['a', 'b', 'c', 'e', 'f'] index = l_data2.index('b') #指定した値のindexを調べる print(index) #1 print('a' in l_data2) #True 値'a'が存在するか調べる l_data4 = list('a1b1c1') print(l_data4.count('1')) #指定した値がいくつ存在するか調べる n = [5, 3, 0, 4, 1] n.sort() #昇順で並べ替え print(n) #[0, 1, 3, 4, 5] n.sort(reverse=True) #降順で並べ替え print(n) #[0, 1, 3, 4, 5] #リストのコピー l_data5 = [1, 2, 3] l_data6 = l_data5 #参照の代入 print(l_data6) l_data5[0] = 99 #l_data5を変更 print(l_data6) #l_data6にも反映(l_data6はl_data5を参照) l_data5 = [1, 2, 3] l_data7 = l_data5.copy() #l_data5のコピー l_data8 = list(l_data5) #l_data5の全ての要素をコピー l_data9 = l_data5[:] #l_data5の全ての要素をスライスして作成 l_data5[1] = -99 print(l_data5) #[1, -99, 3] print(l_data7) #[1, 2, 3] 変化なし print(l_data7) #[1, 2, 3] 変化なし print(l_data7) #[1, 2, 3] 変化なし #リスト内表記 comp1 = [num for num in range(1, 6)] print(comp1) #[1, 2, 3, 4, 5] comp2 = [num for num in range(1, 6) if num % 2 == 1] print(comp2) #[1, 3, 5] # #タプル(書き換え不可) # t_1 = ('a', 'b', 'c', 'd') print(t_1) #('a', 'b', 'c', 'd') t_2 = 'A', 'B', 'C' #()は無くても良い。','がタプル print(t_2) #('A', 'B', 'C') a1, b1, c1, = t_2 #タプルは一度に変数に代入可能 print(a1, b1, c1, sep=':') #A:B:C def f_list(): print("p_list") if __name__ == "__main__": print("***fukusyu.py***") f_list()
2709a6ba676f938e6dfff92cca2cd5446c3f132d
jnnhuynh-web/Python_Challenge
/PyBank/main.py
2,544
4.03125
4
#BANK #import library import csv import os #import filepath csvpath = os.path.join("budget_data.csv") #open the file with open(csvpath) as file: #use filehandle as the name for the file filehandle = csv.reader(file,delimiter=',') #exclude the header row next(filehandle, None) #PART 1 #total months and net total amount of "Profit/Losses" #zero out the month and sum as the starting point total_month = 0 total_sum = 0 #list the revenue, dates, and list for revenue storage revenue = [] date = [] rev_change = [] #loop through the rows for the sum and month for i, eachrow in enumerate(filehandle): total_month += 1 total_sum += int(eachrow[1]) revenue.append(eachrow[1]) date.append(eachrow[0]) if i>=1: rev_change.append(int(revenue[i]) - int(revenue[i-1])) #max and min change max_rev_change = max(rev_change) min_rev_change = min(rev_change) #date of max and min change max_rev_change_date = (date[rev_change.index(max(rev_change))]) min_rev_change_date = (date[rev_change.index(min(rev_change))]) avg_rev_change = round(sum(rev_change) / len(rev_change)) #print summary header print("Financial Analysis") print("----------------------------") #print results print("Total Months: " + str(total_month)) print("Total: $" + str(total_sum)) #print the average change, the max and min change print("Average Revenue Change: $" + str(avg_rev_change)) print("Greatest Increase in Revenue:" + str(max_rev_change_date) + "($" + str(max_rev_change)+")" ) print("Greatest Decrease in Revenue:" + str(min_rev_change_date) +"($" + str(min_rev_change) + ")") #export the text file with the results output_path = os.path.join("results.txt") # Open the file using "write" mode. Specify the variable to hold the contents with open(output_path, 'w', newline='') as csvfile: # Initialize csv.writer csvwriter = csv.writer(csvfile, delimiter=',') # Write the rows csvwriter.writerow(['Financial Analysis']) csvwriter.writerow(['----------------------------']) csvwriter.writerow(['Total Months: ' + str(total_month)]) csvwriter.writerow(['Total: $' + str(total_sum)]) csvwriter.writerow(["Average Revenue Change: $" + str(avg_rev_change)]) csvwriter.writerow(["Greatest Increase in Revenue:" + str(max_rev_change_date) + "($" + str(max_rev_change)+")" ]) csvwriter.writerow(["Greatest Decrease in Revenue:" + str(min_rev_change_date) +"($" + str(min_rev_change) + ")"])
c1ac9b4695b9088810cb08fd8eea6a5c63def56c
cjbrooks/weather
/weather.py
993
3.625
4
#!usr/bin/env python from urllib2 import Request, urlopen, URLError import json city_list = ("Cambridge,USA", "Berkeley", "Oakland", "Palo_Alto") api_key = '306e98f72c67de6deffd7ac8f6151565' city_clean = [] temps = [] for city in city_list: #print city weather_api_call = "http://api.openweathermap.org/data/2.5/find?q="+city+"&mode=json&units=imperial&APPID="+api_key #print weather_api_call weather_call = urlopen(weather_api_call) weather = weather_call.read() data = json.loads(weather) #print data clean_city = data["list"][0]["name"] str(clean_city) print clean_city temp = data["list"][0]["main"]["temp"] print temp city_clean.append(clean_city) temps.append(temp) temps_dict = {} cities_and_temps = zip(city_clean, temps) for city, temp in cities_and_temps: temps_dict[city] = temp for key, value in temps_dict.iteritems() : happy = key + ":", value
18a868ca4246b213f675d3afd4f4699ced78cf57
bkstephen/milky_way_model_in_python
/milky_way_main.py
3,293
3.65625
4
import tkinter as tk from random import randint, uniform, random import math SCALE = 225 # enter 225 to see Earth's radio bubble NUM_CIVS = 15600000 root = tk.Tk() root.title("Milky Way galaxy") c = tk.Canvas(root, width=1000, height=800, bg='black') c.grid() c.configure(scrollregion=(-500, -400, 500, 400)) # actual Milky Way dimensions (light-years) DISC_RADIUS = 50000 DISC_HEIGHT = 1000 DISC_VOL = math.pi * DISC_RADIUS**2 * DISC_HEIGHT def scale_galaxy(): """Scale galaxy dimensions based on radio bubble size (scale).""" disc_radius_scaled = round(DISC_RADIUS / SCALE) bubble_vol = 4/3 * math.pi * (SCALE / 2)**3 disc_vol_scaled = DISC_VOL/bubble_vol return disc_radius_scaled, disc_vol_scaled def detect_prob(disc_vol_scaled): """Calculate probability of galactic civilizations detecting each other.""" ratio = NUM_CIVS / disc_vol_scaled # ratio of civs to scaled galaxy volume if ratio < 0.002: # set very low ratios to probability of 0 detection_prob = 0 elif ratio >= 5: # set high ratios to probability of 1 detection_prob = 1 else: detection_prob = -0.004757 * ratio**4 + 0.06681 * ratio**3 - 0.3605 * \ ratio**2 + 0.9215 * ratio + 0.00826 return round(detection_prob, 3) def random_polar_coordinates(disc_radius_scaled): """Generate uniform random (x, y) point within a disc for 2D display.""" r = random() theta = uniform(0, 2 * math.pi) x = round(math.sqrt(r) * math.cos(theta) * disc_radius_scaled) y = round(math.sqrt(r) * math.sin(theta) * disc_radius_scaled) return x, y def spirals(b, r, rot_fac, fuz_fac, arm): """Build spiral arms for tkinter display using logarithmic spiral formula. b = arbitrary constant in logarithmic spiral equation r = scaled galactic disc radius rot_fac = rotation factor fuz_fac = random shift in star position in arm, applied to 'fuzz' variable arm = spiral arm (0 = main arm, 1 = trailing stars) """ spiral_stars = [] fuzz = int(0.030 * abs(r)) # randomly shift star locations theta_max_degrees = 520 for i in range(theta_max_degrees): # range(0, 600, 2) for no black hole theta = math.radians(i) x = r * math.exp(b * theta) * math.cos(theta + math.pi * rot_fac) \ + randint(-fuzz, fuzz) * fuz_fac y = r * math.exp(b * theta) * math.sin(theta + math.pi * rot_fac) \ + randint(-fuzz, fuzz) * fuz_fac spiral_stars.append((x, y)) for x, y in spiral_stars: if arm == 0 and int(x % 2) == 0: c.create_oval(x - 2, y - 2, x + 2, y + 2, fill='white', outline='') elif arm == 0 and int(x % 2) != 0: c.create_oval(x - 1, y - 1, x + 1, y + 1, fill='white', outline='') elif arm == 1: c.create_oval(x, y, x, y, fill='white', outline='') def star_haze(disc_radius_scaled, density): """Randomly distribute faint tkinter stars in galactic disc. disc_radius_scaled = galactic disc radius scaled to radio bubble diameter density = multiplier to vary number of stars posted """ for i in range(0, disc_radius_scaled * density): x, y = random_polar_coordinates(disc_radius_scaled) c.create_text(x, y, fill='white', font=('Helvetica', '7'), text='.')
0c29e056ad03a4c33a459452a3307b34f78c5de9
vy3191/Graphs
/projects/graph/graph.py
8,903
4.40625
4
""" Simple graph implementation """ from util import Stack, Queue # These may come in handy class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): self.vertices = {} def add_vertex(self, vertex): """Add a vertex to the graph.""" self.vertices[vertex] = set() def add_edge(self, v1, v2): """Add a directed edge to the graph.""" if v1 in self.vertices and v2 in self.vertices: self.vertices[v1].add(v2) else: print('Error: Vertices were not found') def get_neighbors(self, starting_vertex): return self.vertices[starting_vertex] def bft(self, starting_vertex): """Print each vertex in breadth-first order beginning from starting_vertex.""" # Create an empty queue -- FIFO # Add starting_vertex to the queue and # this will keep track of next_to_visit_vertices queue = Queue() queue.enqueue(starting_vertex) # Create an empty set to track the visited vertices visited = set() # while queue is not empty while queue.size(): # dequeue the vertex off the queue current_vertex = queue.dequeue() # if current_vertex is not in visited set # add current vertex to the visited set if current_vertex not in visited: # print the current_vertex print(current_vertex) visited.add(current_vertex) # for each neighbor of the current_list **Add to queue for neighbor in self.vertices[current_vertex]: # Add all the neighbors of the current_list to the queue queue.enqueue(neighbor) return None def dft(self, starting_vertex): """Print each vertex in depth-first orderbeginning from starting_vertex.""" # Create an empty stack stack = Stack() # Add the starting_vertex to the stack # so that we can track the next_to_visit_vertices stack.push(starting_vertex) # Create an empty stack to track visited vertices visited = set() # while stack is not empty: while stack.size(): # Remove vertex off of the stack current_vertex = stack.pop() # If the current vertex is not in if current_vertex not in visited: #print the current_vertex print(current_vertex) # Add current_vertex to the visited visited.add(current_vertex) # for every neighbor of the current vertex for neighbor in self.vertices[current_vertex]: # Add neighbor to the stack stack.push(neighbor) return None def dft_recursive(self, starting_vertex, stack=None): """Print each vertex in depth-first orderbeginning from starting_vertex. This should be done using recursion.""" # Write a base case for dft_recursive if not starting_vertex: return None # Create an empty stack list using set if stack == None: stack = set() # check if the starting_vertex is in the stack or not # Add the starting_vertex to the stack to track the next_to_visit vertices if starting_vertex not in stack: stack.add(starting_vertex) for neighbor in self.get_neighbors(starting_vertex): self.dft_recursive(neighbor, stack) # Make sure not to pass self here return None def bfs(self, starting_vertex, destination_vertex): """Return a list containing the shortest path fromstarting_vertex to destination_vertex in breath-first order.""" # Create an empty queue # Add a path to the empty queue i.e., add [starting_vertex] to the queue queue = Queue() queue.enqueue([starting_vertex]) # Create an empty visited set to track of visited vertices visited = set() # while queue is not empty while queue.size(): # Dequeue the queue to get the current_path current_path = queue.dequeue() # Get the current_vertex from the current_path(last vertex in path array) current_vertex = current_path[-1] # if current_vertex not in visited: if current_vertex not in visited: #Add current_vertex to the visited visited.add(current_vertex) #if current_vertex == destination_vertex # return current_path if current_vertex == destination_vertex: return current_path # for each neighbor of the current_vertex for neighbor in self.vertices[current_vertex]: # get the copy of the current path current_path_copy = list(current_path) # add neighbor to the current path current_path_copy.append(neighbor) # now add this current path copy to the queue queue.enqueue(current_path_copy) return None def dfs(self, starting_vertex, destination_vertex): """Return a list containing a path fromstarting_vertex to destination_vertex in depth-first order.""" # Create an empty stack and add current_path to it # i.e., Add [starting_vertex] to the stack stack = Stack() stack.push([starting_vertex]) # Create an empty visited set to track the vertices if they are visited or not visited = set() # while stack is not empty while stack.size(): # Get the path from stack by deleting it current_path = stack.pop() # Get the current_vertex from current_path array(last item in the array) current_vertex = current_path[-1] # if current_vertex is not in the visited set if current_vertex not in visited: #Add it to the visited set visited.add(current_vertex) # if current vertex == destination_vertex if current_vertex == destination_vertex: return current_path # return the current path else: #for every neighbor of the current vertex for neighbor in self.vertices[current_vertex]: # get the copy of the current path current_path_copy = list(current_path) # add neighbor to current path copy current_path_copy.append(neighbor) # add the whole current path copy to the stack stack.push(current_path_copy) return None if __name__ == '__main__': graph = Graph() # Instantiate your graph # https://github.com/LambdaSchool/Graphs/blob/master/objectives/breadth-first-search/img/bfs-visit-order.png graph.add_vertex(1) graph.add_vertex(2) graph.add_vertex(3) graph.add_vertex(4) graph.add_vertex(5) graph.add_vertex(6) graph.add_vertex(7) graph.add_edge(5, 3) graph.add_edge(6, 3) graph.add_edge(7, 1) graph.add_edge(4, 7) graph.add_edge(1, 2) graph.add_edge(7, 6) graph.add_edge(2, 4) graph.add_edge(3, 5) graph.add_edge(2, 3) graph.add_edge(4, 6) ''' Should print: {1: {2}, 2: {3, 4}, 3: {5}, 4: {6, 7}, 5: {3}, 6: {3}, 7: {1, 6}} ''' print(graph.vertices) ''' Valid DFT paths: 1, 2, 3, 5, 4, 6, 7 1, 2, 3, 5, 4, 7, 6 1, 2, 4, 7, 6, 3, 5 1, 2, 4, 6, 3, 5, 7 ''' print("Executing Depth First Traverse>>>>>>>>>") graph.dft(1) ''' Valid BFT paths: 1, 2, 3, 4, 5, 6, 7 1, 2, 3, 4, 5, 7, 6 1, 2, 3, 4, 6, 7, 5 1, 2, 3, 4, 6, 5, 7 1, 2, 3, 4, 7, 6, 5 1, 2, 3, 4, 7, 5, 6 1, 2, 4, 3, 5, 6, 7 1, 2, 4, 3, 5, 7, 6 1, 2, 4, 3, 6, 7, 5 1, 2, 4, 3, 6, 5, 7 1, 2, 4, 3, 7, 6, 5 1, 2, 4, 3, 7, 5, 6 ''' print("Executing BFirst Traverse>>>>>>>>>") graph.bft(1) ''' Valid DFT recursive paths: 1, 2, 3, 5, 4, 6, 7 1, 2, 3, 5, 4, 7, 6 1, 2, 4, 7, 6, 3, 5 1, 2, 4, 6, 3, 5, 7 ''' print("Executing Depth First Recursive>>>>>>>>>") graph.dft_recursive(1) ''' Valid BFS path: [1, 2, 4, 6] ''' print("Executing BFirst Search>>>>>>>>>") print(graph.bfs(1, 6)) ''' Valid DFS paths: [1, 2, 4, 6] [1, 2, 4, 7, 6] ''' print("Executing Depth First Search>>>>>>>>>") print(graph.dfs(1, 6))
13bb9aaf0c9dc907633a38d3c3fcbead56cd33c2
asutoshpanigrahi07/firstproject
/oct/odd & sum.py
257
3.921875
4
m=int(input("enter the initial value")) n=int(input("enter the final value")) s=0 if m%2==1: for a in range (m,n+1,2): print(a) s=s+a print(s) else: m=m+1 for a in range (m,n+1,2): print(a) s=s+a print(s)
bc8a48186b3f18968005c57bcf0f77908b33cdc3
asutoshpanigrahi07/firstproject
/nov/charloop.py
99
3.578125
4
for i in range(3,0,-1): for j in range(i,0,-1): print(chr(119+i), end=" ") print()
8837a891d0ba345b1e8cbd845626000076072b46
asutoshpanigrahi07/firstproject
/oct/Q. 06.py
175
4.15625
4
a=int(input("enter the value of a")) b=int(input("enter the value of b")) if (b%a==0): print("a is fully divisible by b") else: print("a is not fully divisible by b")
928a8eda342cf9781b7b7fd946bf29541630e05a
asutoshpanigrahi07/firstproject
/leetcode/Queue.py
959
4.09375
4
class Queue: data=[] def __init__(self): data=[] def push(self,x): self.data.append(x) def pop(self): v=self.data.pop(0) print(v,' is being popped out') def search(self,x): if x in self.data: print(x,'is present the Queue') else: print(x,'is not present the Queue') def display(self): print(self.data) c=0 myqueue = Queue() while c<5: print("MAIN MENU") print("1.Add a element to the stack") print("2.Remove a element from the stack") print("3.Search") print("4.Display all") print("5.Exit") c=int(input("Enter your option:")) print("") if c==1: a=int(input("Enter the number you want to add:")) myqueue.push(a) elif c==2: myqueue.pop() elif c==3: a=int(input("Enter the number you want to search:")) myqueue.search(a) elif c==4: myqueue.display()
9ff93fbc3de742fc58cb653930ab7a12b02dc6b7
asutoshpanigrahi07/firstproject
/nov/fibonacii no..py
225
3.984375
4
n=int(input("Enter the no. of fibonacii no.:")) x=0 y=1 if n==1: print(x) elif n==2: print(x) print(y) else: print(x) print(y) for i in range(2,n): z=x+y print(z) x,y=y,x+y
6423de1df7dee7e6c287de814ab1ef6295c9b49f
prasannaaav/Data_Cleaning_project
/DataCleanerV2.py
1,573
3.796875
4
''' Created on Feb 23, 2021 @author: prasanna ''' import numpy as np import pandas as pd import tkinter as tk from tkinter import filedialog #1.Creating a dialog box enabling the user to select the desired excel root= tk.Tk() canvas1 = tk.Canvas(root, width = 300, height = 300, bg = 'lightsteelblue') canvas1.pack() #2.function that allows the user to select the data def getExcel (): global df import_file_path = filedialog.askopenfilename() u=import_file_path return u #end of the function #3.code that links the function and the gui browseButton_Excel = tk.Button(text='Import Excel File', command=getExcel, bg='green', fg='white', font=('helvetica', 12, 'bold')) canvas1.create_window(150, 150, window=browseButton_Excel) var=getExcel () #print(var) #data maipulation df=pd.read_excel(r'D:/Data_analysis_with_python/counterparties.xlsx') df=df.set_index('Sno.') #apply map used here to make all the items to uppercase df=df.applymap(lambda x: x.upper() if type(x)== str else x) df=df.applymap(lambda x: x.replace('[.:@"]','')) df=df.applymap(lambda x: x.replace("'","")) df['CounterpartyName']=df['CounterpartyName'].str.replace('LTD','') df['CounterpartyName']=df['CounterpartyName'].str.replace('LIMITED','') df['CounterpartyName']=df['CounterpartyName'].str.replace(' ','') df=df.duplicated(keep='first') l=(df[df]) y='The duplicates are:' top = tk.Toplevel() msg2=tk.Label(top,text=y,anchor='w') msg2.pack() msg = tk.Label(top, text=l,anchor='w') msg.pack() frame = tk.Frame(top, width=500, height=500) frame.pack() root.mainloop()
1bee5db70703db3004b93c5c40312602564a8098
pmin825/python-algos
/two_sum.py
197
3.625
4
def twoNumberSum(array, targetSum): hash = {} for i in range(len(array)): num = array[i] diff = targetSum - num if diff in hash: return [diff, num] else: hash[num] = True return []
dd9873e3979fc3621a89d469d273f830371d757a
kingamal/OddOrEven
/main.py
500
4.1875
4
print('What number are you thinking?') number = int(input()) while number: if number >=1 and number <= 1000: if number % 2 != 0: print("That's an odd number! Have another?") number = int(input()) elif number % 2 == 0: print("That's an even number! Have another?") number = int(input()) else: print("Thanks for playing") else: print("That's a wrong number! Try it again") number = int(input())
5835ee1ebe75f72cd44a173583ed9ba4b4313edc
sahilbnsll/Python
/Lists & Tuples/Program05.py
152
3.5
4
# Tuple Methods t = (1,4,6,9,1,3,5,1,4,1) print(t.count(1)) # Return number of occurence of values print(t.index(9)) # Return first index of value
d3d012d57ee0d909efb270522d1fdc693c181f03
sahilbnsll/Python
/Lists & Tuples/Practise Set/Problem02.py
441
3.921875
4
# Problem 2. Sorting Marks of 6 Students using sort() in Python m1 = int(input("Enter marks of student number 1: ")) m2 = int(input("Enter marks of student number 2: ")) m3 = int(input("Enter marks of student number 3: ")) m4 = int(input("Enter marks of student number 4: ")) m5 = int(input("Enter marks of student number 5: ")) m6 = int(input("Enter marks of student number 6: ")) myList = [m1,m2,m3,m4,m5,m6] myList.sort() print(myList)
916910d6ca390870186931278824d3d96510137b
sahilbnsll/Python
/Object Oriented Programming/Program01.py
148
3.703125
4
# Creating Class class Number: def sum(add): return (add.a + add.b) num = Number() num.a = 4 num.b = 3 s = num.sum() print(s)
d6a5f32aea3864aea415514dad886b81d434a8cc
sahilbnsll/Python
/Inheritence/Program01.py
949
4.25
4
# Basics of Inheritance class Employee: company= "Google Inc." def showDetails(self): print("This is a employee") class Programmer(Employee): language="Python" company= "Youtube" def getLanguage(self): print(f"The Language is {self.language}") def showDetails(self): print("This is Programmer Class.") e = Employee() e.showDetails() p = Programmer() p.showDetails() # Prints same content as e.showDetails because Programmer class doesn't have showDetails() so programmer class inherit showDetails() function from Base class Employee. print(p.company) # Prints "Google Inc." as Programmer class doesn't have company, so programmer class inherit company from Base class Employee. p.showDetails() # Prints "This is Programmer Class" as this time showDetails() is present in Programmer Class. print(p.company) # Prints "Youtube" as this time company is present in Programmer Class.
6e0f7759356bbfbf474fc5af93eb902e8a875661
sahilbnsll/Python
/Projects/Basic_Number_Game.py
406
4.15625
4
# Basic Number Game while(True): print("Press 'q' to quit.") num =input("Enter a Number: ") if num == 'q': break try: print("Trying...") num = int(num) if num >= 6: print("Your Entered Number is Greater than or equal to 6\n") except Exception as e: print(f"Your Input Resulted in an Error:{e}") print("Thanks For Playing.")
f6312249a01979a968a18d9765f44fbc323a55d2
sahilbnsll/Python
/Fuctions and Recursion/Practise Set/Problem03.py
187
4.0625
4
# Preventing python print() to print a new line at the end print("Hello,", end=" ") # By default, this end is end="\n" print("how", end=" ") print("are", end=" ") print("you?", end=" ")
b99568f0c3b67265183fef5bc7718bfb3aa193b8
sahilbnsll/Python
/Dictionary/Practise Set/Problem02.py
388
3.65625
4
# problem 2. - allow 4 friends to enter their favourite language as Values favLang={} a= input("Enter your favourite language Sahil: ") b= input("Enter your favourite language Dhruv: ") c= input("Enter your favourite language Kshitij: ") d= input("Enter your favourite language Parth: ") favLang['Sahil'] = a favLang['Dhruv'] = b favLang['Kshitij'] = c favLang['Parth'] = d print(favLang)
ed8513152295d58be6afdd3919223131d9a941de
sahilbnsll/Python
/Loops/Practise Set/Problem01.py
199
4.0625
4
# Problem 1. Multiplication Table. i=1 num=int(input("Enter a number: ")) for i in range(1,11): print(str(num)+" X "+str(i)+" = "+str(num*i)) #print(f"{num} X {i} = {num*i}") #same as above
94a3197a7042ed1352ad7b71df61fa0c1dca038b
sahilbnsll/Python
/Files Input Output/Program04.py
323
3.5
4
# With Statement with open('sample04.txt', 'r') as f: # by using with statement, you don't need to close the file as f.close() as it automatically done a = f.read() print(a) with open('sample04.txt', 'w') as f: a = f.write("With Statement Writing") #this line should be overwrite in your sample file
97061e39c0f754dc217ad865082a913e36cc6bcb
sahilbnsll/Python
/Object Oriented Programming/Practise Set/Problem05.py
1,095
3.90625
4
# Problem 5. Creating a Class train which has methods to book tickets, get status and get fare info. class Train: def __init__(self,myName,name,fare,seats): self.myName = myName self.name = name self.fare =fare self.seats = seats def getStatus(self): print(f"The name of the train is {self.name}") print(f"Available seats in this train is {self.seats}") print("*********") def bookTickets(self): if(self.seats>0): print(f"Dear {self.myName}, your Ticket has been booked!. Your Seat No. is {self.seats}") print("*********") self.seats = self.seats - 1 else: print("Sorry, This train is Full. Try in Tatkal(Emergency)") print("*********") def fareInfo(self): print(f"The price of the ticket is {self.fare}") print("*********") journey = Train("Sahil","Rajdhani", 200, 150) journey.getStatus() journey.fareInfo() journey.bookTickets() journey.getStatus() journey.myName="ayush" journey.bookTickets() journey.getStatus()
e60ae97af8c17ffa38e9d63a15f0d7adb384e4cf
hihello-jy/portfolio
/과제06(이준영)-최빈값 찾기.py
412
3.8125
4
from collections import Counter def findMax(numbers): c=Counter(numbers) numbers_freq=c.most_common() max_count=numbers_freq[0][1] modes=[] for num in numbers_freq: if num[1]==max_count: modes.append(num[0]) max_value=modes[-1] return max_value a1=[1,2,3,4,3,5,2,5,3] a2=[1,2,3,5,3,5,2,5,3] print(a1,findMax(a1)) print(a2,findMax(a2))