blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
c5d37e12a12dac2df8bf04bd536a9c84418b5ce9
seddon-software/python3
/Python3/src/13 Scientific Python/Pandas/12_covid.py
1,124
4.125
4
import pandas as pd pd.set_option('display.precision', 1) pd.set_option('display.width', None) # None means all data displayed pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) ''' Pandas 2D dataset are called dataframe. This example shows several methods of the dataframe. ''' def main(): df = pd.read_csv("data/covid.csv", engine = 'python') #, # skipinitialspace = True, # sep = '[*# ]+') # print(df) pd.set_option('display.width', 80) df = df.sort_values(by=['geography']) print(df.head()) # first five rows print(df.tail()) # last five rows print(df.sample(5)) # random sample of rows print(df.shape) # number of rows/columns in a tuple print(df.describe()) # calculates measures of central tendency df.info() # memory footprint and datatypes tmax = df.sort_values('tmax', axis=0, ascending=False) pd.set_option('display.max_rows', 20) print(tmax) main()
d2b0186cdd02cc43b02744d499ea724e2252ca2a
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/lngyas001/question4.py
574
3.765625
4
import math function = input('Enter a function f(x):\n') for y in range(10,-11,-1): for x in range(-10,11): new_function = round(eval(function)) if new_function == y: print('o', end = '') elif new_function != y and y != 0 and x !=0: print (' ',end= '') elif x == 0 and y == 0 and new_function != y: print ('+', end = '') elif x == 0 and new_function != y: print ('|', end = '') elif y == 0 and new_function !=y: print('-', end = '') print ()
cc2b67a4e83bdd889030bc4c9223cefa699e506c
duk1edev/projects
/PythonExamples/Python_Lesson2/PythonApplication1/elis_switch.py
295
4.09375
4
print("""Menu: 1.File 2.View 3.Exit """) choise = input("Enter your choise: ") if choise == "1": print("File menu open!") elif choise == "2": print("Choise view parameters") elif choise == "3": print("Exit!Press enter") else : print("You choose is wrong!Exiting program...")
c37fb45c3052c3403099a70dabaa738f7b67b1b7
mvitnyucoders/64squares
/algos/dec1/twoSum.py
605
3.640625
4
from typing import List class Solution: def twoSum(self, nums: List[int], target: int): h = {} # iterating a list for i, val in enumerate(nums): if target - val in h: # check if target value - current value exists in dictionary return [h[target - val], i] # add the values into dictionary if they don't exist there already h[val] = i p1 = Solution() print(p1.twoSum([2,7,11,15], 13)) # Time complexity # O(n) - only 1 for loops - 2n => O(n) # Space complexity # O(n) because only one dictionary is used
2d6502ccd78151922404c308cbd1dd6dbd39d54c
jadhavsmita/Letsupgrade-pyhton-assignment
/Day 8 Assignment.py
693
4.21875
4
#!/usr/bin/env python # coding: utf-8 # # Day 8 Assignment 1 # In[43]: fibonacci_cache={} def fibonacci(n): if n in fibonacci_cache: return fibonacci_cache[n] if n==1: value=1 elif n==2: value=1 elif n > 2: value = fibonacci(n-1) + fibonacci(n-2) fibonacci_cache[n]=value return value for n in range(1, 10): print(n, fibonacci(n)) # # Assignment 2 Day 8 # In[26]: try: fob=open("test","r") fob.write("It's my test file to verify exception handling in python!") except IOError: print("Error: can\'t find the file or read data") else: print("Write operation is performed siccessfully on the file")
04b8570841d921b6133ceee1e0fe36bfc2d6bbb8
GeorgeJopson/OCR-A-Level-Coding-Challenges
/53-Mortage Calculator (Extensions Available)/Mortgage Calculator.py
533
4.125
4
#Mortgage amount mortgage=int(input("Input the mortgage amount: ")) #Number of years years=int(input("Input how long you have to pay off the £{0:d} mortgage: ".format(mortgage))) #Interest interest=float(input("What is the interest: ")) months=years*12 interestMultiplier=interest/100 interestMultiplierPerMonth=interestMultiplier/12 mortgagePayment= mortgage*(interestMultiplierPerMonth*(1+interestMultiplierPerMonth)**months)/((1+interestMultiplierPerMonth)**months-1) print("Monthly Payment: £{0:.2f}".format(mortgagePayment))
f936cd4f957065b886e86865e66ee4c84f4ff5a5
sunilsm7/python_exercises
/python_3 by pythonguru/defaultarg.py
120
3.53125
4
def func(i,j=100): print("Addition",i+j) v1 = int(input("Enter value1:")) v2 = int(input("Enter value2:")) func(v1,v2)
cdea58774f8c025d1a7ae33b403aaf64735647ff
GDN2/DL
/DeepLearning/backpropagation_simulator.py
1,128
3.53125
4
import numpy as np W2 = np.array([1,1,2,1]).reshape(2,2) W3 = np.array([2,1,1,1]).reshape(2,2) T = np.array([2,1]) b2 = np.array([1,1]) b3 = np.array([0,2]) learning_rate = 0.1 A1 = np.array([1,2],ndmin=2) A2 = np.random.rand(1,2) A3 = np.random.rand(1,2) def sigmoid(z): dic = { 0:-3, 1:-2, 2:-1, 3:0, 4:1, 5:2, 6:3, 7:4 } z[0][0] = dic[z[0][0]] z[0][1] = dic[z[0][1]] return z def feedforward(): Z2 = np.dot(A1, W2) + b2 A2 = sigmoid(Z2) Z3 = np.dot(A2, W3)+b3 A3 = sigmoid(Z3) return A2, A3 A2, A3 = feedforward() print(A2) print(A3) def backpropagation(b3, W3, b2, W2): loss3 = (A3-T)*A3*(1-A3) loss2 = np.dot(loss3, W3.T)*A2*(1-A2) b3 = b3 - learning_rate*loss3 W3 = W3 - learning_rate*np.dot(A2.T, loss3) b2 = b2 - learning_rate*loss2 W2 = W2 - learning_rate*np.dot(A1.T, loss2) return b3, W3, b2, W2 b3, W3, b2, W2 = backpropagation(b3, W3, b2, W2) print("backpropagation") print("b3", b3) print("W3", W3) print("b2", b2) print("W2", W2)
8dac1029344b3e2fda805996909e196647388d5a
slamatik/Free_Code_Camp
/Scientific Computing with Python Projects/Arithmetic Formatter/arithmetic_arranger.py
1,796
3.953125
4
def arithmetic_arranger(problems, display_answer=False): if len(problems) > 5: return "Error: Too many problems." temp_first_line = [] temp_second_line = [] temp_dashed_line = [] temp_answer_line = [] for question in problems: left = question.split()[0] operator = question.split()[1] right = question.split()[2] # Checks if operator not in "+-": return "Error: Operator must be '+' or '-'." if len(left) > 4 or len(right) > 4: return "Error: Numbers cannot be more than four digits." try: if operator == "+": answer = int(left) + int(right) elif operator == "-": answer = int(left) - int(right) answer = str(answer) except ValueError: return "Error: Numbers must only contain digits." question_len = max(len(left), len(right)) + 2 temp_first_line.append(" " * (question_len - len(left)) + left) temp_second_line.append(operator + " " * (question_len - 1 - len(right)) + right) temp_dashed_line.append("-" * question_len) temp_answer_line.append(" " * (question_len - len(answer)) + answer) first_line = " ".join(temp_first_line) second_line = " ".join(temp_second_line) dash_line = " ".join(temp_dashed_line) answer = " ".join(temp_answer_line) if display_answer: arranged_problems = f"{first_line}\n{second_line}\n{dash_line}\n{answer}" else: arranged_problems = f"{first_line}\n{second_line}\n{dash_line}" return arranged_problems print(arithmetic_arranger(["3 + 855", "3801 - 2", "45 + 43", "123 + 49"])) print(arithmetic_arranger(["32 + 8", "1 - 3801", "9999 + 9999", "523 - 49"], True))
e342e28881b5e78c5d1c3319f2d51ceb742de145
java131312/python_execise
/2017-04-21/for1list.py
116
3.75
4
#!/bin/env python #! -*- coding:utf-8 -*- #这里可以写中文。 print [x * x for x in range(1,11) if x %2 == 0]
aed54136b8ce03669e30835d8c287f094a8b9b7f
zupph/CP3-Supachai-Khaokaew
/Exercise5_2_Supachai_K.py
353
3.59375
4
s = int(input("กรุณาใส่ค่าระยะทางการเคลื่อนที่ (km) : ")) t = int(input("กรุณาใส่ค่าเวลาในการเคลื่อนที่ (h) : ")) v = s/t print("อัตราเร็วของการเคลื่อนที่คือ : ", v, " km/h")
02a9d436b130ab9d005a2f3edd4178b7292657ba
infinityman8/logbook-week-13-15
/week 13 q1.py
787
3.734375
4
class Animal(): def __init__(self,types,name): self.types=types self.name=name def getAnimalString(self): return "animal name: %s, type: %s" %(self.name, self.types) class Mammal(Animal): def __init__(self, species, name): super().__init__("mammal", name) self.species = species class Insect(Animal): def __init__(self, species, name): super().__init__("insect", name) self.species = species def getAnimalString(self): result = super().getAnimalString() return "%s, animal species: %s" %(result, self.species) mammal1 = Mammal("dog", "Alsatian") insect1 = Insect("bee", "bummble bee") print(mammal1.getAnimalString()) print(insect1.getAnimalString())
20d52f6d911ff4e89bd65b0e1fb8d91b1592610e
rakesh08061994/github_practice
/Project (2).py
570
4.34375
4
# BMI Calculator height = float(input("Enter your Height in centemeter : ")) weight = float(input("Enter your weight : ")) new_height = height/100 BMI = weight/(new_height * new_height) print("Your body mass index is : ",BMI) if BMI > 0: if BMI <= 16: print("You are severly underweight") elif BMI <= 18.5: print("You are underweight!") elif BMI <= 25: print("Your are healthy!") elif BMI <= 30: print("You are overweight !") else: print("You are severly overweight") else: print("Enter Valid details.")
3c82ebf0ae4e52945ee6956800414238bb48e67f
michalczaplinski/scrabblez
/scrabble_letter_counter.py
2,423
3.71875
4
#!/usr/bin/env python '''Scrabble tile counter. Returns neat statistics about the tiles that are still left in the game. The respective commands allow you to keep track of the tiles played so far, as well as remove tiles that have been entered in error. The count command runs the statistics Usage: scrabble_letter_counter.py add <tiles> scrabble_letter_counter.py remove <tiles> scrabble_letter_counter.py count ''' from docopt import docopt from os.path import join, dirname, realpath def get_tiles(tiles_path): with open(tiles_path, 'a+') as f: f.seek(0) return f.read() def add_tiles(tiles_path, tiles_to_add): with open(tiles_path, 'a') as f: f.write(tiles_to_add) def remove_tiles(tiles_path, all_tiles, tiles_to_remove): new_tiles = all_tiles.translate(None, tiles_to_remove) with open(tiles_path, 'w') as f: f.write(new_tiles) def calculateOdds(letter, letter_freq, num_all): return float(letter_freq[letter]) / float(num_all) def getLetterFrequencies(tiles_on_board): letter_freq = {'e': 12, 'a': 9, 'i': 9, 'o': 8, 'n': 6, 'r': 6, 't': 6, 'l': 4, 's': 4, 'u': 4, 'd': 4, 'g': 3, 'b': 2, 'c': 2, 'm': 2, 'p': 2, 'f': 2, 'h': 2, 'v': 2, 'w': 2, 'y': 2, 'k': 1, 'j': 1, 'x': 1, 'q': 1, 'z': 1} tiles_on_board = tiles_on_board.replace(' ', '') for i in tiles_on_board: letter_freq[i] = letter_freq[i] - 1 num_all = sum(x for x in letter_freq.itervalues()) num_vovels = sum([letter_freq[x] for x in letter_freq if x in 'aeiuoy']) print num_all, 'tiles left' print float(num_vovels)/float((num_all)) * 100, 'percent are vovels' for k in sorted(letter_freq, key=letter_freq.get, reverse=True): if letter_freq[k] > 0: odds = round(calculateOdds(k, letter_freq, num_all)) print k, '\t', odds, 4*100, '\t', '*' * letter_freq[k] def main(): arguments = docopt(__doc__) tiles_path = join(dirname(realpath(__file__)), 'word_count.txt') all_tiles = get_tiles(tiles_path) current_tiles = arguments['<tiles>'] if arguments['add'] is True: add_tiles(tiles_path, current_tiles) elif arguments['remove'] is True: remove_tiles(tiles_path, all_tiles, current_tiles) elif arguments['count'] is True: getLetterFrequencies(all_tiles) if __name__ == '__main__': main()
52460b7b7543f9a18b168d00e561c0b382493a29
AlexandrShestak/mag_python
/lab6/iterators.py
250
3.578125
4
import itertools def unique(iterable): visited = set() for elem in iterable: if elem not in visited: yield elem visited.add(elem) def transpose(iterable): return list(itertools.izip_longest(*iterable))
f25e7a4560fcde9427f723cd182c6c699edae30b
daniel-reich/ubiquitous-fiesta
/wwN7EwvqXKCSxzyCE_7.py
460
3.78125
4
def reorder_digits(lst, direction): new_lst = [] if direction == 'asc': for i in lst: i = list(str(i)) i.sort() i = int("".join(i)) new_lst.append(i) return new_lst elif direction == 'desc': for i in lst: i = list(str(i)) i.sort() i = list(reversed(i)) i = int("".join(i)) new_lst.append(i) return new_lst
af407fcf80b0abe57cdc63e4c5e5922f4fa1f7e5
zsmountain/lintcode
/python/stack_queue_hash_heap/541_zigzag_iterator_ii.py
1,348
3.9375
4
''' Follow up Zigzag Iterator: What if you are given k 1d vectors? How well can your code be extended to such cases? The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". Have you met this question in a real interview? Example Given k = 3 1d vectors: [1,2,3] [4,5,6,7] [8,9] Return [1,4,8,2,5,9,3,6,7]. ''' import heapq class ZigzagIterator2: """ @param: vecs: a list of 1d vectors """ def __init__(self, vecs): # do intialization if necessary self.data = [(j, i, vecs[i][j]) for i in range(len(vecs)) for j in range(len(vecs[i]))] heapq.heapify(self.data) """ @return: An integer """ def next(self): # write your code here return heapq.heappop(self.data)[2] """ @return: True if has next """ def hasNext(self): # write your code here return len(self.data) > 0 # Your ZigzagIterator2 object will be instantiated and called as such: # solution, result = ZigzagIterator2(vecs), [] # while solution.hasNext(): result.append(solution.next()) # Output result vecs = [[1, 2, 3], [4, 5, 6, 7], [8, 9]] solution, result = ZigzagIterator2(vecs), [] while solution.hasNext(): result.append(solution.next()) print(result)
5c19969f4190acbfd063cc2f2066cc3dbe743776
QuentinDuval/PythonExperiments
/arrays/FindMissingAndRepeating.py
3,068
3.640625
4
""" https://practice.geeksforgeeks.org/problems/find-missing-and-repeating/0 Given an unsorted array of size N of positive integers. One number 'A' from set {1, 2, …N} is missing and one number 'B' occurs twice in array. Find these two numbers. Note: - If you find multiple answers then print the Smallest number found. - Also, expected solution is O(n) time and constant extra space. """ """ How to approach it? - We cannot sort because it is O(n log n) - We cannot use a hash map because it would require extra space => We need to find two tricks to summarize the numbers, 2 equations to solve it But there are other solutions as well: https://www.geeksforgeeks.org/find-a-repeating-and-a-missing-number/ """ """ TWO EQUATIONS If we sum the entire collection to S, we can compare the sum with N(N+1)/2 (the normal sum) If we multiply the entire collection to P, we can compare the sum with N! (the normal production) We have: r - m = S - N(N+1)/2 r / m = P / N! => r = m + S - N(N+1)/2 m = (S - N(N+1)/2) / (P / N! - 1) TOO SLOW (due to the big numbers) """ def missing_and_repeating_1(nums): n = len(nums) nums_sum = 0 nums_prod = 1 normal_prod = 1 for i, val in enumerate(nums): nums_sum += val nums_prod *= val normal_prod *= i + 1 diff_sum = nums_sum - n * (n + 1) / 2 ratio_prod = nums_prod / normal_prod missing = diff_sum / (ratio_prod - 1) repeating = missing + diff_sum return round(repeating), round(missing) """ MARK NEGATIVE INDEX (use MUTABILITY) Mark as negative the indexes of the elements you visit: - If an element is already negative, it means the index is the value of the repeated element - If at the end an element is positive, it is the index of the missing element (second scan) Another approach (that avoids a second scan) is to sum the collection and make the different with N(N+1)/2. S - repeating + missing = N(N+1)/2 FAST ENOUGH (smaller numbers) """ def missing_and_repeating_2(nums): n = len(nums) repeating = 0 nums_sum = 0 for i, val in enumerate(nums): if nums[abs(val) - 1] < 0: repeating = abs(val) else: nums[abs(val) - 1] *= -1 nums_sum += abs(val) diff_sum = nums_sum - n * (n + 1) // 2 missing = repeating - diff_sum return repeating, missing """ MARK NEGATIVE INDEX (use MUTABILITY) - variant Mark as negative the indexes of the elements you visit, and the collect the positive elements """ def missing_and_repeating(nums): for val in nums: nums[abs(val) - 1] *= -1 incorrects = [] for i in range(len(nums)): if nums[i] > 0: incorrects.append(i+1) if incorrects[0] in nums: return incorrects[0], incorrects[1] else: return incorrects[1], incorrects[0] print(missing_and_repeating([1, 3, 3])) # (3, 2) print(missing_and_repeating([1, 14, 31, 8, 18, 33, 28, 2, 6, 16, 20, 3, 34, 17, 19, 21, 24, 25, 32, 11, 30, 13, 27, 7, 26, 29, 27, 15, 4, 12, 22, 5, 9, 10])) # (27, 23)
b3bfd740ab8fe3ac47e76e6bc0272fc40b5dcdea
xuxiazhuang/LeetCode
/python_leetcode/_561.py
871
3.796875
4
Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. Example 1: Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). solution1: class Solution: def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() list_sum=[] for i in range(int(len(nums)/2)): list_min=min(nums[2*i:2*i+2]) list_sum.append(list_min) result=sum(list_sum) return result solution2: class Solution(object): def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ return sum(sorted(nums)[::2])
b32e81caf0e9d8a9b5a0f0a4cffcaf64a23a52ac
sweetyn/Leetcode
/traversal_bin.py
917
4.125
4
"""graph traversal, binary search tree, OOP 1 2 3 4 5 Depth First Traversals: (a) Inorder (Left, Root, Right) : 4 2 5 1 3 (b) Preorder (Root, Left, Right) : 1 2 4 5 3 (c) Postorder (Left, Right, Root) : 4 5 2 3 1""" class Node(object): def __init__(self, val): self.left = None self.right = None self.val = val def inorder(root): if root: print("left") inorder(root.left) print("root") print(root.val) inorder(root.right) print("right") def preorder(root): if root: print(root.val) preorder(root.left) preorder(root.right) # Driver code root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print (inorder(root)) # print ("Preorder : " + preorder(root)) # print ("Ineorder : " + inorder(root)) # print ("Preorder : " + preorder(root))
ee112893b97db689308ddf37ba78a4554af14fe8
aramosescobar/Aliciamonday9
/Monday 9/monday.py
251
3.765625
4
for i in range(0,5): print("first identification") for j in range(0,3): print("Second indentation") for k in range(0,10): print("third identidication") print("forth identification") print("fifth identification")
d67a09531ca47b192f39a88f96bf77aa085c1fbd
Sarthak-Singhania/Work
/Class 11/untitled1.py
129
3.859375
4
def countSquares(n): return (((n+1) * (n + 2) / 2) * (2 * (n+1) + 1) / 3) n = 8 print("Count of squares is ",countSquares(n))
b943fef0e483cb0b71bfcb07f3dd43fcaf27328f
brenj/solutions
/hacker-rank/python/numpy/arrays.py
248
4.15625
4
# Arrays Challenge """ You are given a space separated list of numbers. Your task is to print a reversed NumPy array with the element type float. """ import numpy numbers = raw_input().split() numbers.reverse() print numpy.array(numbers, float)
14247a965997a52a6ea723febe81848a92eb0229
jingong171/jingong-homework
/尤焕雄/第一次作业/第一次作业 金工1 尤焕雄 2017310411/zhishu.py
138
3.546875
4
num=[]; for m in range(2,100): for n in range(2,m): if (m%n==0): break else: num.append(m) print(num)
7ae6149d6dca398f55c1f886636499bb9e0752d2
LINLUZHANGZZ1/----
/三家餐馆_cases.py
607
3.765625
4
class Restaurant(): """这里是表示一家餐馆的类""" def __init__(self,restaurant_name,cuisine_type): """初始化属性name和type""" self.restaurant_name=restaurant_name self.cuisine_type=cuisine_type def describe_restaurant(self): print("这家餐厅的名字是"+self.restaurant_name.title()+" 类型是"+self.cuisine_type.title()) def open_restaurant(self): print("这家餐馆正在营业") restaurant1=Restaurant('KFC','快餐店') restaurant2=Restaurant('田野餐厅','中式快餐店') restaurant1.describe_restaurant()#调用方法describe restaurant2.describe_restaurant()
f69feb6df2b451b6d6c17c7f44736be2b9f02fd3
EmersonBraun/python-excercices
/cursoemvideo/ex065.py
927
4.03125
4
# Crie um programa que leia vários números inteiros pelo teclado. # No final da execução, mostre a média entre todos os valores # e qual foi o maior e o menor valores lidos. # O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores cont = 0 total = 0 continua = 'S' while True: entrada = int(input('Digite um número inteiro: ')) if cont == 0: maior = entrada menor = entrada else: if entrada > maior: maior = entrada if entrada < menor: menor = entrada total += entrada cont += 1 continua = str(input('Deseja continuar? [S/N] ')).strip().upper()[0] if continua == 'N': break if continua == 'S': continue if continua not in 'SN': print('Opção inválida! ') print(f"\nForam lidos {cont} números \ncom a média de: {total/cont}\no menor: {menor}\no maior: {maior} ")
eebf73dd9eff454febb5bc90e7a5aab1111b5e06
emehrawn/mehran.github.io
/Python/Tkinter/tkinterMessagebox.py
544
4.0625
4
''' This program is a simple example of Message Box in Tkinter where you can use various types, in this program we only came across (askquestion & showinfo) ''' from tkinter import * import tkinter.messagebox root=Tk() answer=tkinter.messagebox.askquestion("Question","Do you get offended if i use swear words?") if answer=="no": tkinter.messagebox.showinfo("Information Title","You're a nice person") else: tkinter.messagebox.showinfo("Information Title","You're just another typical shithead") root.mainloop()
85cfec59c000a0eebddda678bd4044e6b274b266
Enfernuz/project-euler
/problem-2/O(logN)_0.py
774
4.0625
4
#python 3 def getSumOfEvenFibonacciTerms (limit): prevTerm = 1 nextTerm = 2 sum = 2 # Starting from the term 2, each next 3rd Fibonacci term is even (indexing from 1). # The logic is simple: # 1 (odd) + 2 (even) = 3 (odd) --> the start of the sequence: odd + even = odd, order = 1 # 2 (even) + 3 (odd) = 5 (odd) --> even + odd = odd, order = 2 # 3 (odd) + 5 (odd) = 8 (even) --> odd + odd = even, order = 3 # 5 (odd) + 8 (even) = 13 (odd) --> the sequence repeats from here # ... order = 1 while nextTerm <= limit: tmp = nextTerm nextTerm = prevTerm + nextTerm prevTerm = tmp if order == 3: sum += nextTerm order = 1 else: order += 1 return sum print( getSumOfEvenFibonacciTerms(4000000) )
334b59e794cccd1ab78c1c80d82cadb4dd998698
digitalladder/leetcode
/problem70.py
1,140
3.546875
4
#problem 70 /Climbing Stairs #DP with memory class Solution: def climbStairs(self, n): memo = [0]*(n+1) x = self.ways(0,n,memo) return x def ways(self,i,n,memo): if i>n: return 0 if i == n: return 1 if memo[i]>0: return memo[i] memo[i] = self.ways(i+1,n,memo)+self.ways(i+2,n,memo) return memo[i] #DP with memory version 2 using hashing class Solution: def climbStairs(self, n: int) -> int: memo = {1:1,2:2} #初始字典,一个台阶和两个台阶的情况,相当于递归推出条件 x = self.ways(n,memo) return x def ways(self,n,memo): if n not in memo: memo[n] = self.ways(n-1,memo)+self.ways(n-2,memo) return memo[n] #DP bottom to top class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n == 1: return 1 res = [0 for i in range(n)] res[0] = 1 res[1] = 2 for i in range(2,n): res[i] = res[i-1]+res[i-2] return res[n-1]
54834efd7e3fa0a71075a1c11534bab7b5654229
Artinto/Python_and_AI_Study
/Week02/Main_HW/Nested Lists/Nested Lists_LGY.py
1,916
3.890625
4
#key, value 나눠 sort. dict에서 찾아서 프린트 if __name__ == '__main__': student = {} ans = [] for _ in range(int(input())): name = input() score = float(input()) # input값을 받아서 student[name] = score # dictionary로 저장 names = student.keys() # key, value로 각각 리스트 생성 scores = student.values() S = sorted(list(set(scores))) # set으로 중복제거 second = S[1] # 두번째로 낮은 점수 A = [name_ for name_, score_ in student.items() if score_ == second] # student라는 딕셔너리에서 value(score)값이 '두번째로 낮은 점수(second)'와 같다면(if), # 그때 key(name)값을 A라는 list로 만듦. A.sort() # 알파벳 순으로 정렬하기 위해 for i in A: # 하나씩 프린트 print(i) ------------------------------------------------------------------------------ # dict 정렬 사용, 찾아서 프린트 if __name__ == '__main__': student = {} ans = [] for _ in range(int(input())): name = input() score = float(input()) # input값을 받아서 student[name] = score # dictionary로 저장 scores = student.values() S = sorted(list(set(scores))) # set으로 중복제거 second = S[1] # 두번째로 낮은 점수 Student = dict(sorted(student.items(), key = lambda x : x[0])) # lambda x : x[0] # x라는 인자가 들어오면 x[0]을 출력한다. >> student.keys() # sort을 거치면 tuple형태로 출력되서 dict형태로 바꿈 # Student : student를 알파벳순으로 정렬한 dict for name_, score_ in Student.items(): #알파벳순으로 정렬된거 중에 if score_ == second: # 찾는 점수와 같으면 print(name_) # 그때 key값 출력
88289486c2e412bec81d25e880bdedc6d1d938f4
MoazMansour/data-structures
/Binary_search_tree.py
1,536
4.09375
4
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BST(object): def __init__(self, root): self.root = Node(root) def insert(self, new_val): current = self.root notPlaced = True while notPlaced: if new_val < current.value: if not current.left: current.left = Node(new_val) notPlaced = False current = current.left else: if not current.right: current.right = Node(new_val) notPlaced = False current = current.right def search(self, find_val): current = self.root if current.value == find_val: return True notFound = True while notFound: if find_val < current.value: if not current.left: return False notFound = False current = current.left elif find_val > current.value: if not current.right: return False notFound = False current = current.right else: return True notFound = False # Set up tree tree = BST(4) # Insert elements tree.insert(2) tree.insert(1) tree.insert(3) tree.insert(5) # Check search # Should be True print tree.search(4) # Should be False print tree.search(6)
81dcbe272b97d8a349e6be11646c615d523c513c
itscrisu/pythonPractice
/Guías/diccionarios2.py
1,036
3.546875
4
# Vamos a crear otro diccionario y utilizarlo para practicar otras cosas: gatitos = { "Frodo": { "nombre": "Frodo", "edad": 3, "ronronea": "Si, muy bajito", "hermoso": "Si" }, "Sami": { "nombre": "Sami", "edad": 2, "ronronea": "Muchisimo", "hermoso": "Muy" } } # Tambien podemos definir antes las variables Sami y Frodo con los valores que están dentro de nuestro # diccionario, así evitamos tener tanto choclo adentro de un mismo diccionario. Quedaría el código de esta forma: # frodo = { # "nombre": "Frodo", # "edad": 3, # "ronronea": "Si, muy bajito", # "hermoso": "Si" # } # sami = { # "nombre": "Sami", # "edad": 2, # "ronronea": "Muchisimo", # "hermoso": "Muy" # } # gatitos = { # "Frodo": frodo, # "Sami": sami # } # Otra forma de declarar un diccionario es esta: # perritos = dict(nombre="Priya", edad=2, ronronea="No", hermosa="Muy") # Todas estas formas alternativas son correctas, no hay una mejor o peor
3d33017c6480d0526d4a63054cd69fbe48da036b
leeanna96/Python
/Chap03/직선 방정식 구하기.py
323
3.6875
4
x1=int(input("첫 번째 점의 x좌표: ")) y1=int(input("첫 번째 점의 y좌표: ")) x2=int(input("두 번째 점의 x좌표: ")) y2=int(input("두 번째 점의 y좌표: ")) if x2-x1!=0: m=(y2-y1)/(x2-x1) q=y1-m*x1 print("직선의 방정식은",m,"x+",q) else: print("직선의 방정식은 x=", x1)
43bc39623cf54d05d607c70c1539bfd78650abbd
gauravsarvaiya/python-codes
/lambda.py
857
4.15625
4
# changes # lambda expression # other name is anonymous function # lambda exprestion means name without funtion # lambda use map,filter etc # add=lambda a,b: a+b # print(add(10,20)) # multply=lambda a,b: a*b lambda use in programe # print(multply(10,10)) # g1 = lambda a: a**2 # print(g1(10)) # def func(a): # return a%2==0 #simple function create # print(func(8)) # h1=lambda a: a%2==0 #lambda form # print(h1(5)) # def last_char(s): # return s[-1] # print(last_char('gaurav')) # l_char=lambda s :s[-1] # print(l_char('yash')) # if ,else in lambda # def g1(s): # if len(s)>5: # print(True) # else: # print(False) # # print(g1('abcf')) # w1=lambda s:True if len(s) > 5 else False # print(w1('qqqqqq')) j1=lambda s: s[::-1].title() print(j1('gaurav')) i = 10 while (i<=10): print(i) i=i+1
bce3b5395752a971ba2797fc3fbdd7cecdb54dec
cb2411/2019-camerino-ODD
/potions/tools/cooking.py
1,524
3.671875
4
"""This file contains all defined cooking methods for brewing potions. All cooking methods are functions, so there are docstrings available. In case you are wondering, this is the text in the module docstring of /tools/cooking.py . """ dummy = 1 def stir(potion, direction): """Stirs the potion. Updates colour in the class instance. Parameters ---------- potion : Potion instance The potion to be stirred. direction : {'clockwise', 'anti-clockwise'} str The direction in which the potions is to be stirred """ if direction == "clockwise": potion.colour = "vomit-yellow" print('NO!! Your potion turns vomit-yellow. Did you stir in the right direction?') return if direction == "anti-clockwise": potion.colour = "newt-green" print('Your potion turns a lovely newt-green.') return def simmer(potion, duration): """Cooks the potion. Updates simmer_duration and cooked attributes in the class instance. Parameters ---------- potion : Potion instance The potion to be cooked. duration : int How long to cook the potion for [hours]. """ potion.simmer_duration = duration if duration < 2: print('Are you sure you are cooking the potion enough? Your ingredients look a bit raw...') elif duration > 5: print('Oops, you have fallen asleep at your desk! Are you sure you want to simmer this long?') else: potion.cooked = True return
5a298518591eea60a0bc001de1495a5c60bf272a
abhinandan991/Projects-and-Assignments
/CS50/pset6/hello/hello.py
89
3.78125
4
#Takes input for name a=input("What is your name?\n") #prints required print("hello,", a)
f19603ec3564cd21914d37124fd478c9be9466e5
ryosuke071111/algorithms
/AtCoder/ABC/card_game_easy.py
256
3.578125
4
from collections import deque A=deque(input()) B=deque(input()) C=deque(input()) turn={"a":A,"b":B,"c":C} next = A.popleft() flag = True while flag: if len(turn[next]) != 0: next = turn[next].popleft() else: print(next.upper()) break
81b099d183251d5cb3cc4a21e6ab378f001c344a
rShar01/Scrapespeare
/ScrapeShakespeare.py
3,470
3.59375
4
from bs4 import BeautifulSoup from requests import get from warnings import warn from heapq import nlargest import matplotlib.pyplot as plt """ To be honest, I don't have any meaningful analysis of this information. If you do, go right ahead and use this code I just did this as practice """ print("Welcome to the Shakespeare word counter!") print("Enter a word you want to see the frequency of") print("Alternatively enter 'ALL_WORDS' to get a bar graph of the 75 most used words") search_word = input() headers = {"Accept-Language": "en-US, en;q=0.5"} url = "http://shakespeare.mit.edu/" response = get(url, headers=headers) if response.status_code != 200: warn("Did not connect properly") main_page_parser = BeautifulSoup(response.text, 'html.parser') all_works_html = main_page_parser.findAll('a') all_works_html.pop(0) all_works_html.pop(0) all_works_html.pop(-1) all_works_html.pop(-1) all_works_links = [] for a in all_works_html: all_works_links.append(a['href']) """ sample code of one instance I based my loop around first_link = all_works_links[0] response = get("http://shakespeare.mit.edu/" + first_link[0:-10] + "full.html") html_parser = BeautifulSoup(response.text, 'html.parser') all_sentences = html_parser.findAll('blockquote') for sentence in all_sentences: list_of_words = sentence.text.split() for word in list_of_words: if word in dict_of_words.keys(): dict_of_words[word] = dict_of_words[word] + 1 else: dict_of_words[word] = 1 """ if search_word == 'ALL_WORDS': dict_of_words = {} for url in all_works_links: print("working on " + url[0:-11]) response = get("http://shakespeare.mit.edu/" + url[0:-10] + "full.html", headers=headers) html_parser = BeautifulSoup(response.text, 'html.parser') all_sentences = html_parser.findAll('blockquote') for sentence in all_sentences: list_of_words = sentence.text.split() for word in list_of_words: if word in dict_of_words.keys(): dict_of_words[word] = dict_of_words[word] + 1 else: dict_of_words[word] = 1 most_common = nlargest(75, dict_of_words, key=dict_of_words.get) dict_of_most_common = {} for word in most_common: dict_of_most_common[word] = dict_of_words.get(word) plt.bar(list(dict_of_most_common.keys()), dict_of_most_common.values(), color='g') plt.xticks(rotation=45, horizontalalignment='right', fontweight='light') plt.show() else: dict_of_count = {} for url in all_works_links: current_work = url[0:-11] print("working on " + current_work) dict_of_count[current_work] = 0 response = get("http://shakespeare.mit.edu/" + url[0:-10] + "full.html", headers=headers) html_parser = BeautifulSoup(response.text, 'html.parser') all_sentences = html_parser.findAll('blockquote') for sentence in all_sentences: list_of_words = sentence.text.split() for word in list_of_words: if word == search_word: dict_of_count[current_work] = dict_of_count[current_work] + 1 plt.bar(list(dict_of_count.keys()), dict_of_count.values(), color='g') plt.xticks(rotation=45, horizontalalignment='right', fontweight='light') plt.show()
ba41ef426a5439807aad825f9365774652974925
dvoiss/programming-puzzles
/programming-praxis/sum-of-four.py
649
3.734375
4
import itertools as it test = [2, 3, 1, 0, -4, -1] value = 0 # numbers in test can be used more than once: # [0, 0, 0, 0] = 0 or [1, 1, -1, -1] = 0 print [i for i in it.combinations_with_replacement(test, 4) if sum(i) == value] # no numbers in the test array can be used more than once, # ex: full result set of test = [2, 3, 1, 0, -4, -1] and value = 0: # [(2, 3, -4, -1), (3, 1, 0, -4)] print [i for i in it.combinations(test, 4) if sum(i) == value] # returns all permutations of elements where the sum is equal to the value # ex: (1, 1, -1, -1), (-1, 1, 1, -1), (-1, 1, -1, 1) print [i for i in it.product(test, repeat=4) if sum(i) == value]
d4d2f5b787b90e78b75e24e9a684b585178758f8
Hermotimos/Learning
/algorithms/8.SORT ALGORITHMS.py
13,676
4.5625
5
""" This file is for learning and exercise purposes. Topics: - algorithms: recursion, monkey sort, bubble sort, selection sort, merge sort Sources: https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/ Aditya Bhargava - Algorytmy. Ilustrowany przewodnik. """ import random from time_function_decorator import time_function # CODE TO CHECK IF LIST IS SORTED def is_sorted(list_): return all(list_[n - 1] <= list_[n] for n in range(1, len(list_))) tuple1 = 1, 2, 3, 4 list1 = [1, 2, 3, 4, 4] tuple2 = 1, 2, 3, 4, 3 list2 = [1, 2, 3, 4, 3, 4, 3] print('Test is_sorted(): True, True, False, False') print(is_sorted(tuple1)) print(is_sorted(list1)) print(is_sorted(tuple2)) print(is_sorted(list2)) print() # ---------------------------------------------------------------------------------------------------- # >>>>>>>>>>>>>>>>>>>>>>>>>>> MONKEY SORT / BOGO SORT / SHOTGUN SORT <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # ---------------------------------------------------------------------------------------------------- print('MONKEY SORT / BOGO SORT / SHOTGUN SORT') # PURE ALGORITHM def bogo_sort(list_): while not all(list_[n - 1] <= list_[n] for n in range(1, len(list_))): random.shuffle(list_) return list_ # VERSION WITH PRINTOUT AND COUNTER def bogo_sort2(list_, shuffle_counter=0): print(f'Start: {list_}') while not all(list_[n - 1] <= list_[n] for n in range(1, len(list_))): random.shuffle(list_) shuffle_counter += 1 print(f'Steps needed: {shuffle_counter}: {list_}') list1 = [1, 2, 3, 1, 4, 3, 4, 3, 1] list2 = [(2, 'two'), (3, 'three'), (0, 'zero'), (4, 'four'), (1, 'one')] list3 = [17, 2, 73, 1, 34, 3, 54, 43, 11, 1, 2, 3, 1, 4, 3, 4, 3, 1, 17, 2, 73, 1, 34, 3, 54, 43, 11, 1, 2, 3, 1, 4, 3] print('\nlist1'), bogo_sort2(list1) print('\nlist2'), bogo_sort2(list2) # print('\nlist3'), bogo_sort2(list3) # Woooops... this probably takes hours. print() # This algorithm will eventually sort short lists. # 10 trials for a 7-element list: 327, 325, 235, 204, 169, 421, 401, 593, 3, 391 ===> seen range 3 - 2400 !!! # Order of growth O is unbounded. # ---------------------------------------------------------------------------------------------------- # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> BUBBLE SORT <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # ---------------------------------------------------------------------------------------------------- print('BUBBLE SORT') print() def bubble_mit(list_): swap = False while not swap: swap = True for j in range(1, len(list_)): if list_[j - 1] > list_[j]: swap = False temp = list_[j] list_[j] = list_[j - 1] list_[j - 1] = temp return list_ list1 = [1, 2, 3, 1, 4, 3, 4, 3, 1] print(f'MIT algorithm test for {list1}:') print(bubble_mit(list1)) print() # COMMENT # The 'swap' flag in this MIT lecture algorithm is counter-intuitive: makes 'swap = False' right before a swap is done. # Also it doesn't make use of multiple assignment. And it's long... So it needs simplification: def bubble_sort_short(list_): while True: swap = False for e in range(1, len(list_)): if list_[e - 1] > list_[e]: list_[e - 1], list_[e] = list_[e], list_[e - 1] swap = True if not swap: return list_ list1 = [1, 2, 3, 1, 4, 3, 4, 3, 1] print(f'Shorter algorithm test for list {list1}:') print(bubble_sort_short(list1)) print() def bubble_sort_shortest(list_): while not all(list_[n - 1] <= list_[n] for n in range(1, len(list_))): for e in range(1, len(list_)): if list_[e - 1] > list_[e]: list_[e - 1], list_[e] = list_[e], list_[e - 1] return list_ list1 = [1, 2, 3, 1, 4, 3, 4, 3, 1] print(f'Shortest algorithm test for list {list1}:') print(bubble_sort_shortest(list1)) print() # VERSION WITH PRINTOUT AND COUNTER def bubble_sort2(list_, printout=True): print(f'Start: {list_}') if printout else None step_count = 0 while True: swap = False for e in range(1, len(list_)): if list_[e - 1] > list_[e]: list_[e - 1], list_[e] = list_[e], list_[e - 1] swap = True step_count += 1 print(f'Step {step_count}: {list_}') if printout else None if not swap: return list_ if printout else print(f'Steps: {step_count}: {list_}.') list1 = [1, 2, 3, 1, 4, 3, 4, 3, 1] list2 = [(2, 'two'), (3, 'three'), (0, 'zero'), (4, 'four'), (1, 'one')] list3 = [17, 2, 73, 1, 34, 3, 54, 43, 11, 1, 2, 3, 1, 4, 3, 4, 3, 1, 17, 2, 73, 1, 34, 3, 54, 43, 11, 1, 2, 3, 1, 4, 3] print('\nlist1'), bubble_sort2(list1) print('\nlist2'), bubble_sort2(list2) print('\nlist3'), bubble_sort2(list3, False) print() # Order of growth O(n**2) because each iterative solution is O(len(list_) = O(n). # There are 2 iterative constructs (while and for), so O(n)*O(n) = O(n**2) # ---------------------------------------------------------------------------------------------------- # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SELECTION SORT <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # ---------------------------------------------------------------------------------------------------- print('SELECTION SORT') # PURE ALGORITHM def selection_sort(list_): index = 0 while index < len(list_): for n in range(index, len(list_)): if list_[index] > list_[n]: list_[index], list_[n] = list_[n], list_[index] index += 1 return list_ # From Aditya Bhargava - Algorytmy. Ilustrowany przewodnik. def selection_sort2(unordered_list): def find_smallest(list_): smallest = list_[0] smallest_index = 0 for e in range(1, len(list_)): if list_[e] < smallest: smallest = list_[e] smallest_index = e return smallest_index ordered_list = [] for _ in range(len(unordered_list)): smallest_ = find_smallest(unordered_list) ordered_list.append(unordered_list.pop(smallest_)) return ordered_list # WITH PRINTOUT def selection2(list_): suffix = 0 while suffix != len(list_): print(f'Step {suffix}: {list_}') for n in range(suffix, len(list_)): if list_[suffix] > list_[n]: list_[suffix], list_[n] = list_[n], list_[suffix] suffix += 1 return list_ list1 = [1, 2, 3, 1, 4, 3, 4, 3, 1] list2 = [(2, 'two'), (3, 'three'), (0, 'zero'), (4, 'four'), (1, 'one')] list3 = [17, 2, 73, 1, 34, 3, 54, 43, 11, 1, 2, 3, 1, 4, 3, 4, 3, 1, 17, 2, 73, 1, 34, 3, 54, 43, 11, 1, 2, 3, 1, 4, 3] print('\nlist1'), print(selection2(list1)) print('\nlist2'), print(selection2(list2)) print('\nlist3'), print(selection2(list3)) print() # ---------------------------------------------------------------------------------------------------- # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> MERGE SORT <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # ---------------------------------------------------------------------------------------------------- print('MERGE SORT') def merge_sort(list_): def merge(left, right): result = [] a, b = 0, 0 while a < len(left) and b < len(right): if left[a] < right[b]: result.append(left[a]) a += 1 else: result.append(right[b]) b += 1 while a < len(left): result.append(left[a]) a += 1 while b < len(right): result.append(right[b]) b += 1 return result if len(list_) < 2: return list_[:] else: middle = len(list_) // 2 half1 = merge_sort(list_[:middle]) half2 = merge_sort(list_[middle:]) return merge(half1, half2) list1 = [1, 2, 3, 1, 4, 3, 4, 3, 1] list2 = [(2, 'two'), (3, 'three'), (0, 'zero'), (4, 'four'), (1, 'one')] list3 = [17, 2, 73, 1, 34, 3, 54, 43, 11, 1, 2, 3, 1, 4, 3, 4, 3, 1, 17, 2, 73, 1, 34, 3, 54, 43, 11, 1, 2, 3, 1, 4, 3] print('\nlist1'), print(merge_sort(list1)) print('\nlist2'), print(merge_sort(list2)) print('\nlist3'), print(merge_sort(list3)) # WITH PRINTOUT # Steps counting has no meaning by recursion - I'm putting it here to see why def merge_sort2(list_): global counter counter += 1 def merge(left, right): print(f'Step {counter}:\n\t\tleft: {left}\n\t\tright: {right}') result = [] a, b = 0, 0 while a < len(left) and b < len(right): if left[a] < right[b]: result.append(left[a]) a += 1 else: result.append(right[b]) b += 1 while a < len(left): result.append(left[a]) a += 1 while b < len(right): result.append(right[b]) b += 1 return result if len(list_) < 2: return list_[:] else: middle = len(list_) // 2 half1 = merge_sort2(list_[:middle]) half2 = merge_sort2(list_[middle:]) return merge(half1, half2) list1 = [1, 2, 3, 1, 4, 3, 4, 3, 1] list2 = [(2, 'two'), (3, 'three'), (0, 'zero'), (4, 'four'), (1, 'one')] list3 = [17, 2, 73, 1, 34, 3, 54, 43, 11, 1, 2, 3, 1, 4, 3, 4, 3, 1, 17, 2, 73, 1, 34, 3, 54, 43, 11, 1, 2, 3, 1, 4, 3] counter = 0 print('\nlist1'), print(merge_sort2(list1)) counter = 0 print('\nlist2'), print(merge_sort2(list2)) counter = 0 print('\nlist3'), print(merge_sort2(list3)) print() # ---------------------------------------------------------------------------------------------------- # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> QUICK SORT <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # ---------------------------------------------------------------------------------------------------- print('QUICK SORT') def quick_sort(list_): if len(list_) < 2: return list_ else: pivot = list_[0] less = [i for i in list_[1:] if i < pivot] greater = [i for i in list_[1:] if i > pivot] return quick_sort(less) + [pivot] + quick_sort(greater) list1 = [1, 2, 3, 1, 4, 3, 4, 3, 1] list2 = [(2, 'two'), (3, 'three'), (0, 'zero'), (4, 'four'), (1, 'one')] list3 = [17, 2, 73, 1, 34, 3, 54, 43, 11, 1, 2, 3, 1, 4, 3, 4, 3, 1, 17, 2, 73, 1, 34, 3, 54, 43, 11, 1, 2, 3, 1, 4, 3] print('\nlist1'), print(quick_sort(list1)) print('\nlist2'), print(quick_sort(list2)) print('\nlist3'), print(quick_sort(list3)) print() # ---------------------------------------------------------------------------------------------------- # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PERFORMANCE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # ---------------------------------------------------------------------------------------------------- print('--------------- PERGORMANCE ---------------') algorithms = [bubble_mit, bubble_sort_short, bubble_sort_shortest, selection_sort, merge_sort, quick_sort] for alg in algorithms: list1 = [17, 2, 73, 1, 34, 3, 54, 17, 2, 73] # len 10 list2 = list1 + list1 + list1 + list1 + list1 + list1 + list1 + list1 + list1 + list1 # len 100 list3 = list2 + list2 + list2 + list2 + list2 + list2 + list2 + list2 + list2 + list2 # len 1000 list4 = list3 + list3 + list3 + list3 + list3 + list3 + list3 + list3 + list3 + list3 # len 10000 # list5 = list4 + list4 + list4 + list4 + list4 + list4 + list4 + list4 + list4 + list4 # len 100000 lists = [list1, list2, list3, list4] print() for i, listx in enumerate(lists): print(f'list length: {len(listx)}') time_function(alg, print_args=False)(listx) """ CONCLUSION: 1) Hierarchy of algorithms as per performance: 1.quick; 2.merge; 3.selection; 4.bubble 2) bubble sort algorithms: all three versions perform almost the same 3) monkey sort of course is completely inefficient. Exemplary performance times: --------------------------------- list length: 10 Time for bubble_mit(): 0.0000170650 secs list length: 100 Time for bubble_mit(): 0.0013789030 secs list length: 1000 Time for bubble_mit(): 0.1603156460 secs list length: 10000 Time for bubble_mit(): 16.5113194890 secs list length: 10 Time for bubble_sort_short(): 0.0000162130 secs list length: 100 Time for bubble_sort_short(): 0.0018666960 secs list length: 1000 Time for bubble_sort_short(): 0.1574986800 secs list length: 10000 Time for bubble_sort_short(): 16.7325608480 secs list length: 10 Time for bubble_sort_shortest(): 0.0000298650 secs list length: 100 Time for bubble_sort_shortest(): 0.0016368780 secs list length: 1000 Time for bubble_sort_shortest(): 0.2606456100 secs list length: 10000 Time for bubble_sort_shortest(): 16.9746885460 secs list length: 10 Time for selection_sort(): 0.0000153590 secs list length: 100 Time for selection_sort(): 0.0005668640 secs list length: 1000 Time for selection_sort(): 0.0582939100 secs list length: 10000 Time for selection_sort(): 5.8116967250 secs list length: 10 Time for merge_sort(): 0.0000298650 secs list length: 100 Time for merge_sort(): 0.0003760130 secs list length: 1000 Time for merge_sort(): 0.0049737770 secs list length: 10000 Time for merge_sort(): 0.0632207570 secs list length: 10 Time for quick_sort(): 0.0000108080 secs list length: 100 Time for quick_sort(): 0.0000301490 secs list length: 1000 Time for quick_sort(): 0.0001877220 secs list length: 10000 Time for quick_sort(): 0.0016840930 secs """
31dfe1bf9c36c12a9477bec393bcfa3f1af759c3
ojhak02/python2
/disjoint.py
1,198
3.75
4
x={"apple","banana","cherry"} y={"google","microsoft","facebook"} z=x.isdisjoint(y) print(z) x={"a","b","c"} y={"f","e","d","c","b","a"} z=x.issubset(y) print(z) x={"apple","banana","cherry"} y={"google","microsoft","facebook"} x.intersection_update(y) print(x) x={"a","b","c"} z=x.issuperset(y) print(z) x={"Apple","banana","cherry"} y={"google","microsoft","apple"} z=x.symmetric_difference(y) print(z) x={"apple ","banana","cherry"} y={"google","microsoft","apple"} z=x.union(y) print(z) a=[] b={} c=() print(type(a)) print(type(b)) print(type(c)) college={ "name":"lamaboy", "dept":"IT", "age":"18" } print("student name is " +college["name"]) print("dept name is"+college["dept"]) print(college.keys()) print(college.values()) for x in college: print(x+"->"+college[x]) college["gender"]="male" print(college) if "age" in college: print("yes, age is a key of college") college.pop("age") print(college) x=("123","abc","xyz") y=0 college=dict.fromkeys(x,y) print(college) x=5 if x%2==0: print("even") else: print("odd")
6c7d31368081e5e1989a5ea1e608eb946d698591
lucianovictor/python-estudo
/pythonexercicios/ex006.py
142
3.921875
4
n1= int(input('Digite um numero:')) n2= int(input('Digite um numero:')) s = n1 + n2 print('A soma de {} e {} é igual {}!'.format(n1, n2, s))
9ec579927f47973ddde5b3b3dac3fdfc8004626c
Kumarved123/Basic-Data-Structure-Algorithm
/Dynamic Programming/Longest_Bitonic_Subsequence.py
972
3.828125
4
#Longest Bitonic Subsequence '''Given an array arr[0 … n-1] containing n positive integers, a subsequence of arr[] is called Bitonic if it is first increasing, then decreasing. Write a function that takes an array as argument and returns the length of the longest bitonic subsequence. A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. Similarly, decreasing order sequence is considered Bitonic with the increasing part as empty.''' def bitonic(arr): n = len(arr) inc = [1]*n dec = [1]*n for i in range(1,n): for j in range(0,i): if arr[i]> arr[j] and inc[j] +1 > inc[i]: inc[i] = inc[j]+1 for i in range(n-2, -1, -1): for j in range(n-1, i, -1): if arr[i]> arr[j] and dec[i] +1 > dec[j]: dec[i] = dec[j]+1 res = [] for i in range(n): res.append(inc[i]+dec[i]) print(max(res)-1) bitonic([12, 11, 40, 5, 3, 1])
3fa46146099c29aad9a17748a199b6bbe204b7f0
hanchang7388/PythonExercises
/test/test_re.py
315
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import re def match(a): pattern = re.compile(r'(\w+)@(\w+).(\w+)') m=re.match(pattern,a) if re.match(pattern,a): print "yes" else: print "fail" # a=raw_input("enter email: ") a="123@qq.com" print a match(a) # print 'a b cd'.split(' ')
2772971267cc3e1209c5b576e5f2b86933c5c41d
lunar0926/python-for-coding-test
/binary_search/binary_p1-1.py
1,103
3.703125
4
''' 입력 예시 5 8 3 7 9 2 3 5 7 9 ''' # 내가 적은 코드로 문제를 맞추긴 했지만 교재에 있는 예시대로 이진 탐색, 계수 정렬, 집합 자료형을 이용해서 해결해보기. # 이진 탐색 활용(재귀함수) # 함수 정의 def check(array, start, end, target): # target에는 구매하려는 제품 종류를 변수로 넣어야 함. # target을 못 찾았을 때 if start > end: print("no", end=' ') # 중간값 mid = (start + end) // 2 if array[mid] == target: print("yes", end=' ') if array[mid] > target: return check(array, start, mid-1, target) elif array[mid] < target: return check(array, mid+1, end, target) # 입력 받기 n = int(input()) # 가게에 있는 부품 개수 stock_list = list(map(int, input().split())) stock_list.sort() # 이진 탐색을 하기 위해서 정렬해주어야 함. m = int(input()) # 손님이 구매하려는 부품 개수 buy_list = list(map(int, input().split())) # 구매하려는 부품 재고 확인하기 for i in buy_list: check(stock_list, 0, n-1, i)
82ae7f2888896719b1a1d0105534989f29316514
SonoDavid/python-ericsteegmans
/CH2_floating_point/realroots.py
760
4.21875
4
# Calculates the real roots of a quadratic equation # The equation is in the from a*x**2+b*x+c # The solution is x = (-b +- sqrt(discriminant)) # The discriminant is b**2 + 4*a*c from math import sqrt a = float(input("Give the value of a: ")) b = float(input("Give the value of b: ")) c = float(input("Give the value of c: ")) discr = b**2 - 4*a*c if a == 0: print("This is a linear equation") x = -c/b print("x:", x) elif discr < 0: print("The function does not have any real roots") elif discr > 0: print("The function has two roots") x1 = (-b + sqrt(discr)) / (2*a) x2 = (-b -sqrt(discr)) / (2*a) print("x1: ", x1, "\tx2: ", x2) else: print("The function has exactly one root") x = -b print("x:", x)
5b4abcd48177ce4df4b1961c2fd9c09611a70c31
rachit995/practice
/hackerrank/ctci-bubble-sort.py
529
3.84375
4
#!/bin/python3 import math import os import random import re import sys # Complete the countSwaps function below. def countSwaps(a): n = len(a) num_swaps = 0 for _ in range(n): for j in range(n-1): if a[j] > a[j+1]: num_swaps += 1 a[j], a[j+1] = a[j+1], a[j] print("Array is sorted in "+str(num_swaps)+" swaps.") print("First Element: "+str(a[0])) print("Last Element: "+str(a[n-1])) if __name__ == '__main__': a = [3, 2, 1] countSwaps(a)
4aabc4f894a412f527394bfd5baa4e318f5cfac6
teojcryan/rosalind
/code/fibo.py
178
3.765625
4
# Fibonacci Numbers """ Problem Given: A positive integer n≤25. Return: The value of Fn. """ def fibo(n): if n <= 1: return n else: return fibo(n-1) + fibo(n-2)
8c65de342e9e44951c77b6c2c935d99e024f514e
UncleBob2/MyPythonCookBook
/JSON urlopen read loads dict get.py
692
3.578125
4
import json from urllib.request import urlopen with urlopen('https://api.exchangeratesapi.io/latest') as response: source = response.read() data = json.loads(source) # print(json.dumps(data, indent=2)) usd_rates = dict() # create new dic from JSON for quicker access # for item in data['list']['resources']: # name = item['resources']['field']['name'] # price = item['resources']['field']['price'] # usd_rates[name] = price for item in data['rates']: # print(item, end=' ') # print(data['rates'].get(item)) usd_rates[item] = data['rates'].get(item) print('The rate of CAD vs EUR', usd_rates['CAD']) print('50 EUR in $CAD = ', 50 * float(usd_rates['CAD']))
90b69ffcadd562c183b5d0ee09e16c819dbbb8f3
grigor-stoyanov/PythonAdvanced
/workshop/tic_tac_toe/core/validators.py
963
3.625
4
from tic_tac_toe.core.helpers import get_row_col def is_position_in_range(position): if 1 <= position <= 9: return True return False def is_place_available(board, position): row, col = get_row_col(position) if board[row][col] == ' ': return True return False def is_winner(board, sign): for row in board: if row.count(sign) == 3: return True for col in range(len(board)): if len([board[row][col] for row in range(len(board)) if board[row][col] == sign]) == 3: return True if len([board[row][row] for row in range(len(board)) if board[row][row] == sign]) == 3: return True if len([board[row][len(board) - row - 1] for row in range(len(board)) if board[row][len(board) - row - 1] == sign]) == 3: return True return False def is_board_full(board): for row in board: if ' ' in row: return False return True
e41b028d8baf32b88767103e217d0c4416a2c92e
panthitesh6410/python-programs
/functional_programming.py
211
3.609375
4
# functional programming tells to do work using function : def add_ten(x): return x + 10 def twice(func, arg): # call any function twice return func(func(arg)) print(twice(add_ten, 10))
28b2fc46d177873fc6b56f4309570a6363725d9a
Juhee-Jeong-SW/ALGORITHM
/PROGRAMMERS/STACK:QUEUE/42583.py
1,206
3.640625
4
from collections import deque # idea : '다리'의 무게와 '다리'에 대한 리스트를 동시에 갱신시키며 값을 구한다. # 트럭이 '다리'에서 빠져나가는 부분(앞)과 트럭에서 빼내어 다리에 붙여주는 부분(뒤)가 구현되어야 함. -> deque 특성 def solution(bridge_length, weight, truck_weights): answer = 0 bridge = deque([0] * bridge_length) # 다리 크기만큼의 deque [0,0] truck_weights = deque(truck_weights) # 트럭 deque [7,4,5,6] bridge_weight = sum(bridge) # bridge deque 에 들어있는 총합 현재: 0 while bridge: bridge_weight -= bridge[0] # 가장 앞 쪽에 있는 트럭을 지워주기 위함 bridge.popleft() # 위와 동일 answer += 1 if truck_weights: if bridge_weight + truck_weights[0] <= weight: # 트럭이 다리에 올라올 수 있음. bridge_weight += truck_weights[0] # 앞에 있는 트럭을 브릿지 무게에 더해줌(올라오니까)) bridge.append(truck_weights.popleft()) # 위와 동일 else: bridge.append(0) # 무게 크면 그대로 대기 return answer
e45bd7eb869e74f499121aa2d6e5f02efc7da37f
TheJoeCollier/cpsc128
/code/python3/simple_plot_example.py
653
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 17 17:59:45 2019 @author: sbulut """ #example1 import matplotlib.pyplot as plt plt.plot([1,2,3,4], [1,4,9,16],label='data by hand') plt.ylabel('axis label with equation $y=x^2$') plt.xlabel('x') plt.legend() plt.show() #example 2 import numpy as np import matplotlib.pyplot as plt # search space (size of computational problem) N=np.arange(1,20,0.5) #generates list: 1. 1.5 2 2.5 ... plt.plot(N, N,label='linear search: $f(N)=N$') plt.plot(N, np.log2(N), label='bisection method: $f(N)=log_2N$') plt.ylabel('computation time') plt.xlabel('problem size: N') plt.legend() plt.show()
fc928c0fd0f53b4f44163b67fba387b4aab7c80e
Narendon123/python
/140p.py
96
4
4
t=input().split() if(t=='a' and t=='b' or t=='a' or t=='b'): print("yes") else: print("no")
f2477a62cc1ccf2a190c4ef55a28c17f968f5191
Zahidsqldba07/CodeFights-9
/Arcade/Intro/Level 12/digitsProduct/code.py
800
3.78125
4
from math import sqrt def factor(x): return sorted(reduce(list.__iadd__, [[n, x / n] for n in range(1, int(sqrt(x)) + 1) if not (x % n)])) def is_prime(x): return True if len(factor(x)) == 2 else False def digitsProduct(product): # This should be 0 to be consistent with 1, 2, 3, ..., 9. if product == 0: return 10 if product < 10: return product if is_prime(product): return -1 factors = factor(product) result = "" while product != 1: factors = filter(lambda x: x != 1 and x < 10, factors) if len(factors): f = factors[-1] result += str(f) product /= f factors = factor(product) else: return -1 return int("".join(sorted(result)))
1d018ae5e775b13618c66839101492effae0dddf
Ajinkyasarmalkar/Python-examples
/enter a number.py
212
4
4
while(True): inp = int(input(("enter a number: ")) if inp>100: print("congrats ypu have entered number greater than 100.") break else: print("Try again!") continue
3d5ff5e747548bdd6c8ead7f6f3e195aff197d90
bradyt/project-euler
/python/p005.py
578
3.78125
4
# Smallest multiple # Problem 5 # # 2520 is the smallest number that can be divided by each of the # numbers from 1 to 10 without any remainder. # # What is the smallest positive number that is evenly divisible by # all of the numbers from 1 to 20? import fractions def lcm(a, b): return a * b // fractions.gcd(a, b) def lcm_list(l): result = 1 for a in l: result = lcm(a, result) return result def p005(): return lcm_list(range(1, 20)) def solution(): return p005() def main(): print(solution()) if __name__ == '__main__': main()
97ee1f0148f653317d2672adf93671d1d6c89fb6
TeddyTeddy/Complete-Python-3-Bootcamp
/19-Managing Python Environments/sys-path-is-fixed/1-package-import-example/start.py
1,477
3.90625
4
""" Let’s recap the order in which Python searches for modules to import: 1) built-in modules from the Python Standard Library (e.g. sys, math) 2) modules or packages in a directory specified by sys.path: a) If the Python interpreter is run interactively, sys.path[0] is the empty string ''. This tells Python to search the current working directory from which you launched the interpreter, i.e., the output of pwd on Unix systems. b) If we run a script with python <script>.py, sys.path[0] is the path to <script>.py. 3) directories in the PYTHONPATH environment variable 4) default sys.path locations, including remaining Python Standard Library modules which are not built-in 5?) Virtual environment path """ print('Case 1: sys.path is fixed/known ahead of time') print('In this example, only start.py needs to be invoked via python -m start (The other modules are only imported but not invoked)') print('sys.path will always include the path to start.py in its search path') print('Therefore, all of the import statements can be written relative to the start.py s path') print('--------------------------------------') import sys print(f'start.py: with __name__: {__name__}') # __name__ is main print(f'start.py: with sys.path (shared across all imported modules): {sys.path}') print('--------------------------------------') import my_package # equivalent to import my_package.__init__ print(my_package.package_variable) my_package.package_function()
9226ca05867d9985f7db3c69666d34bd1fc155c8
rarezhang/data_structures_and_algorithms_in_python
/exercises/ch07_linked_lists/SinglyLinkedBaseRecursive.py
3,366
3.625
4
""" base class for singly linked list recursive version reference: UC Berkeley CS61A """ class _SinglyLinkedBaseRecursive: """ a base class for singly linked list recursive version """ empty = () def __init__(self, head, rest=empty): """ :param head: :param rest: """ assert rest is _SinglyLinkedBaseRecursive.empty or isinstance(rest, _SinglyLinkedBaseRecursive) self._head = head self._rest = rest def __getitem__(self, item): """ implicit recursive :param item: :return: """ if item == 0: return self._head else: return self._rest[item-1] # will invoke the same __getitem__ method def __len__(self): """ implicit recursive :return: """ return 1 + len(self._rest) # len(empty)=0 def is_empty(self): """ return True if the list is empty :return: """ return len(self) == 0 def __str__(self): """ :return: """ if self._rest: # rest is not empty rest_str = ' ' + str(self._rest) else: # rest is empty rest_str = '' return '{{ {0} {1}}}'.format(self._head, rest_str) def _extend(self, L, element): """ help method for extend() :param L: :param element: :return: """ if L is self.empty: return _SinglyLinkedBaseRecursive(element) else: return _SinglyLinkedBaseRecursive(L._head, self._extend(L._rest, element)) def extend(self, element): """ return link followed by new element :param element: new element :return: """ return self._extend(self, element) def _map_link(self, L, fun): """ helper function for map_link :return: """ if L is self.empty: return L else: return _SinglyLinkedBaseRecursive(fun(L._head), self._map_link(L._rest, fun)) def map_link(self, fun): """ apply fun to each element of list :param fun: :return: """ return self._map_link(self, fun) def _filter_link(self, L, fun): """ helper function for filter_link :param L: :param fun: :return: """ if L is self.empty: return L else: filtered = self._filter_link(L._rest, fun) if fun(L._head): return _SinglyLinkedBaseRecursive(L._head, filtered) else: return filtered def filter_link(self, fun): """ return a link with element of link for which fun return true :param fun: :return: """ return self._filter_link(self, fun) def _reverse(self, L): """ helper function of reverse :param L: :return: """ if L._rest is self.empty: return L else: return _SinglyLinkedBaseRecursive(self._reverse(L._rest), _SinglyLinkedBaseRecursive(L._head)) def reverse(self): """ recursive algorithm for reversing a singly linked list :return: """ return self._reverse(self)
91e4f4157c7c0cbfaca18fbbf1b528f9adf533f8
FabianTz/Study-Data
/Data Analysis/FunctionsPandas.py
1,060
3.5625
4
import tkinter as tk from tkinter import filedialog import numpy as np import math import pandas as pd def grab_data(): # file open dialog to select the file to work on root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() # by default expect a csv delim = "," # if a tsv is found, switch delimiter to a tab character if file_path[-4:] == ".tsv": delim = "\t" # warn the user that this is a tab sep file print("\n.tsv file detected, switching delimiter \n") # pull the data from the file data = pd.read_csv(file_path, delimiter=delim, header=0, index_col=False) # print(type(data)) # print the file name & location to the console print("Getting data from: ", file_path, "\n") # return the data array return data def segment_length(x1, y1, z1, x2, y2, z2): delta_x_squared = (x2 - x1)**2 delta_y_squared = (y2 - y1)**2 delta_z_squared = (z2 - z1)**2 l = math.sqrt((delta_x_squared + delta_y_squared + delta_z_squared)) return l
f721da4a62a9d6ee2a783efd17d7bc324a8275c7
charliedmiller/coding_challenges
/minimum_depth_of_binary_tree.py
1,601
4.03125
4
# Charlie Miller # Leetcode - 111. Minimum Depth of Binary Tree # https://leetcode.com/problems/minimum-depth-of-binary-tree/ """ recursivley find the min depth of left and right children. Keep track of min depth seen so we don't have to venture futher than necessary """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def min_depth(self,root,cur_depth,max_depth): #case: one child is null, so we return inf if not root: return float("inf") #optimization:stop if we've gone deeper than some other child if cur_depth > max_depth: return max_depth #we found a leaf. Return its depth #(we already know its shorter than what we've seen before) if not root.left and not root.right: return cur_depth left_depth = self.min_depth(root.left,cur_depth+1,max_depth) #left child can be shorter than what we've seen before. update it like so max_depth = min(left_depth,max_depth) right_depth = self.min_depth(root.right,cur_depth+1,max_depth) #right child could be shorter, give the shorter of max_depth, left child, and right child return min(right_depth,max_depth) def minDepth(self, root: TreeNode) -> int: if not root: return 0 return self.min_depth(root,1,float("inf"))
7da1237855a4951f6cf2c5f9f43e1fc108d32d22
plawanrath/Leetcode_Python
/MulyiplyStrings.py
2,733
4.125
4
""" Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Input: num1 = "2", num2 = "3" Output: "6" """ from typing import List from itertools import zip_longest def multiply(num1: str, num2: str) -> str: if num1 == "0" or num2 == "0": return "0" # Reverse both numbers. first_number = num1[::-1] second_number = num2[::-1] # For each digit in second_number, multipy the digit by first_number and then # store the multiplication result (reversed) in the results array. results = [] for index, digit in enumerate(second_number): results.append(multiply_one_digit(digit, index, first_number)) # Add all of the results together to get our final answer (in reverse order) answer = sum_results(results) # Reverse answer and join the digits to get the final answer. return ''.join(str(digit) for digit in reversed(answer)) def multiply_one_digit(digit2: str, num_zeros: int, first_number: List[str]) -> List[int]: """Multiplies first_number by a digit from second_number (digit2).""" # Insert zeros at the beginning of the current result based on the current digit's place. current_result = [0] * num_zeros carry = 0 # Multiply each digit in first_number with the current digit of the second_number. for digit1 in first_number: multiplication = int(digit1) * int(digit2) + carry # Set carry equal to the tens place digit of multiplication. carry = multiplication // 10 # Append last digit to the current result. current_result.append(multiplication % 10) if carry != 0: current_result.append(carry) return current_result def sum_results(results: List[List[int]]) -> List[int]: # Initialize answer as a number from results. answer = results.pop() # Add each result to answer one at a time. for result in results: new_answer = [] carry = 0 # Sum each digit from answer and result. Note: zip_longest is the # same as zip, except that it pads the shorter list with fillvalue. for digit1, digit2 in zip_longest(result, answer, fillvalue=0): # Add current digit from both numbers. curr_sum = digit1 + digit2 + carry # Set carry equal to the tens place digit of curr_sum. carry = curr_sum // 10 # Append the ones place digit of curr_sum to the new answer. new_answer.append(curr_sum % 10) if carry != 0: new_answer.append(carry) # Update answer to new_answer which equals answer + result answer = new_answer return answer
088be36a6a6c205d444a4b495ca6f4eddc880ade
chan2ie/2018_datastructure_exercises
/exercise_week4/gen_maze.py
809
3.640625
4
from __future__ import print_function from random import shuffle, randrange def make_maze(w = 42, h = 43): print( h*2 +1, w*2 + 1) vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)] ver = [["10"] * w + ['1'] for _ in range(h)] + [[]] hor = [['0'] + ["11"] * w for _ in range(1)] hor += [["11"] * w + ['1'] for _ in range(h-1)] hor += [["11"] * w + ['0'] for _ in range(1)] def walk(x, y): vis[y][x] = 1 d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)] shuffle(d) for (xx, yy) in d: if vis[yy][xx]: continue if xx == x: hor[max(y, yy)][x] = "10" if yy == y: ver[y][max(x, xx)] = "00" walk(xx, yy) walk(randrange(w), randrange(h)) s = "" for (a, b) in zip(hor, ver): s += ''.join(a + ['\n'] + b + ['\n']) return s if __name__ == '__main__': print(make_maze())
04fb95505b09128ea51da08c6bb6ccf9a6e329ad
RLNetworkSecurity/Python_learning
/time_table.py
330
4.125
4
#while loop example table_number = int(input("Input yoru times table: ")) number_rows = int(input("Input row_number: ")) #display heading print(f"{table_number} times table") print("-"*60) #for loop examples for row in range(number_rows+1): answer = table_number * row print(f"{row:3} * {table_number} = {answer:4}")
6c7c60c05f45220175e7f5e4df26532401d32cd1
meda-kiran/DS
/graph/dfsIterative.py
1,721
3.703125
4
from collections import defaultdict import collections class Graph: def __init__(self): self.graph=defaultdict(list) def addEdge(self,src,dest): self.graph[src].append(dest) print self.graph def DFS(self,v): visited=[False]*(len(self.graph)) q=collections.deque() self.prev={} q.append(v) visited[v]=True self.prev[v]=0 while q: node=q.pop() print "popped node:%s" %node for tmpNode in self.graph[node]: if not visited[tmpNode]: self.prev[tmpNode]=node q.append(tmpNode) visited[tmpNode]=True def path(self,a,b): if not self.prev: print "Prev dict is not set" return else: path=[] path.append(b) next=b while(next!=a): next=self.prev[next] path.append(next) print path def BFS(self,v): visited=[False]*(len(self.graph)) q=collections.deque() q.append(v) visited[v]=True while q: node=q.popleft() print "popped node:%s" %node for tmpNode in self.graph[node]: if not visited[tmpNode]: q.append(tmpNode) visited[tmpNode]=True g=Graph() g.addEdge(0,1) g.addEdge(0,2) g.addEdge(1,0) g.addEdge(2,0) g.addEdge(1,3) g.addEdge(2,3) g.addEdge(3,1) g.addEdge(3,2) g.addEdge(3,4) g.addEdge(3,5) g.addEdge(4,3) g.addEdge(5,3) g.addEdge(4,6) g.addEdge(5,6) g.addEdge(6,4) g.addEdge(6,5) g.DFS(0) g.path(2,6) g2 = Graph() g2.addEdge(0, 1) g2.addEdge(0, 2) g2.addEdge(1, 2) g2.addEdge(2, 0) g2.addEdge(2, 3) g2.addEdge(3, 3) g2.DFS(0)
f7cbc93a59297a303cff722230e5a59ec2aa79f9
NewMike89/Python_Stuff
/Ch.1 & 2/flo_math.py
179
3.609375
4
# Michael Schorr # 2/19/19 # Program of basic math operations on floats(decimal) numbers. print(0.1 + 0.1) print(0.2 - 0.2) print(2 * 0.2) print(0.2 / 2) print(0.2 + 0.1) print(3 * 0.1)
c40886ce475522978854c1cfce8baccc4c042c97
sadatusa/PCC
/6_4.py
750
4.53125
5
# 6-4. Glossary 2: Now that you know how to loop through a dictionary, clean # up the code from Exercise 6-3 (page 102) by replacing your series of print # statements with a loop that runs through the dictionary’s keys and values. # When you’re sure that your loop works, add five more Python terms to your # glossary. When you run your program again, these new words and meanings # should automatically be included in the output. python_glossary={'list':'collection of items in a particular order','tuple':'immutable list is called a tuple','if':'examine the\ current state of a program','variable':'use to store values','string':'series of characters'} for py_words,meaning in python_glossary.items(): print(py_words.title()+' : '+meaning)
7f807624844f3912c905728155194b2d91f9ee6a
petitviolet/python_challenge
/ex2.py
531
3.515625
4
# -*- encoding:utf-8 -*- from itertools import permutations def count(text): words = {} for t in text: words.setdefault(t, 0) words[t] += 1 return words def main(): lines = file('text_2.txt').read() words = count(lines) ans = [] for k, v in words.items(): if v == 1: ans.append(k) for p in permutations(ans): # print ''.join(p) if ''.join(p) == 'equality': print 'answer is "', ''.join(p), '"' if __name__ == '__main__': main()
e4fca1702eb1f12c3bcf96ca21a5b1800e4898a6
joashcabanilla/DICT-python-training
/day3/day3prac2.py
493
4.03125
4
answer = "Y" while answer.upper() == "Y": num1 = int(input("Enter First Number: ")) num2 = int(input("Enter Second Number: ")) if (num1 + num2) % 2 == 0: print("The sum of two integers is Even") else: print("The sum of two integers is Odd") print("______________________________________________________________") answer = str(input("Try Again? Input [Y/y] if Yes and [N/n] if No: ")) print() if answer.upper() == "N": print("Thank You!")
13fdad4ac41f8e5b5b18cd8ee24d996c13d22cef
rpycgo/tf-pdf
/union_find.py
965
3.609375
4
# -*- coding: utf-8 -*- class Union_Find: __slots__ = ['data', 'size'] def __init__(self, n): self.data = [-1 for _ in range(n)] self.size = n def upward(self, change_list, index): value = self.data[index] if value < 0: return index change_list.append(index) return self.upward(change_list, value) def find(self, index): change_list = [] result = self.upward(change_list, index) for i in change_list: self.data[i] = result return result def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.data[x] < self.data[y]: self.data[y] = x elif self.data[x] > self.data[y]: self.data[x] = y else: self.data[x] -= 1 self.data[y] = x self.size -= 1
f4682acabc6a3895c4c98ab30e3c3759d00d6518
thefr33radical/codeblue
/concepts/function_tracer.py
293
4.125
4
'''' function to trace the recursion stack : factorial of a number ''' def func(n): print(n) if(n==0 or n==1): return 1 if(n==2): return 2 else: x=(n* func(n-1)) print(x) return x if __name__=="__main__": y=func(5) print(y)
9b8149938e5d0074a0f5d653f057d51a422cdba4
FerniPicart/Lista.py
/Lista.py
62,681
3.578125
4
from tda_lista_lista import nodoLista , Lista, insertar, eliminar, busqueda_lista, busqueda_lista_vec, barrido_sublista, barrido_lista, tamanio, lista_vacia, criterio from random import randint, choice from datetime import date from time import sleep lista = Lista() def lista_numerica(lista): while tamanio(lista) < 10: dato = randint(0,10) insertar(lista, dato) print(dato) print('tamaño de lista comun: ' + str(tamanio(lista))) def lista_letras(lista): while tamanio(lista) < 10: dato = chr(randint(65,122)) insertar(lista,dato) print('letra: ' + dato) print('tamaño de lista comun: ' + str(tamanio(lista))) # 1. Diseñar un algoritmo que permita contar la cantidad de nodos de una lista. ''' print(lista_numerica(lista)) def contar_nodos(lista): cont = 0 aux = None for i in range(tamanio(lista)): cont += 1 if aux == None: aux = lista.inicio else: aux = aux.sig print('nodos contados') return cont print(contar_nodos(lista)) ''' #2. Diseñar un algoritmo que elimine todas las vocales que se encuentren en una lista de caracteres. ''' print(lista_letras(lista)) def eliminar_vocales(lista): vocales = 'aAeEiIoOuU' aux = None for i in range(tamanio(lista)): if aux == None: aux = lista.inicio else: aux = aux.sig if aux.info in vocales: eliminar(lista,aux.info) print('se elimino la letra: ' + aux.info) print('lista sin vocales: ') print(barrido(lista)) print(eliminar_vocales(lista)) ''' #3. Dada una lista de números enteros, implementar un algoritmo para dividir dicha lista en # dos, una que contenga los números pares y otra para los números impares. ''' print(lista_numerica(lista)) def lista_par_impar(lista): lista_par = Lista() lista_impar = Lista() aux = None for i in range(tamanio(lista)): if aux == None: aux = lista.inicio else: aux = aux.sig if (aux.info % 2 == 0): insertar(lista_par, aux.info) else: insertar(lista_impar, aux.info) print('lista de pares, tamanio: ' + str(tamanio(lista_par))) barrido(lista_par) print('lista impares, tamanio: '+ str(tamanio(lista_impar))) barrido(lista_impar) print(lista_par_impar(lista)) ''' #4. Implementar un algoritmo que inserte un nodo en la i-ésima posición de una lista. ''' print(lista_letras(lista)) def insertar_iesimo(lista,pos,elemento): nodo = nodoLista() nodo.info = elemento aux = lista.inicio tam = lista.tamanio while tam == lista.tamanio: if pos >= 0 and pos <= lista.tamanio: for i in range(1, pos): aux = aux.sig nodo.sig = aux.sig aux.sig = nodo print('- Se ha agregado el elemento en la posicion ' + str(pos)) else: print('Elemento será agregado al final de la lista') pos = lista.tamanio for i in range(1, pos): aux = aux.sig nodo.sig = aux.sig aux.sig = nodo barrido_lista(lista) pos = int(input('ingrese una posicion en la cual agregar el elemento: ')) print(insertar_iesimo(lista,pos,'objeto')) ''' #5. Dada una lista de números enteros eliminar de estas los números primos. ''' print(lista_numerica(lista)) def eliminar_primos(lista): aux = None for i in range(tamanio(lista)): div = 0 if aux == None: aux = lista.inicio else: aux = aux.sig for j in range (0,aux.info): j += 1 if (aux.info % j == 0): div += 1 if div > 2: break if div <= 2: print('elemento primo eliminado: ' + str(aux.info)) eliminar(lista, aux.info) print('lista SIN primos: ') barrido(lista) print(eliminar_primos(lista)) ''' #6. Dada una lista de superhéroes de comics, de los cuales se conoce su nombre, año aparición, casa de comic a la que # pertenece (Marvel o DC) y biografía, implementar la funciones necesarias para poder realizar las siguientes actividades: #a. eliminar el nodo que contiene la información de Linterna Verde; #b. mostrar el año de aparición de Wolverine; #c. cambiar la casa de Dr. Strange a Marvel; #d. mostrar el nombre de aquellos superhéroes que en su biografía menciona la palabra “traje” o “armadura”; #e. mostrar el nombre y la casa de los superhéroes cuya fecha de aparición sea anterior a 1963; #f. mostrar la casa a la que pertenece Capitana Marvel y Mujer Maravilla; #g. mostrar toda la información de Flash y Star-Lord; #h. listar los superhéroes que cominezan con la letra B, M y S; #i. determinar cuántos superhéroes hay de cada casa de comic. ''' superheroes = ['Linterna Verde','Wolverine','Dr Strange','Capitana Marvel','Mujer Maravilla','Flash','Star-Lord','Iron Man','Thanos','Batman','Dr Doom','Ghost Rider'] comic = ['Marvel', 'DC'] biografia = ['traje','armadura','Otras palabras','mas palabras'] for i in range (10): dato = ['','','',0] dato[0] = choice(superheroes) dato[1] = choice(comic) dato[2] = choice(biografia) dato[3] = randint(1920,2020) insertar(lista,dato) print(dato) def super_heroes(lista): print(' ') aux = None for i in range(tamanio(lista)): if aux == None: aux = lista.inicio else: aux = aux.sig if aux.info[0] == 'Linterna Verde': eliminar(lista, aux.info) print('Se ha eliminado a Linterna Verde') if aux.info[0] == 'Wolverine': print('Wolverine: Su año de aparicion fue en--> ' + str(aux.info[3])) if aux.info[0] == 'Dr Strange': if aux.info[1] != 'Marvel': aux.info[1] = 'Marvel' print('... Se ha cambiado la casa de "Dr Strange" a "Marvel" ...') print(aux) print(' ') print('personajes con la palabra traje o armadura en su biografia:') aux = None for i in range(tamanio(lista)): if aux == None: aux = lista.inicio else: aux = aux.sig if (aux.info[2] == 'traje') or (aux.info[2] == 'armadura'): print(aux.info[0] + ' - ' + aux.info[2]) print(' ') print('Nombre y Casa de los superhéroes cuya fecha de aparición es anterior a 1963:') aux = None for i in range(tamanio(lista)): if aux == None: aux = lista.inicio else: aux = aux.sig if (aux.info[3] < 1963): print(' - ' + aux.info[0] + ' - ' + aux.info[1] + ' - ' + str(aux.info[3])) print(' ') print('Casa a la que pertenece Capitana Marvel y Mujer Maravilla:') aux = None for i in range(tamanio(lista)): if aux == None: aux = lista.inicio else: aux = aux.sig if (aux.info[0] == 'Capitana Marvel') or (aux.info[0] == 'Mujer Maravilla'): print(aux.info[0] + ' - ' + aux.info[1]) print(' ') print('Informacion completa de Flash y Star-Lord:') aux = None cont_Marvel = 0 cont_Dc = 0 for i in range(tamanio(lista)): if aux == None: aux = lista.inicio else: aux = aux.sig if (aux.info[0] == 'Flash') or (aux.info[0] == 'Star-Lord'): print(aux.info[0] + ' ||| ' + aux.info[1] + ' - ' + aux.info[2] + ' - ' + str(aux.info[3])) if (aux.info[1] == 'Marvel'): cont_Marvel += 1 else: cont_Dc += 1 print(' ') print('La casa Marvel tiene ' + str(cont_Marvel) + ' Superheroes') print('La casa DC tiene ' + str(cont_Dc) + ' Superheroes') print(super_heroes(lista)) ''' #7. Implementar los algoritmos necesarios para resolver las siguientes tareas: #a. concatenar dos listas, una atrás de la otra; #b. concatenar dos listas en una sola omitiendo los datos repetidos y manteniendo su orden; #c. contar cuántos elementos repetidos hay entre dos listas, es decir la intersección de ambas; #d. eliminar todos los nodos de una lista de a uno a la vez mostrando su contenido. ''' lista_aux = Lista() lista_conc = Lista() #A def lista_concatenada(lista,lista_aux): print('Lista 1') barrido_lista(lista) print('Lista 2') barrido_lista(lista_aux) aux = lista_aux.inicio for i in range(0,tamanio(lista_aux)): insertar(lista,aux.info) aux = aux.sig print('') print('Lista concatenada') barrido_lista(lista) print('') #B y C def lista_concatenada_or(lista, lista_aux): repetidos = 0 lista_conc = Lista() aux = lista.inicio while(aux is not None): pos = busqueda_lista(lista_conc, aux.info) if(pos is None): insertar(lista_conc, aux.info) else: repetidos += 1 aux = aux.sig print("Lista concatenada sin repetidos") barrido_lista(lista_conc) print('Cantidad de elementos repetidos: ' + str(repetidos)) print('') #D def eliminar_nodos(lista): aux = lista.inicio while aux is not None: eliminar(lista, aux.info) print('Se ha eliminado el nodo:' + str(aux.info)) aux = aux.sig print(lista_letras(lista)) print(lista_letras(lista_aux)) print(lista_concatenada(lista,lista_aux)) print(lista_concatenada_or(lista,lista_aux)) print(eliminar_nodos(lista)) ''' #8. Utilizando una lista doblemente enlazada, cargar una palabra carácter a carácter, y # determinar si la misma es un palíndromo, sin utilizar ninguna estructura auxiliar. ''' NO SE HACE ''' #9. Se tiene una lista de los alumnos de un curso, de los que se sabe nombre, apellido y legajo. #Por otro lado se tienen las notas de los diferentes parciales que rindió cada uno de ellos #con la siguiente información: materia que rindió, nota obtenida y fecha de parcial. #Desarrollar un algoritmo que permita realizar la siguientes actividades: #a. mostrar los alumnos ordenados alfabéticamente por apellido; #b. indicar los alumnos que no desaprobaron ningún parcial; #c. determinar los alumnos que tienen promedio mayor a 8,89; #d. mostrar toda la información de los alumnos cuyos apellidos comienzan con L; #e. mostrar el promedio de cada uno de los alumnos; #f. debe modificar el TDA para implmentar lista de lista. ''' alumnos = ['Fernando', 'Cynthia', 'Tomas', 'Joaquin', 'Julieta', 'Walter'] apellidos = ['Picart','Carmona','Bide','Lopez','Gutierrez','Lauren'] materias = ['Algebra','Calculo','Algoritmos'] class Alumno(object): def __init__(self,nombre,apellido,legajo): self.nombre = nombre self.apellido = apellido self.legajo = legajo def __str__(self): return '<<< ' + self.nombre + ' - ' + self.apellido + ' - ' + str(self.legajo) + ' >>>' class Parcial(object): def __init__(self,materia,nota,fecha): self.materia = materia self.nota = nota self.fecha = fecha def __str__(self): return '' + self.materia + '|| Nota = '+ str(self.nota) + '|| fecha = ' + str(self.fecha) def parciales_alumnos(lista): print('Alumnos ordenados por apellido') for i in range(len(alumnos)): legajo = i+1 dato = Alumno(alumnos[i],apellidos[i],legajo) insertar(lista, dato, 'apellido') barrido_lista(lista) print(' ') for i in range(tamanio(lista)): i += 1 for j in range(3): pos = busqueda_lista(lista,i,'legajo') dato = Parcial(materias[j],randint(4,10),date(2020,randint(1,12),randint(1,30))) insertar(pos.sublista, dato, 'materia') barrido_sublista(lista) print(' ') aux = lista.inicio p = 0 while aux != None: aprobado = True c = 0 prom = 0 pos = aux.sublista.inicio while pos != None: c += 1 if pos.info.nota < 7: aprobado = False prom += pos.info.nota pos = pos.sig if aprobado == True: print(aux.info.nombre + ' ' + aux.info.apellido + ' Ha aprobado todas las materias') if ((prom / c) > 8.89): p += 1 print(aux.info.nombre + ' ' + aux.info.apellido + ' Tiene promedio mayor a 8,89, su promedio es: ' + str(round(prom/c,2))) aux = aux.sig if (p < 1): print('Ningun alumno tiene promedio mayor a 8,89.') print('') print('Alumnos con apellido que comienza con L') aux = lista.inicio while aux != None: if aux.info.apellido[0] == 'L': print(aux.info.nombre + ' ' + aux.info.apellido + '; legajo ' + str(aux.info.legajo)) aux = aux.sig print('') print('Promedio de todos los alumnos:') aux = lista.inicio while aux != None: suma_notas = 0 c = 0 pos = aux.sublista.inicio while pos != None: suma_notas += pos.info.nota c += 1 pos = pos.sig prom = (suma_notas / c) print('El promedio de el alumno ' + aux.info.nombre + ' ' + aux.info.apellido + ' es ' + str(round(prom,2))) aux = aux.sig print(parciales_alumnos(lista)) ''' #10. Se dispone de una lista de canciones de Spotify, de las cuales se sabe su nombre, banda o #artista, duración y cantidad de reproducciones durante el último mes. Desarrollar un #algoritmo que permita realizar las siguientes actividades: #a. obtener la información de la canción más larga; #b. obtener el TOP 5, TOP 10 y TOP 40 de canciones más escuchadas; #c. obtener todas las canciones de la banda Arctic Monkeys; #d. mostrar los nombres de las bandas o artistas que solo son de una palabra. ''' canciones = ['In the end','505','Smoke on the wather','Marinero','Hoja en blanco','Habia una vez','Give me power','Do I wanna know'] bandas = ['Linkin Park','Arctic Monkeys','Deep Purple','Maluma','Dread Mar I','Indio Solari','Molotov','Arctic Monkeys'] duraciones = [3.37 , 4.10 , 5.40 , 4.48 , 4.48 , 4.29 , 4.08 , 4.26] class Cancion(object): def __init__(self, nombre,banda,duracion,reprod): self.nombre = nombre self.banda = banda self.duracion = duracion self.reprod = reprod def __str__(self): return self.nombre + ' | ' + self.banda + ' | ' + str(self.duracion) + ' | ' + str(self.reprod) def spotify(lista): for i in range(len(canciones)): reproducciones = randint(1,60) dato = Cancion(canciones[i],bandas[i],duraciones[i],reproducciones) insertar(lista,dato,'reprod') aux = lista.inicio m_dur = 0 # A while aux != None: if aux.info.duracion > m_dur: m_dur = aux.info.duracion pos = aux aux = aux.sig print('la cancion de mayor duracion es ' + pos.info.nombre + ', de ' + pos.info.banda + ' con ' + str(pos.info.duracion) + ' minutos de duracion') print('') # B print('Top 5 de canciones mas escuchadas') aux = lista.inicio i = 0 while aux != None: i+=1 if (i == tamanio(lista)-5) : for i in range(5): print(aux.info.nombre + ', de ' + aux.info.banda + '; de duracion ' + str(aux.info.duracion) + ' y ' + str(aux.info.reprod) + ' MM. cantidad de reproducciones') aux = aux.sig aux = aux.sig print('') # C print('Canciones de la banda "Arctic Monkeys":') aux = lista.inicio while not aux == None: if aux.info.banda == 'Arctic Monkeys': print(aux.info.nombre + ';') aux = aux.sig print() # D print('Bandas o artistas que solo son de una palabra:') aux = lista.inicio while not aux == None: esp = False for i in range (len(aux.info.banda)): char = aux.info.banda[i] if char == ' ': esp = True if esp == False: print('- ' +aux.info.banda) aux = aux.sig print(spotify(lista)) ''' # 11. Dada una lista que contiene información de los personajes de la saga de Star Wars con la # siguiente información nombre, altura, edad, género, especie, planeta natal y episodios en # los que apareció, desarrollar los algoritmos que permitan realizar las siguientes actividades: # a. listar todos los personajes de género femenino; # b. listar todos los personajes de especie Droide que aparecieron en los primeros seis episodios de la saga; # c. mostrar toda la información de Darth Vader y Han Solo; # d. listar los personajes que aparecen en el episodio VII y en los tres anteriores (4,5,6 y 7); # e. mostrar los personajes con edad mayor a 850 años y de ellos el mayor; # f. eliminar todos los personajes que solamente aparecieron en los episodios IV, V y VI; # g. listar los personajes de especie humana cuyo planeta de origen es Alderaan; # h. mostrar toda la información de los personajes cuya altura es menor a 70 centímetros; # i. determinar en qué episodios aparece Chewbacca y mostrar además toda su información. ''' class Personaje(object): def __init__(self,nombre,altura,edad,genero,especie,planeta): self.nombre = nombre self.altura = altura self.edad = edad self.genero = genero self.especie = especie self.planeta = planeta def __str__(self): return self.nombre+' || Altura: ' +str(self.altura) +', Edad: '+str(self.edad)+ ', Genero: '+self.genero+ ', Especie: '+self.especie+', Planeta: '+self.planeta class Episodios(object): def __init__(self,episodio): self.episodio = episodio def __str__(self): return 'Episodio: ' + str(self.episodio) personajes = ['Luke Skywalker','Beru Lars', 'R2-D2', 'Han Solo', 'Maestro Yoda', 'Jar Jar Binks','Darth Vader','Chewbacca','Leia Organa'] alturas = [1.72 , 1.65 , 0.38 , 1.74 , 0.60 , 1.96 , 1.84 , 2.30 , 1.55] edades = [47,37,853,54,917,1382,1059,987,90] generos = ['M','F','Bot','M','M','M','M','M','F'] especies = ['Humano','Humano','Droide','Humano','Yoda','Gungan','Darth','Wookiee','Humano'] planetas = ['Tatooine','Tatooine','Naboo','Corellia','896 ABY','Naboo','Tatooine','Kashyyyk','Alderaan'] episodios = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] for i in range(len(personajes)): dato = Personaje(personajes[i],alturas[i],edades[i],generos[i],especies[i],planetas[i]) insertar(lista,dato,'planeta') aux = lista.inicio while not aux == None: cant = (randint(1,15)) lista_epis = [] for i in range(cant): epis = choice(episodios) if len(lista_epis) == 0: lista_epis.append(epis) insertar(aux.sublista,Episodios(epis),'episodio') if epis not in lista_epis: insertar(aux.sublista,Episodios(epis),'episodio') lista_epis.append(epis) aux = aux.sig print('Lista de personajes ordenada segun Planetas Natales: ') barrido_lista(lista) print() aux = lista.inicio # A print('Lista de personajes FEMENINOS') while aux != None: if aux.info.genero == 'F': print(aux.info) aux = aux.sig print() # B print('Lista de los personajes de especie Droide, que aparecieron en los primeros seis episodios de la saga:') aux = lista.inicio while not aux == None: pos = aux.sublista.inicio while not pos == None: if pos.info.episodio == 1: print(aux.info.nombre + ' aparecio en el capitulo 1.') elif pos.info.episodio == 2: print(aux.info.nombre + ' aparecio en el capitulo 2.') elif pos.info.episodio == 3: print(aux.info.nombre + ' aparecio en el capitulo 3.') elif pos.info.episodio == 4: print(aux.info.nombre + ' aparecio en el capitulo 4.') elif pos.info.episodio == 5: print(aux.info.nombre + ' aparecio en el capitulo 5.') elif pos.info.episodio == 6: print(aux.info.nombre + ' aparecio en el capitulo 6.') else: break pos = pos.sig aux = aux.sig # C print() print('-información de Darth Vader y Han Solo') aux = lista.inicio while aux != None : if (aux.info.nombre == 'Darth Vader') or (aux.info.nombre == 'Han Solo'): print(aux.info) aux = aux.sig # D print() print('Personajes que aparecen en el episodio VII y en los tres anteriores:') aux = lista.inicio p = 0 while aux != None: pos = aux.sublista.inicio c = 0 while pos != None: if pos.info.episodio == 4: c += 1 elif pos.info.episodio == 5: c += 1 elif pos.info.episodio == 6: c +=1 elif pos.info.episodio == 7: c += 1 if c == 4: print(aux.info.nombre +', aparecio en los capitulos 4,5,6 y 7.') p += 1 pos = pos.sig aux = aux.sig if p == 0: print('__No hay personajes que mostrar en esta lista.') # E print() print('Personajes con edad mayor a 850 años') aux = lista.inicio mayor = '' ed = 0 while aux != None: if aux.info.edad > 850: print(aux.info.nombre + ': tiene ' + str(aux.info.edad) + ' años.') if ed < aux.info.edad: mayor = aux.info.nombre ed = aux.info.edad aux = aux.sig print() print('<<< El personaje de mayor EDAD es: '+ mayor+ ', con '+ str(ed) +' años >>>') # F print() print('Se eliminaran los personajes que hayan aparecido solamente en los capitulos: 4,5 y 6') aux = lista.inicio p = 0 while aux != None: pos = aux.sublista.inicio c = 0 n = 0 while pos != None: if pos.info.episodio == 4: c += 1 elif pos.info.episodio == 5: c += 1 elif pos.info.episodio == 6: c += 1 else: n += 1 break pos = pos.sig if (c == 3) and (n == 0): eliminar(lista,aux.info.nombre,'nombre') print('Se ha eliminado al personaje '+ aux.info.nombre) p += 1 aux = aux.sig if p == 0: print('__No hay personajes que mostrar en esta lista.') print() # G print('Personajes Humanos cuyo planeta de origen es Alderaan;') aux = lista.inicio while aux != None: if (aux.info.especie == 'Humano') and (aux.info.planeta == 'Alderaan'): print(aux.info.nombre +': es Humano y su planeta natal es: ' + aux.info.planeta) aux = aux.sig print() # H print('Personajes cuya altura es menor a 70 centímetros;') aux = lista.inicio while aux != None: if aux.info.altura < 0.70: print(aux.info) aux = aux.sig print() # I aux = lista.inicio while aux != None: if aux.info.nombre == 'Chewbacca': print('- Informacion de Chewbacca:') print(aux.info) print('>>> Episodios en los que aparece:') pos = aux.sublista.inicio while pos != None: print(pos.info.episodio) pos = pos.sig aux = aux.sig print() ''' #12. Desarrollar un algoritmo que elimine el anteúltimo nodo de una lista independientemente # de la información del mismo, utilizando lista simplemente enlazada ''' print(lista_numerica(lista)) def elim_anteultimo(lista): print('---lista comun---') barrido_lista(lista) aux = lista.inicio i = 0 while aux != None: if (i == tamanio(lista)-1) : eliminar(lista,aux.info) print('') i+=1 aux = aux.sig print('- Lista sin su anteultimo nodo:') barrido_lista(lista) print(elim_anteultimo(lista)) ''' # 13. Desarrollar un algoritmo que permita visualizar el contenido de una lista de manera ascendente # y descendente de sus elementos, debe modificar el TDA para implementar lista doblemente enlazada. ''' NO SE HACE ''' # 14. Un grupo de amigos se reúnen a jugar un juego de dados, suponga que dichos jugadores están cargados # en una lista de acuerdo a un número asignado de manera aleatoria y su nombre. Desarrollar un algoritmo # que contemple las siguientes condiciones: # a. simular la tirada de un dado –de seis lados D6– en cada turno del jugador; # b. el orden de turno de los jugadores es el mismo en el que están cargados en la lista; # c. después de que tira el último jugador de la lista debe seguir el primero; # d. el juego termina cuando uno de los jugadores saca un 5, en ese caso mostrar su nombre; ''' jug = ['Juan','Ricardo','Juliana','Rocio','Marta','Federico','Mirta'] turnos = [1,2,3,4,5,6,7] dados = [1,2,3,4,5,6] class Jugador(object): def __init__(self, nombre,turno): self.nombre = nombre self.turno = turno def __str__(self): return self.nombre +' | turno nro: ' + str(self.turno) def juego_dados(lista): t = [] for i in range(len(jug)): turno = None while turno == None: turno = randint(1,len(jug)) if turno in t: turno = None else: t.append(turno) insertar(lista,Jugador(jug[i],turno),'turno') print(str(turno) + '.- sera la posicion de ' + jug[i]) print('') print('--- Jugadores por turnos ---') barrido_lista(lista) print('') print('--- Empieza el juego ---') aux = lista.inicio while aux != ' ': dado = (choice(dados)) sleep(1) print('Dado = ' + str(dado)) if dado == 5: break else: print('El jugador ha sacado ' + str(dado)) print('...Turno del siguiente jugador...') aux = aux.sig if aux == None: aux = lista.inicio print('¡¡¡¡ El jugador ' + aux.info.nombre + ' ha sacado 5 y por lo tanto ha ganado !!!!') print(juego_dados(lista)) ''' #15. Se cuenta con una lista de entrenadores Pokémon. De cada uno de estos se conoce: # nombre, cantidad de torneos ganados, cantidad de batallas perdidas y cantidad de batallas ganadas. # Y además la lista de sus Pokémons, de los cuales se sabe: nombre, nivel, tipo y subtipo. # Se pide resolver las siguientes actividades utilizando lista de lista implementando las funciones necesarias: # a. obtener la cantidad de Pokémons de un determinado entrenador; # b. listar los entrenadores que hayan ganado más de tres torneos; # c. el Pokémon de mayor nivel del entrenador con mayor cantidad de torneos ganados; # d. mostrar todos los datos de un entrenador y sus Pokémos; # e. mostrar los entrenadores cuyo porcentaje de batallas ganados sea mayor al 79 %; # f. los entrenadores que tengan Pokémons de tipo fuego y planta o agua/volador (tipo y subtipo); # g. el promedio de nivel de los Pokémons de un determinado entrenador; # h. determinar cuántos entrenadores tienen a un determinado Pokémon; #### i. mostrar los entrenadores que tienen Pokémons repetidos; # j. determinar los entrenadores que tengan uno de los siguientes Pokémons: Tyrantrum, Terrakion o Wingull; # k. determinar si un entrenador “X” tiene al Pokémon “Y”, tanto el nombre del entrenador como del Pokémon deben # ser ingresados; además si el entrenador tiene al Pokémon se deberán mostrar los datos de ambos; ''' entrenadores = ['Juan','Ricardo','Juliana','Rocio','Marta','Federico','Mirta'] pokemon = { 'Bulbasaur' : ['panta','veneno'] , 'Charmander' : ['fuego','None'] , 'Squirtle': ['Agua','None'], 'Pelipper' : ['agua','volador'] , 'Wingull' : ['agua','volador'], 'Cyndaquil' : ['fuego','planta'], 'Caterpie' : ['bicho','None'] , 'Pikachu' : ['electrico','None'] , 'Nidoran' : ['veneno','None'], 'Vulpix' : ['Fuego','None'] , 'Jigglypuff' : ['Normal','Hada'] , 'Psyduck' : ['agua','None'], 'Abra' : ['psiquico','None'] , 'Machop' : ['lucha','None'] , 'Onix' : ['roca','tierra'], 'Terrakion' : ['roca','dragon'] , 'Hitmonlee' : ['lucha','None'] , 'Magikarp' : ['agua','None'] , 'Eevee' : ['normal','None'] ,'Snorlax' : ['normal','None'] , 'Mewtwo' : ['psiquico','None'] , 'Tyrantrum' : ['roca','dragon'] , 'Articuno' : ['hielo','volador']} class Entrenador(object): def __init__(self,nombre,t_ganados,bat_ganadas,bat_perdidas,cant_pok): self.nombre = nombre self.t_ganados = t_ganados self.bat_ganadas = bat_ganadas self.bat_perdidas = bat_perdidas self.cant_pok = cant_pok def __str__(self): return self.nombre + ' | torneos: ' + str(self.t_ganados) + ' | gano ' + str(self.bat_ganadas) + ' batallas y perdio ' + str(self.bat_perdidas) + '| Tiene ' +str(self.cant_pok)+ ' Pokemones' class Pokemon(object): def __init__(self, nombre,tipo,subtipo,nivel): self.nombrepok = nombre self.tipo = tipo self.subtipo = subtipo self.nivel = nivel def __str__(self): return self.nombrepok + ' tipo: ' + self.tipo + '/'+ self.subtipo + '. su nivel es ' + str(self.nivel) def pokemones(lista): for i in range(len(entrenadores)): aux = Entrenador(entrenadores[i],randint(0,10),randint(0,100),randint(0,100),randint(1,10)) insertar(lista,aux,'t_ganados') barrido_lista(lista) print('') aux = lista.inicio while not aux == None: print(aux.info) print('---- Pokemones') cant = aux.info.cant_pok for j in range (cant): pok = choice(list(pokemon.keys())) dato = Pokemon(pok, pokemon[pok][0], pokemon[pok][1], randint(1,50)) print(dato) insertar(aux.sublista,dato,'nivel') aux = aux.sig print('') #b print('') print('<<<<< Entrenadores que han ganado MAS de 3 torneos Pokemon >>>>>') aux = lista.inicio c = 0 while not aux == None: if aux.info.t_ganados > 3 : print(aux.info) c += 1 aux = aux.sig print(' - Hay ' + str(c) + ' entrenadores que ganaron mas de 3 torneos Pokemon.') print('') # C torn = 0 ent = None aux = lista.inicio nv = 0 pok = None while not aux == None: if aux.info.t_ganados > torn: torn = aux.info.t_ganados max_torn = aux.info.nombre ent = aux.sublista.inicio while not ent == None: if nv < ent.info.nivel: nv = ent.info.nivel pok = ent.info.nombrepok ent = ent.sig aux = aux.sig print('- El entrenador que mas Torneos Pokemon ha ganado es: ' + max_torn + ', con ' + str(torn)+ ' Torneos ganados.') print('- Su pokemon de mayor nivel es: ' + pok + ' de nivel ' + str(nv)) print('') nom = input('ingrese Entrenador a mostrar sus datos y pokemones: ') pos = busqueda_lista(lista,nom,'nombre') if not pos == None: print(pos.info) print('_____Pokemones:') aux = pos.sublista.inicio while not aux == None: print(aux.info) aux = aux.sig print('') # e print('- ENTRENADORES CON PORCENTAJE DE VICTORIA MAYOR A 79% :') aux = lista.inicio x = False while aux is not None: bat_tot = aux.info.bat_ganadas + aux.info.bat_perdidas porcentaje = (aux.info.bat_ganadas * 100)/bat_tot if porcentaje > 79: x = True print(aux.info.nombre +' tiene un porcentaje de ' +str(round(porcentaje,2)) + '% batalladas ganadas.') aux = aux.sig if x == False: print('No hay Entrenadores con un porcentaje mayor a 79.') print() # f aux = lista.inicio while aux is not None: sub = aux.sublista.inicio while sub is not None: if (sub.info.tipo == 'fuego'): if (sub.info.subtipo == 'planta'): print(aux.info.nombre, ': tiene un pokemon tipo fuego y subtipo planta, ' + sub.info.nombrepok) if (sub.info.tipo == 'agua'): if (sub.info.subtipo == 'volador'): print(aux.info.nombre, ': tiene un pokemon tipo agua y subtipo volador, ' + sub.info.nombrepok) sub = sub.sig aux = aux.sig print('-') print('') # g nom = input('ingrese Entrenador a sacar promedio de nivel de sus Pokemones: ') pos = busqueda_lista(lista,nom,'nombre') if not pos == None: print(pos.info) niveles = 0 cant = 0 sub = pos.sublista.inicio while sub is not None: cant += 1 print(sub.info) niveles += sub.info.nivel sub = sub.sig prom = niveles / cant print('--- El promedio de nivel de sus pokemones es: '+ str(round(prom, 2))) print('') # H aux = lista.inicio cont = 0 pok = input(str('Ingrese el nombre del pokemon a buscar: ')) while aux is not None: pos = busqueda_lista(aux.sublista, pok, 'nombrepok') if pos is not None: cont += 1 print(aux.info.nombre +' tiene a ' + pok) aux = aux.sig print(str(cont) +' entrenadores tienen al pokemon '+ pok) print('') # J aux = lista.inicio while aux is not None: sub = aux.sublista.inicio while sub is not None: if (sub.info.nombrepok == 'Tyrantrum') or (sub.info.nombrepok == 'Terrakion') or (sub.info.nombrepok == 'Wingull'): print('El entrenador ' +aux.info.nombre + ', tiene al pokemon ' + sub.info.nombrepok) sub = sub.sig aux = aux.sig print('') # K pos = None n = None x = None while ent not in entrenadores: ent = input('Ingrese nombre del entrenador: ') pos = busqueda_lista(lista,ent,'nombre') while n not in pokemon: n = input('Ingrese nombre de pokemon a buscar: ') if (not pos == None) and (not n == None): print('') b = False nom = pos.sublista.inicio while not nom == None: if (nom.info.nombrepok == n): b = True break nom = nom.sig if b == False: print('El entrenador '+ pos.info.nombre + ' no tiene al pokemon buscado.') elif b == True: print('Entrenador y pokemon encontrados.') print('Mostrando sus datos...') sleep(1.5) print(pos.info) sleep(0.7) print(nom.info) print(pokemones(lista)) ''' # 16. Se deben administrar las actividades de un proyecto de software, de estas se conoce su # costo, tiempo de ejecución, fecha de inicio, fecha de fin estimada, fecha de fin efectiva y # persona a cargo. Desarrollar un algoritmo que realice las siguientes actividades: # a. tiempo promedio de tareas; # b. costo total del proyecto; # c. actividades realizadas por una determinada persona; # d. mostrar la información de las tareas a realizar entre dos fechas dadas; # e. mostrar las tareas finalizadas en tiempo y las finalizadas fuera de tiempo; # f. indicar cuántas tareas le quedan pendientes a una determinada persona, indicada por el usuario. ''' def proyecto_software(): proyectos = Lista() a_tiempo = Lista() fuera_de_tiempo = Lista() personal = ['Tomas', 'Flavio', 'Juan', 'Claudia', 'Guillermo', ''] actividades = ['Recopilar informacion','Estudio de factibilidad','Planificacion','Analisar la informacion','Codificar el sistema','Probar el sistema','Instalacion Sw'] promedio = 0 costo_total = 0 for i in range(len(personal)): costo = randint(0, 50000) tiempo_ejecucion = randint(1, 10) fecha_inicio = [ randint(1, 31), randint(1, 12),2020] fecha_estimada = [ randint(1, 31), randint(1, 12),2020] fechaF_efectiva = [ randint(1, 31), randint(1, 12),2020] persona_cargo = choice(personal) actividad = actividades[i] tareas = [costo,actividad, tiempo_ejecucion, fecha_inicio, fecha_estimada, fechaF_efectiva, persona_cargo] insertar(proyectos, tareas) print() print('Lista con actividades:') barrido_lista(proyectos) aux = proyectos.inicio print() while aux is not None: # A promedio = promedio + aux.info[2] # B costo_total = costo_total + aux.info[0] # C if aux.info[5]: print('Persona:',aux.info[6]) print('Actividades que realiza:',aux.info[1]) print('Coste de la actividad:',aux.info[0]) print('Tiempo de ejecucion:',aux.info[2]) print() if aux.info[2] < 7: insertar(a_tiempo,aux.info[1]) else: insertar(fuera_de_tiempo,aux.info[1]) aux = aux.sig # D fecha1 = [1,2,2020] fecha2 = [25,4,2020] print() print('Actividades entre '+ str(fecha1) + ' y '+ str(fecha2)) aux = proyectos.inicio while aux is not None: if fecha1 < aux.info[5] and fecha2 > aux.info[5]: print(aux.info[1]) aux = aux.sig print() print('Tareas que se realizaron a tiempo: ') barrido_lista(a_tiempo) print() print('Tareas que se realizaron fuera de tiempo: ') barrido_lista(fuera_de_tiempo) print(proyecto_software()) ''' # 17. Se cuenta con los vuelos del aeropuerto de Heraklion en Creta, de estos se sabe la siguiente # información: empresa, número del vuelo, cantidad de asientos del avión, fecha de salida, destino, # kms del vuelo. Y además se conoce los datos de cantidades de asientos totales y ocupados por clase # (primera y turista). Implemente las funciones necesarias que permitan realizar las siguiente actividades: # a. mostrar los vuelos con destino a Atenas, Miconos y Rodas; # b. mostrar los vuelos con asientos clase turista disponible.; # c. mostrar el total recaudado por cada vuelo, considerando clase turista ($75 por kilómetro) # y primera clase ($203 por kilómetro); # d. mostrar los vuelos programados para una determinada fecha; # e. vender un asiento (o pasaje) para un determinado vuelo; # f. eliminar un vuelo. Tener en cuenta que si tiene pasajes vendidos, se debe indicar la cantidad de # dinero a devovler; # g. mostrar las empresas y los kilómetros de vuelos con destino a Tailandia. ''' empresas = ['"British Airways"','"American Airlines"','"Lufthansa"','"Lion Air"'] destinos = ['Atenas','Miconos','Rodas','Argentina','China','Brasil','España','Francia','Tailandia'] asientos = [40,45,50,60,70,80] km = [1000,2000,2500,5000,7000,10500] clases = ['turista','primera'] tru = [False,True] class Vuelo(object): def __init__(self,empresa,num_v,c_asientos,f_salida,destino,kms): self.empresa = empresa self.num_v = num_v self.c_asientos = c_asientos self.f_salida = f_salida self.destino = destino self.kms = kms def __str__(self): return 'datos: ' + self.empresa +': vuelo ' +str(self.num_v)+', asientos: ' + str(self.c_asientos)+'; Fecha: '+ str(self.f_salida)+ ', Destino: ' + self.destino+ ', kms: ' + str(self.kms) +'.' class Asiento(object): def __init__(self,numero,ocupado,clase,precio): self.numero = numero self.ocupado = ocupado self.clase = clase self.precio = precio def __str__(self): return self.numero +'; Vendido = '+self.ocupado +', Clase: '+ self.clase +', Precio:'+ self.precio def aeropuerto(lista): for i in range(len(destinos)): num_v = i+1 d = randint(1,30) m = randint(1,12) a = randint(2020,2021) fecha = [d,m,a] kms = choice(km) cant = choice(asientos) dato = Vuelo(choice(empresas),num_v,cant,fecha,destinos[i],kms) insertar(lista,dato,'destino') aux = lista.inicio while aux != None: cant = aux.info.c_asientos p = cant//1.5 precio = 0 for i in range(cant): asiento = i+1 ocupado = choice(tru) if asiento < p: clase = 'Turista' precio = (75*kms) else: clase = 'Primera' precio = (203*kms) dato = Asiento(asiento,ocupado,clase,precio) insertar(aux.sublista,dato,'numero') aux = aux.sig # A aux = lista.inicio while not aux == None: if aux.info.destino == 'Atenas': print('Destino a Atenas: ') print(aux.info) if aux.info.destino == 'Miconos': print('Destino a Miconos: ') print(aux.info) if aux.info.destino == 'Rodas': print('Destino a Rodas: ') print(aux.info) aux = aux.sig print('') # B aux = lista.inicio while not aux == None: print() s_n = input('Desea ver los asientos libres de la clase turista del destino '+ aux.info.destino + ': ') if (s_n == 'S') or (s_n == 's'): pos = aux.sublista.inicio while not pos == None: if pos.info.clase == 'Turista' and pos.info.ocupado == False: print('El asiento '+ str(pos.info.numero) + ' esta desocupado') pos = pos.sig aux = aux.sig # C print() print('Total recaudado por cada vuelo') aux = lista.inicio while not aux == None: recaudado = 0 pos = aux.sublista.inicio while pos != None: if pos.info.ocupado == True: recaudado += pos.info.precio pos = pos.sig print('El vuelo nro '+str(aux.info.num_v)+', a '+ aux.info.destino +' recaudo: '+ str(recaudado)+ ' dinero.') aux = aux.sig print() # E s_n = None while (s_n != 'n') and (s_n != 'N'): s_n = input('Quiere comprar un nuevo pasaje? S/N: ') if (s_n == 'S') or (s_n == 's'): destino = input('Indique su destino: ') bus = None bus = busqueda_lista(lista,destino,'destino') if bus != None: compra = False while compra == False: pas = int(input('Elija numero de pasaje: (1/'+ str(bus.info.c_asientos) +') : ')) pos = bus.sublista.inicio while pos != None: if pos.info.numero == pas: if pos.info.ocupado == False: pos.info.ocupado = True print('Compra de pasaje exitosa.') print() compra = True break else: print('Lo siento, ese pasaje esta ocupado.') print() break pos = pos.sig # F print() elim = None while (elim != 'n') and (elim != 'N'): elim = input('Desea eliminar algun vuelo? S/N: ') if (elim == 's') or (elim == 'S'): vuelo = int(input('Indique con numero, el Nro de vuelo a eliminar: ')) bus = None bus = busqueda_lista(lista,vuelo,'num_v') if bus != None: b = input('- Seguro que desea eliminar el vuelo con destino a '+ bus.info.destino+' ? S/N: ') if (b == 's') or (b == 'S'): eliminar(lista,bus.info.num_v,'num_v') print('>>> Se ha eliminado el vuelo Nro: '+str(bus.info.num_v)+', con destino a '+ bus.info.destino ) pos= bus.sublista.inicio recaudado = 0 while pos != None: if pos.info.ocupado == True: recaudado += pos.info.precio pos = pos.sig print('>>> La cantidad de dinero a devolver es igual a: ' + str(recaudado)) print() # G print() print('Empresas y kilómetros de vuelos con destino a Tailandia:') aux = lista.inicio while aux != None: if aux.info.destino == 'Tailandia': print('__ La empresa '+aux.info.empresa + ' tiene un viaje a Tailandia de '+str(aux.info.kms)+' KMs.') aux = aux.sig print(aeropuerto(lista)) ''' # 18. Se tienen los usuarios colaboradores de un lista de GitHub y de cada uno de estos # se tiene una lista de los commit realizados, de los cuales se cuenta con su timestamp (en # formato fecha y hora), mensaje de commit, nombre de archivo modificado, cantidad de # líneas agregadas/eliminadas (puede ser positivo o negativo) –suponga que solo puede # modificar un archivo en cada commit que se haga–. Desarrollar un algoritmo que permita # realizar las siguientes actividades: # a. obtener el usuario con mayor cantidad de commits –podría llegar a ser más de uno–; # b. obtener el usuario que haya agregado en total mayor cantidad de líneas y el que # haya eliminado menor cantidad de líneas; # c.mostrar los usuarios que realizaron cambios sobre el archivo test.py después delas 19:45 sin importar la fecha; # d. indicar los usuarios que hayan realizado al menos un commit con cero líneas agregados o eliminadas; # e. determinar el nombre del usuario que realizó el último commit sobre el archivo app.py indicando # toda la información de dicho commit; # f. deberá utilizar el TDA lista de lista. ''' class Usuario(): def __init__(self, nombre): self.nombre = nombre def __str__(self): return self.nombre class Commit(): def __init__(self, archivo, timestamp, mensaje, cant_lineas): self.archivo = archivo self.timestamp = timestamp self.mensaje = mensaje self.cant_lineas = cant_lineas def __str__(self): return 'Archivo: '+ self.archivo +'; Timestamp: '+ self.timestamp + ', Mensaje: ' + self.mensaje + ', Modificó: ' + str(self.cant_lineas)+ ' lineas' def github(lista): lista = Lista() user = Usuario('Camilo') insertar(lista, user, 'nombre') user = Usuario('Federico') insertar(lista, user, 'nombre') user = Usuario('Flavia') insertar(lista, user, 'nombre') user = Usuario('Anastacia') insertar(lista, user, 'nombre') commit = Commit('test.py', '11-11-20 19:00', 'testeo de la app', 46) pos = busqueda_lista(lista, 'Camilo', 'nombre') insertar(pos.sublista, commit, 'archivo') commit = Commit('data.py', '11-11-20 19:00', 'correccion error', 12) pos = busqueda_lista(lista, 'Camilo', 'nombre') insertar(pos.sublista, commit, 'archivo') commit = Commit('object.java', '11-11-20 19:00', 'modelado del objeto', -37) pos = busqueda_lista(lista, 'Federico', 'nombre') insertar(pos.sublista, commit, 'archivo') commit = Commit('app.py', '11-11-20 19:00', 'basta chicos', 34) pos = busqueda_lista(lista, 'Flavia', 'nombre') insertar(pos.sublista, commit, 'archivo') commit = Commit('front.html', '11-11-20 19:00', 'update', 47) pos = busqueda_lista(lista, 'Anastacia', 'nombre') insertar(pos.sublista, commit, 'archivo') commit = Commit('vista.css', '11-11-20 19:00', 'update', -2) pos = busqueda_lista(lista, 'Anastacia', 'nombre') insertar(pos.sublista, commit, 'archivo') print('Lista de colaboradores: ') barrido_lista(lista) print() # a aux = lista.inicio mayor = 0 while aux is not None: if tamanio(aux.sublista) > mayor: mayor = tamanio(aux.sublista) aux = aux.sig aux = lista.inicio while aux is not None: if tamanio(aux.sublista) == mayor: print('Colaborador con mayor cantidad de commits: ' + aux.info.nombre) print('Cantidad de commits: '+ str(mayor)) aux = aux.sig print() # b mayor = 0 usuario = '' aux = lista.inicio while aux is not None: pos = aux.sublista.inicio mayor_aux = 0 while pos is not None: mayor_aux += pos.info.cant_lineas pos = pos.sig if mayor_aux > mayor: mayor = mayor_aux usuario = aux.info.nombre aux = aux.sig print(usuario +', agrego la mayor cantidad de lineas: ' +str(mayor)) menor = 0 usuario_menor = '' aux = lista.inicio while aux is not None: pos = aux.sublista.inicio menor_aux = 0 while pos is not None: menor_aux += pos.info.cant_lineas pos =pos.sig if menor_aux < menor: menor = menor_aux usuario_menor = aux.info.nombre aux = aux.sig print(usuario_menor+ ' elimino la mayor cantidad de lineas: '+ str(menor)) print() # C aux = lista.inicio while aux is not None: pos = busqueda_lista(aux.sublista,'test.py','archivo') if pos is not None: print(aux.info.nombre + ', ha realizado cambios en test.py') aux = aux.sig # D print() aux = lista.inicio while aux is not None: pos = busqueda_lista(aux.sublista,0,'cant_lineas') if pos is not None: print(aux.info.nombre + ' ha realizado un commit con 0 lineas') aux = aux.sig print() # E aux = lista.inicio while aux is not None: pos = busqueda_lista(aux.sublista,'app.py','archivo') if pos is not None: print(aux.info.nombre + ', ha realizado cambios en app.py') barrido_sublista(aux.sublista) aux = aux.sig print(github(lista)) ''' #19. Los astilleros de propulsores Kuat, son la mayor corporación de construcción de naves #militares que provee al imperio galáctico –dentro de sus productos más destacados están #los cazas TIE, destructores estelares, transporte acorazado todo terreno (AT-AT), #transporte de exploración todo terreno (AT-ST), ejecutor táctico todo terreno (AT-TE), #entre otros– # y nos solicita desarrollar las funciones necesarias para resolver las siguientes necesidades: #a. debe procesar los datos de las ventas de naves que están almacenados en un #rudimentario archivo de texto, en el cual cada línea tiene los siguientes datos: # código del astillero que lo produjo, producto (los mencionados previamente),precio en créditos galácticos, # si fue construido con partes recicladas o no(booleano), quien realizo la compra (en algunos casos se # desconoce quién realizola compra y este campo tiene valor desconocido), todos estos datos están # separados por “;” en cada línea del archivo; #b. cargar los datos procesados en el punto anterior en dos listas, en la primera las #ventas de las que se conocen el cliente y la segunda las que no; #c. el código del astillero son tres caracteres el primero en una letra mayúscula de la “A” # hasta la “K” seguido de dos dígitos; #d. obtener el total de ingresos de créditos galácticos y cuantas unidades se vendieron; #e. listar los nombres de todos los clientes, los repetidos deberán mostrarse una solavez, puede utilizar # una estructura auxiliar para resolverlo; #f. realizar un informe de las compras realizadas por Darth Vader; #g. se le debe realizar un descuento del 15% a los clientes que compraron naves que # fueron fabricadas con partes recicladas, mostrar los clientes y los montos a devolver a cada uno; # h. determinar cuánto ingreso genero la producción de naves cuyos modelos contengan la sigla “AT”. def venta_naves(): lista_ventas = Lista() clientes = Lista() sin_clientes = Lista() nombre_clientes = Lista() informe = Lista() #A archivo = open('naves') linea = archivo.readline() while linea: linea = linea.replace('\n', '') linea = linea.split(';') linea[0] = linea[0].upper() linea[1] = linea[1].upper() linea[2] = float(linea[2]) linea[3] = linea[3].title() linea[4] = linea[4].title() insertar(lista_ventas, linea) linea = archivo.readline() print('Lista de ventas de naves') barrido_lista(lista_ventas) print() aux = lista_ventas.inicio cont = 0 ac = 0 devolver = 0 ingresoAT = 0 while aux is not None: #B if aux.info[4] == 'Desconocido': insertar(sin_clientes, aux.info) else: insertar(clientes,aux.info) pos = busqueda_lista(nombre_clientes, aux.info[4],4) #E if pos == None: insertar(nombre_clientes,aux.info[4]) #D cont += 1 ac = ac + aux.info[2] #F if aux.info[4] == 'Darth Vader': insertar(informe, aux.info) #H if aux.info[1] == 'AT-AT' or aux.info == 'AT-ST' or aux.info == 'AT-TE': ingresoAT = ingresoAT + aux.info[2] aux = aux.sig print('Total de ingresos de creditos galacticos: ') print(ac) print() print('Total de naves vendidas:') print(cont) print() print('Listado de clientes') barrido_lista(nombre_clientes) print() print('Informe de compras de Darth Vader') barrido_lista(informe) print() print('Clientes que han comprado naves construidas con material reciclado y monto a devoler:') aux2 = lista_ventas.inicio while aux2 is not None: #G if aux2.info[3] == 'Si': devolver = (aux2.info[2] * 15) / 100 print('Al cliente: '+ aux2.info[4] + ' se le devolvera, '+str(round(devolver,2))) aux2 = aux2.sig print() print('Ingreso genero la producción de naves cuyos modelos contengan la sigla “AT”.: '+str(round(ingresoAT,2))) print(venta_naves()) #20. Una empresa meteorológica necesita registrar los datos de sus distintas estaciones en las #cuales recolecta la siguiente información proveniente de sus distintas estaciones de #adquisición de datos diariamente, implemente las funciones para satisfacer los siguientes # requerimientos: # a. se deben poder cargar estaciones meteorológicas, de cada una de estas se sabe su # país de ubicación, coordenadas de latitud, longitud y altitud; # b. estas estaciones registran mediciones de temperatura, presión, humedad y estado el clima –como # por ejemplo soleado, nublado, lloviendo, nevando, etcétera– en distintos lapsos temporales, estos # datos deberán guardarse en la lista junto con la fecha y la hora de la medición; # c. mostrar el promedio de temperatura y humedad de todas las estaciones durante el mes de mayo; # d. indicar la ubicación de las estaciones meteorológicas en las que en el día actual está lloviendo o nevando; # e. mostrar los datos de las estaciones meteorológicas que hayan registrado estado del clima tormenta eléctrica o huracanes; # f. debe implementar el TDA lista de lista. ''' paises = ['Argentina','Uruguay','Brasil','Chile','Paraguay','Mexico','Colombia','Venezuela'] estados_clima = ['soleado','nublado','lloviendo','nevando','tormenta eléctrica','vientos fuertes','huracanes'] estaciones = ['verano','otoño','invierno','primavera'] class Pais(): def __init__(self,pais,latitud,longitud,altitud): self.pais = pais self.latitud = latitud self.longitud = longitud self.altitud = altitud def __str__(self): return 'Pais: '+ self.pais +'|| Ubicacion: Latitud '+ str(self.latitud) + ', Longitud: '+ str(self.longitud) +', Altitud: '+str(self.altitud) class Medicion(): def __init__(self,fecha,temperatura,presion,humedad,clima): self.fecha = fecha self.temperatura = temperatura self.presion = presion self.humedad = humedad self.clima = clima def __str__(self): return '- Fecha: '+str(self.fecha)+'. Temperatura: '+str(self.temperatura)+ ' grados, Presion: '+str(self.presion)+ ', Humedad: '+str(self.humedad)+ ' % , Clima: '+self.clima # A for i in range(len(paises)): dato = Pais(paises[i],randint(0,100),randint(0,100),randint(0,100)) insertar(lista,dato,'pais') aux = lista.inicio # B while not aux == None: print(aux.info) for i in range(12): d = randint(1,30) m = i+1 a = randint(2020,2021) fecha = [d,m,a] dato = Medicion(fecha,randint(-10,50),randint(0,20),randint(0,100),choice(estados_clima)) print(dato) insertar(aux.sublista,dato,'fecha') print('') aux = aux.sig # C print('Promedios de Temperatura y Humedad:') aux = lista.inicio while not aux == None: pos = aux.sublista.inicio temp = 0 hum = 0 cont = 0 while not pos == None: temp += pos.info.temperatura hum += pos.info.humedad cont += 1 pos = pos.sig print(aux.info.pais + ': El promedio de Temperatura es: ' + str(round(temp/cont , 2))) print(aux.info.pais + ': El promedio de Humedad es: ' + str(round(hum/cont , 2))) aux = aux.sig print('') # D aux = lista.inicio while aux is not None: pos = aux.sublista.inicio while not pos == None: if pos.info.clima == 'lloviendo': print('En la fecha '+str(pos.info.fecha)+', en el pais ' +aux.info.pais + ' esta lloviendo.') elif pos.info.clima == 'nevando': print('En la fecha '+str(pos.info.fecha)+', en el pais ' +aux.info.pais + ' esta nevando.') pos = pos.sig aux = aux.sig print('') # E print('- Registros de estado del clima con tormenta eléctrica o huracanes:') aux = lista.inicio while aux != None: pos = aux.sublista.inicio while pos != None: if pos.info.clima == 'huracanes': print(aux.info.pais + ' registro clima de huracanes en la fecha ' + str(pos.info.fecha)) elif pos.info.clima == 'tormenta eléctrica': print(aux.info.pais+ ' registro clima de Tormenta Electrica en la fecha ' + str(pos.info.fecha)) pos = pos.sig aux = aux.sig ''' # 21. Se cuenta con una lista de películas de cada una de estas se dispone de los siguientes datos: # nombre, valoración del público –es un valor comprendido entre 0-10–, año de # estreno y recaudación. Desarrolle los algoritmos necesarios para realizar las siguientes tareas: # a. permitir filtrar las películas por año –es decir mostrar todas las películas de un determinado año–; # b. mostrar los datos de la película que más recaudo; # c. indicar las películas con mayor valoración del público, puede ser más de una; # d. mostrar el contenido de la lista en los siguientes criterios de orden (solo podrá utilizar una lista auxiliar): # i. por nombre #ii. por recaudación, #iii. por año de estreno, #iv. por valoración del público. ''' class Pelicula(): def __init__(self,nombre,valoracion,estreno,recaudacion): self.nombre = nombre self.valoracion = valoracion self.estreno = estreno self.recaudacion = recaudacion def __str__(self): return '- Pelicula: ' + self.nombre + ' ||valoracion: ' + str(self.valoracion) + '. Año de estreno: ' + str(self.estreno) + '. Ha recaudado: ' + str(self.recaudacion) pelis = ['Iron Man','Harry Potter','Stars Wars','Avengers','Spider Man','El señor de los anillos','Capitan America'] def lista_peliculas(lista): for i in range(len(pelis)): dato = Pelicula(pelis[i],randint(1,10),randint(1970,2020),randint(100000,10000000)) insertar(lista,dato,'nombre') barrido_lista(lista) print('') # A pos = None while pos == None: pos = input('Ingrese un año de estreno: ') if pos not in '1234567890': pos = None aux = lista.inicio vacio = False while aux is not None: if pos == aux.info.estreno: print('- '+aux.info.nombre +' se estreno en el año: '+ str(aux.info.estreno)) vacio = True aux = aux.sig if vacio == False: print('- Ninguna pelicula se ha estrenado en ese año.') print('') # B mas_rec = 0 mayor_p = '' aux = lista.inicio while aux is not None: if aux.info.recaudacion > mas_rec: mas_rec = aux.info.recaudacion mayor_p = aux.info aux = aux.sig print('Pelicula que mas recaudo y sus datos:') print(mayor_p) print('') # C print('Valoracion mas Alta:') aux = lista.inicio max_v = 0 while aux is not None: if aux.info.valoracion > max_v: max_v = aux.info.valoracion aux = aux.sig aux = lista.inicio while aux is not None: if aux.info.valoracion == max_v: print('- ' +aux.info.nombre +' tiene la valoracion mas alta, su puntaje es de ' + str(max_v) + ' puntos.') aux = aux.sig print('') # D print('Peliculas mostradas por criterio:') crit = None lista_aux = Lista() print('CRITERIOS: nombre / valoracion / estreno / recaudacion : ') while crit == None: crit = input('Ingrese criterio por el que quiere mostrar: ') if (crit != 'nombre') and (crit != 'recaudacion') and (crit != 'estreno') and (crit != 'valoracion'): crit = None print('ERROR: Criterio mal ingresado, vuelva a intentar...') # ordeno por criterio print('') aux = lista.inicio while aux is not None: insertar(lista_aux, aux.info, crit) aux = aux.sig print('Mostrando Peliculas por ' + crit +'...') sleep(2) barrido_lista(lista_aux) print(lista_peliculas(lista)) '''
8b7c58fcd7ba835068ecb3bcd5fd444d7c99c886
WaveBlocks/WaveBlocksND
/WaveBlocksND/MatrixPotential1S.py
20,063
3.53125
4
r"""The WaveBlocks Project This file contains code for the representation of potentials :math:`V(x)` that contain only a single energy level :math:`\lambda_0`. The number of space dimensions can be arbitrary, :math:`x \in \mathbb{R}^D`. @author: R. Bourquin @copyright: Copyright (C) 2010, 2011, 2012, 2014 R. Bourquin @license: Modified BSD License """ import sympy import numpy from WaveBlocksND.MatrixPotential import MatrixPotential from WaveBlocksND.AbstractGrid import AbstractGrid from WaveBlocksND.GridWrapper import GridWrapper from WaveBlocksND import GlobalDefaults __all__ = ["MatrixPotential1S"] class MatrixPotential1S(MatrixPotential): r"""This class represents a scalar potential :math:`V(x)`. The potential is given as an analytic :math:`1 \times 1` matrix expression. Some symbolic calculations with the potential are supported. """ def __init__(self, expression, variables, **kwargs): r"""Create a new :py:class:`MatrixPotential1S` instance for a given potential matrix :math:`V(x)`. :param expression: The mathematical expression representing the potential. :type expressiom: A `Sympy` matrix type. :param variables: The variables corresponding to the space dimensions. :type variables: A list of `Sympy` symbols. """ # This class handles potentials with a single energy level. self._number_components = 1 # The variables that represents position space. The order matters! self._variables = variables # The dimension of position space. self._dimension = len(variables) # Try symbolic simplification if "try_simplification" in kwargs: self._try_simplify = kwargs["try_simplification"] else: self._try_simplify = GlobalDefaults.__dict__["try_simplification"] # The the potential, symbolic expressions and evaluatable functions assert expression.shape == (1, 1) self._potential_s = expression self._potential_n = sympy.lambdify(self._variables, self._potential_s[0, 0], "numpy") # The cached eigenvalues, symbolic expressions and evaluatable functions self._eigenvalues_s = None self._eigenvalues_n = None # The cached eigenvectors, symbolic expressions and evaluatable functions self._eigenvectors_s = None self._eigenvectors_n = None # The cached exponential, symbolic expressions and evaluatable functions self._exponential_s = None self._exponential_n = None # The cached Jacobian of the eigenvalues, symbolic expressions and evaluatable functions self._jacobian_can_s = None self._jacobian_can_n = None self._jacobian_eigen_s = None self._jacobian_eigen_n = None # The cached Hessian of the eigenvalues, symbolic expressions and evaluatable functions self._hessian_s = None self._hessian_n = None def _grid_wrap(self, agrid): # TODO: Consider additional input types for "nodes": # list of numpy ndarrays, list of single python scalars if not isinstance(agrid, AbstractGrid): agrid = numpy.atleast_2d(agrid) agrid = agrid.reshape(self._dimension, -1) agrid = GridWrapper(agrid) return agrid def evaluate_at(self, grid, entry=None, as_matrix=False): r"""Evaluate the potential :math:`V(x)` elementwise on a grid :math:`\Gamma`. :param grid: The grid containing the nodes :math:`\gamma_i` we want to evaluate the potential at. :type grid: A :py:class:`Grid` instance. (Numpy arrays are not directly supported yet.) :param entry: The indices :math:`(i,j)` of the component :math:`V_{i,j}(x)` we want to evaluate or ``None`` to evaluate all entries. This has no effect here as we only have a single entry :math:`V_{0,0}`. :type entry: A python tuple of two integers. :param as_matrix: Dummy parameter which has no effect here. :return: A list containing a single numpy ``ndarray`` of shape :math:`(1,|\Gamma|)`. """ grid = self._grid_wrap(grid) # Evaluate the potential at the given nodes values = self._potential_n(*grid.get_nodes(split=True)) # Test for potential being constant if numpy.atleast_1d(values).shape == (1,): values = values * numpy.ones(grid.get_number_nodes(), dtype=numpy.complexfloating) # Put the result in correct shape (1, #gridnodes) N = grid.get_number_nodes(overall=True) result = [values.reshape((1, N))] # TODO: Consider unpacking single ndarray iff entry != None if entry is not None: result = result[0] return result def calculate_eigenvalues(self): r"""Calculate the eigenvalue :math:`\lambda_0(x)` of the potential :math:`V(x)`. In the scalar case this is just equal to the matrix entry :math:`V_{0,0}(x)`. Note: This function is idempotent and the eigenvalues are memoized for later reuse. """ if self._eigenvalues_s is not None: return self._eigenvalues_s = self._potential_s self._eigenvalues_n = self._potential_n def evaluate_eigenvalues_at(self, grid, entry=None, as_matrix=False): r"""Evaluate the eigenvalue :math:`\lambda_0(x)` elementwise on a grid :math:`\Gamma`. :param grid: The grid containing the nodes :math:`\gamma_i` we want to evaluate the eigenvalue at. :type grid: A :py:class:`Grid` instance. (Numpy arrays are not directly supported yet.) :param entry: The indices :math:`(i,j)` of the component :math:`\Lambda_{i,j}(x)` we want to evaluate or ``None`` to evaluate all entries. If :math:`j = i` then we evaluate the eigenvalue :math:`\lambda_i(x)`. This has no effect here as we only have a single entry :math:`\lambda_0`. :type entry: A python tuple of two integers. :param as_matrix: Dummy parameter which has no effect here. :return: A list containing a single numpy ndarray of shape :math:`(N_1, ... ,N_D)`. """ # Just evaluate the potential return self.evaluate_at(grid, entry=entry, as_matrix=as_matrix) def calculate_eigenvectors(self): r"""Calculate the eigenvector :math:`\nu_0(x)` of the potential :math:`V(x)`. In the scalar case this is just the value :math:`1`. Note: This function is idempotent and the eigenvectors are memoized for later reuse. """ # We will never use the values pass def evaluate_eigenvectors_at(self, grid, entry=None): r"""Evaluate the eigenvector :math:`\nu_0(x)` elementwise on a grid :math:`\Gamma`. :param grid: The grid containing the nodes :math:`\gamma_i` we want to evaluate the eigenvector at. :type grid: A :py:class:`Grid` instance. (Numpy arrays are not directly supported yet.) :param entry: The index :math:`i` of the eigenvector :math:`\nu_i(x)` we want to evaluate or ``None`` to evaluate all eigenvectors. This has no effect here as we only have a single entry :math:`\nu_0`. :type entry: A singly python integer. :return: A list containing the numpy ndarrays, all of shape :math:`(1, |\Gamma|)`. """ # TODO: Rethink about the 'entry' parameter here. Do we need it? grid = self._grid_wrap(grid) shape = (1, grid.get_number_nodes(overall=True)) return tuple([numpy.ones(shape, dtype=numpy.complexfloating)]) def calculate_exponential(self, factor=1): r"""Calculate the matrix exponential :math:`\exp(\alpha V)`. In the case of this class the matrix is of size :math:`1 \times 1` thus the exponential simplifies to the scalar exponential function. Note: This function is idempotent. :param factor: The prefactor :math:`\alpha` in the exponential. """ self._exponential_s = sympy.exp(factor * self._potential_s[0, 0]) self._exponential_n = sympy.lambdify(self._variables, self._exponential_s, "numpy") def evaluate_exponential_at(self, grid, entry=None): r"""Evaluate the exponential of the potential matrix :math:`V(x)` on a grid :math:`\Gamma`. :param grid: The grid containing the nodes :math:`\gamma_i` we want to evaluate the exponential at. :type grid: A :py:class:`Grid` instance. (Numpy arrays are not directly supported yet.) :return: The numerical approximation of the matrix exponential at the given grid nodes. """ grid = self._grid_wrap(grid) if self._exponential_n is None: self.calculate_exponential() # Evaluate the exponential at the given nodes values = self._exponential_n(*grid.get_nodes(split=True)) # Test for potential being constant if numpy.atleast_1d(values).shape == (1,): values = values * numpy.ones(grid.get_number_nodes(), dtype=numpy.complexfloating) # Put the result in correct shape (1, #gridnodes) N = grid.get_number_nodes(overall=True) result = [values.reshape((1, N))] # TODO: Consider unpacking single ndarray iff entry != None if entry is not None: result = result[0] return result def calculate_jacobian(self): r"""Calculate the Jacobian matrix :math:`\nabla V` of the potential :math:`V(x)` with :math:`x \in \mathbb{R}^D`. For potentials which depend only one variable, this equals the first derivative and :math:`D=1`. Note that this function is idempotent. """ if self._jacobian_eigen_s is None: # TODO: Add symbolic simplification self._jacobian_eigen_s = self._potential_s.jacobian(self._variables).T self._jacobian_eigen_n = tuple(sympy.lambdify(self._variables, entry, "numpy") for entry in self._jacobian_eigen_s) def evaluate_jacobian_at(self, grid, component=None): r"""Evaluate the potential's Jacobian :math:`\nabla \Lambda(x)` at some grid nodes :math:`\Gamma`. :param grid: The grid nodes :math:`\Gamma` the Jacobian gets evaluated at. :param component: Dummy parameter that has no effect here. :return: The value of the potential's Jacobian at the given nodes. The result is an ``ndarray`` of shape :math:`(D,1)` is we evaluate at a single grid node or of shape :math:`(D,|\Gamma|)` if we evaluate at multiple nodes simultaneously. """ # TODO: Rethink about the 'component' parameter here. Do we need it? grid = self._grid_wrap(grid) nodes = grid.get_nodes(split=True) D = self._dimension N = grid.get_number_nodes(overall=True) J = numpy.zeros((D, N), dtype=numpy.complexfloating) for row in range(D): J[row, :] = self._jacobian_eigen_n[row](*nodes) return J def calculate_jacobian_canonical(self): r"""Calculate the Jacobian matrix :math:`\nabla V(x)` of the potential :math:`V(x)` with :math:`x \in \mathbb{R}^D`. For potentials which depend only one variable, this equals the first derivative and :math:`D=1`. Note that this function is idempotent. """ if self._jacobian_can_s is None: # TODO: Add symbolic simplification self._jacobian_can_s = self._potential_s.jacobian(self._variables).T self._jacobian_can_n = tuple([sympy.lambdify(self._variables, entry, "numpy") for entry in self._jacobian_can_s]) def evaluate_jacobian_canonical_at(self, grid, component=None): r"""Evaluate the potential's Jacobian :math:`\nabla V(x)` at some grid nodes :math:`\Gamma`. :param grid: The grid nodes :math:`\Gamma` the Jacobian gets evaluated at. :param component: Dummy parameter that has no effect here. :return: The value of the potential's Jacobian at the given nodes. The result is an ``ndarray`` of shape :math:`(D,1)` is we evaluate at a single grid node or of shape :math:`(D,|\Gamma|)` if we evaluate at multiple nodes simultaneously. """ # TODO: Rethink about the 'component' parameter here. Do we need it? grid = self._grid_wrap(grid) nodes = grid.get_nodes(split=True) D = self._dimension N = grid.get_number_nodes(overall=True) J = numpy.zeros((D, N), dtype=numpy.complexfloating) for row in range(D): J[row, :] = self._jacobian_can_n[row](*nodes) return J def calculate_hessian(self): r"""Calculate the Hessian matrix :math:`\nabla^2 V` of the potential :math:`V(x)` with :math:`x \in \mathbb{R}^D`. For potentials which depend only one variable, this equals the second derivative and :math:`D=1`. Note that this function is idempotent. """ if self._hessian_s is None: # TODO: Add symbolic simplification self._hessian_s = sympy.hessian(self._potential_s[0, 0], self._variables) self._hessian_n = tuple(sympy.lambdify(self._variables, entry, "numpy") for entry in self._hessian_s) def evaluate_hessian_at(self, grid, component=None): r"""Evaluate the potential's Hessian :math:`\nabla^2 V(x)` at some grid nodes :math:`\Gamma`. :param grid: The grid nodes :math:`\Gamma` the Hessian gets evaluated at. :param component: Dummy parameter that has no effect here. :return: The value of the potential's Hessian at the given nodes. The result is an ``ndarray`` of shape :math:`(D,D)` is we evaluate at a single grid node or of shape :math:`(|\Gamma|,D,D)` if we evaluate at multiple nodes simultaneously. """ # TODO: Rethink about the 'component' parameter here. Do we need it? grid = self._grid_wrap(grid) nodes = grid.get_nodes(split=True) D = self._dimension N = grid.get_number_nodes(overall=True) H = numpy.zeros((N, D, D), dtype=numpy.complexfloating) for row in range(D): for col in range(D): H[:, row, col] = self._hessian_n[row * D + col](*nodes) # 'squeeze' would be dangerous here, make sure it works in the 1D case too if N == 1: H = H[0, :, :] return H def calculate_local_quadratic(self, diagonal_component=None): r"""Calculate the local quadratic approximation :math:`U(x)` of the potential's eigenvalue :math:`\lambda(x)`. Note that this function is idempotent. :param diagonal_component: Dummy parameter that has no effect here. """ # Calculation already done at some earlier time? self.calculate_eigenvalues() self.calculate_jacobian() self.calculate_hessian() # Construct function to evaluate the Taylor approximation at point q at the given nodes self._taylor_eigen_s = [(0, self._eigenvalues_s), (1, self._jacobian_eigen_s), (2, self._hessian_s)] self._taylor_eigen_n = [(0, self._eigenvalues_n), (1, self._jacobian_eigen_n), (2, self._hessian_n)] def evaluate_local_quadratic_at(self, grid, diagonal_component=None): r"""Numerically evaluate the local quadratic approximation :math:`U(x)` of the potential's eigenvalue :math:`\lambda(x)` at the given grid nodes :math:`\Gamma`. This function is used for the homogeneous case. :param grid: The grid nodes :math:`\Gamma` the quadratic approximation gets evaluated at. :param diagonal_component: Dummy parameter that has no effect here. :return: A list containing the values :math:`V(\Gamma)`, :math:`\nabla V(\Gamma)` and :math:`\nabla^2 V(\Gamma)`. """ grid = self._grid_wrap(grid) # TODO: Relate this to the _taylor_eigen_{s,n} data V = self.evaluate_eigenvalues_at(grid, entry=(diagonal_component, diagonal_component)) J = self.evaluate_jacobian_at(grid) H = self.evaluate_hessian_at(grid) return tuple([V, J, H]) def calculate_local_remainder(self, diagonal_component=None): r"""Calculate the non-quadratic remainder :math:`W(x) = V(x) - U(x)` of the quadratic Taylor approximation :math:`U(x)` of the potential's eigenvalue :math:`\lambda(x)`. Note that this function is idempotent. :param diagonal_component: Dummy parameter that has no effect here. """ # Calculation already done at some earlier time? self.calculate_eigenvalues() self.calculate_jacobian() self.calculate_hessian() # Point q where the Taylor series is computed # This is a column vector q = (q1, ... ,qD) qs = [sympy.Symbol("q" + str(i)) for i, v in enumerate(self._variables)] pairs = [(xi, qi) for xi, qi in zip(self._variables, qs)] V = self._eigenvalues_s.subs(pairs) J = self._jacobian_eigen_s.subs(pairs) H = self._hessian_s.subs(pairs) # Symbolic expression for the quadratic Taylor expansion term xmq = sympy.Matrix([(xi - qi) for xi, qi in zip(self._variables, qs)]) quadratic = V + J.T * xmq + sympy.Rational(1, 2) * xmq.T * H * xmq # Symbolic simplification may fail if self._try_simplify: try: quadratic = quadratic.applyfunc(sympy.simplify) except: pass # Symbolic expression for the Taylor expansion remainder term remainder = self._potential_s - quadratic # Symbolic simplification may fail if self._try_simplify: try: remainder = remainder.applyfunc(sympy.simplify) except: pass self._remainder_s = remainder # Construct functions to evaluate the approximation at point q at the given nodes # The variable ordering in lambdify is [x1, ..., xD, q1, ...., qD] self._remainder_n = tuple([sympy.lambdify(list(self._variables) + qs, self._remainder_s[0, 0], "numpy")]) def evaluate_local_remainder_at(self, grid, position, diagonal_component=None, entry=None): r"""Numerically evaluate the non-quadratic remainder :math:`W(x)` of the quadratic approximation :math:`U(x)` of the potential's eigenvalue :math:`\lambda(x)` at the given nodes :math:`\Gamma`. :param grid: The grid nodes :math:`\Gamma` the remainder :math:`W` gets evaluated at. :param position: The point :math:`q \in \mathbb{R}^D` where the Taylor series is computed. :param diagonal_component: Dummy parameter that has no effect here. :keyword entry: Dummy parameter that has no effect here. :return: A list with a single entry consisting of an ``ndarray`` containing the values of :math:`W(\Gamma)`. The array is of shape :math:`(1,|\Gamma|)`. """ grid = self._grid_wrap(grid) position = numpy.atleast_2d(position) # Evaluate the remainder at the given nodes args = grid.get_nodes(split=True) + numpy.vsplit(position, position.shape[0]) values = self._remainder_n[0](*args) # Test for potential being constant if numpy.atleast_1d(values).shape == (1,): values = values * numpy.ones(grid.get_number_nodes(), dtype=numpy.complexfloating) # Put the result in correct shape (1, #gridnodes) N = grid.get_number_nodes(overall=True) result = [values.reshape((1, N))] # TODO: Consider unpacking single ndarray iff entry != None if entry is not None: result = result[0] return result
6f465f061f274fe3d2a597c4863d9fd82fb17e70
watalo/fullstack
/面对对象/Day2/1-变量.py
1,728
3.859375
4
#!/usr/bin/python # -*- coding: utf-8 -*- #__author__:"watalo" # @Time: 2019/12/22 19:58 # @Site : # @File : 1-变量.py # @Software: PyCharm # class Foo: # def __init__(self): # 构造方法 # self.name = name # self.age = 21 # # obj = Foo('国宴中') # # class Food: # def func(self): # print(self) # # obj = Food() # print(obj.func()) class Circle: def __init__(self,r): self.r = r self.pi = 3.1415927 def mianji(self): return 0.5*self.r*self.r*self.pi def zhouchang(self): return 2*self.r*self.pi obj = Circle(3) r = obj.mianji() q = obj.zhouchang() print(r,q) class Foo: #类变量/静态字段 country = '中国' # 方法 def __init__(self, name): self.name = name # 实例变量/字段 # 方法 def func(self): pass # obj:Foo类的对象 或者 Foo类的实例 obj1 = Foo('继红') obj2 = Foo('阳光') obj1.country = '美国' print(obj1.country) print(obj2.country) Foo.country = '美国' print(obj1.country) print(obj2.country) # 成员修饰符 #私有实例变量(字段):self.__name class Foo: country = "CN" __city = 'SH' def __init__(self,name): self.name = name self.age = 123 # 私有实例变量(字段) self.__name = name+'a' def func(self): print(self.name) def funs(self): print(self.__name) def funt(self): print(Foo.__city) obj = Foo('sss') print(obj.name) print(obj.age) obj.func() obj.funs() obj.funt() class Foss: country = "CN" __city = 'SH' def __init__(self, name): self.__name = name obj3 = Foss('大大大') print(obj3._Foss__name) # 不推荐
d528e253401283555c736a3cc3b574f65cc49aa1
minhlong94/Theoretical-Models-in-Computing
/Lab 4 - Optimization and HyperOpt/Newton's Algorithm.py
750
4.0625
4
import sympy as s x = s.Symbol('x') f = 4*x - 1.8*(x**2) + 1.2*(x**3) - 0.3*(x**4) iter = int(input("Input your number of iteration:\n")) err = float(input("Input your relative error:\n")) x0 = int(input("Input your initial guess:\n")) print("The program now calculates {} using Newton's Algorithm\n".format(f)) x_prime = s.diff(f, x) # Differentiate x_prime2 = s.diff(f, x, 2) # Second diff for i in range(iter): x1 = x0 - x_prime.subs(x, x0)/x_prime2.subs(x, x0) # Newton-Raphson formula relaerr = s.Abs((x1-x0)/x1) print("Iteration #{}, New x value: {}, Max value: {}, Relative Approx Error:" " {}\n".format(i, x1, f.subs(x, x1), relaerr)) if relaerr > err: x0 = x1 continue else: break
a9242b7fd84c3a3338ffe9981a486fcd18040186
fidelis111/fidelis1
/ex28.py
334
3.9375
4
import random computador = random.randint(0, 5) #faz o computador pensar print('Vou pensar em um número de 0 a 5, tente adivinhar: ') jogador = int(input('Em que número eu pensei? ')) #o jogador tenta adivinhar if jogador == computador: print('Parabéns, você acertou.') else: print('Não foi dessa vez, tente de novo.')
17676c830d2018ffff868232ced6c850b9d8724b
MichelleZ/leetcode
/algorithms/python/designBrowserHistory/designBrowserHistory.py
897
3.84375
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Source: https://leetcode.com/problems/design-browser-history/ # Author: Miao Zhang # Date: 2021-05-09 class BrowserHistory: def __init__(self, homepage: str): self.urls = [] self.urls.append(homepage) self.idx = 0 def visit(self, url: str) -> None: while len(self.urls) > self.idx + 1: self.urls.pop() self.idx += 1 self.urls.append(url) def back(self, steps: int) -> str: self.idx = max(self.idx - steps, 0) return self.urls[self.idx] def forward(self, steps: int) -> str: self.idx = min(self.idx + steps, len(self.urls) - 1) return self.urls[self.idx] # Your BrowserHistory object will be instantiated and called as such: # obj = BrowserHistory(homepage) # obj.visit(url) # param_2 = obj.back(steps) # param_3 = obj.forward(steps)
b4408f7e8c27750a1dd619f71bc0d7d9a1471d5e
mychristopher/test
/Selenium练习/pytest_sample/base_used/test_assert.py
1,060
4
4
# 功能:用于计算a,b 相加的和 def add(a, b): return a + b # 功能:用于判断素数 def is_prime(n): if n <= 1: return False for i in range(2, n): if n % i == 0: return False return True # 测试相等 def test_add_1(): assert add(3, 4) == 7 # 测试不相等 def test_add_2(): assert add(17, 22) != 50 # 测试大于等于 def test_add_3(): assert add(17, 22) <= 50 # 测试小于等于 def test_add_4(): assert add(17, 22) >= 38 # 测试包含 def test_in(): a = "hello" b = "he" assert b in a # 测试不包含 def test_not_in(): a = "hello" b = "hi" assert b not in a # 判断是否为True def test_true_1(): assert is_prime(13) # 判断是否为True def test_true_2(): assert is_prime(7) is True # 判断是否不为True def test_true_3(): assert not is_prime(4) # 判断是否不为True def test_true_4(): assert is_prime(6) is not True # 判断是否为False def test_false_1(): assert is_prime(8) is False
e5c51a662a38f71a745b91efb285bee4f997c6e4
JulianDomingo/learningPython
/firstProgram.py
465
4
4
print('Hello, user.') print('What is your name?') name = input() print('Welcome, ' + name) print('Your name is ') print(len(name)) print(' letters long.') print('What about your age?') age = input() ageVal = int(age) print('You are ' + age + ' years old.') if ageVal >= 21: print('You are old enough to legally drink in the U.S.') else: print('You cannot legally drink in the U.S.') if ageVal == 20: print('Just one more year to go, though!')
dc57b8a59de8a10eaf54bdb6d8edc788e93e9369
bigfil/Code-chef-practice
/digitCounter.py
92
3.890625
4
size = len(str(input())) if size <= 3: print(size) else: print("More than 3 digits")
1ee5530f3b42635cd91749cd181091d1748f3bad
davidyc/GitHub
/davidyc/simplepython/MyFirst.py
480
3.65625
4
from tkinter import * clicked = 0 def Click(): global clicked clicked += 1 root.title("Мой первый интерфейс на Python нажатий клавиш {0}".format(clicked)) root = Tk() root.title("Мой первый интерфейс на Python нажатий клавиш {0}".format(clicked)) root.geometry("800x250") btm = Button(text="Click Me", padx="20", pady="8", font="16", command=Click) btm.pack() root.mainloop()
9524dfd93676c2945b58d564376f7cc568947edc
tpeoples2/Learning-Python
/python_Challenge/puzzle3/puzzle3.py
128
3.703125
4
text = open("puzzle3txt").read() import re hits = re.findall("[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]", text) print "".join(hits)
eb9bfd62db1e67b1d0fd6ff928daaa61422331a1
nderkach/algorithmic-challenges
/reverse_words.py
445
3.640625
4
# def reverse_words(message): # m = ''.join(message[::-1]) # return ' '.join([e[::-1] for e in m.split()]) def reverse_words(message): m = list(message) m = m[::-1] j = 0 for i in range(len(m)+1): if i == len(m) or m[i] == ' ': m[j:i] = m[j:i][::-1] j = i + 1 return ''.join(m) message = 'find you will pain only go you recordings security the into if' print(reverse_words(message))
ee3cb6235f639301f814276d194b9ff3588210ca
jmajorNRELgit/Random-code_bits
/email project/clean up emails.py
1,491
3.609375
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 6 14:03:41 2018 @author: jmajor """ import pandas as pd df = pd.read_csv('C:/Users/jmajor/Desktop/combined_emails.csv', header = None) emails = list(df.iloc[:,0]) i = 0 for email in emails: if len(email.split(' ')) > 1: email = email.split(' ')[-1].lstrip('<').lstrip('(').rstrip('>').rstrip(')') print(email) emails[i] = email i +=1 print(i) #function to remove exact duplicates def remove_exact_duplicates(items): seen = set() for item in items: if item not in seen: print(item) yield item seen.add(item) remove_exact_duplicates(emails) '''This section sorted out the names as well as the email addresses''' #''' #This script searches an HTML website file for specific email addresses #''' ##read the html file as a test file #with open('C:/Users/jmajor/Desktop/emails.htm', 'r') as f: # html_text = f.read() # ##list to hold all the email addresses #names = [] # ##split the test string #html_split = html_text.split('document.Person.submit();"><b>') # #for html in html_split: # for i in range(len(html)): # if html[i] == '<': # names.append(html[:i]) # break # #emails = [] #html_split = html_text.split('href="mailto:') # # #for html in html_split: # for i in range(len(html)): # if html[i] == '"': # emails.append(html[:i]) # break # #names = names[1:] #emails = emails[1:-1]
907fdd94385570eca49cf9051d75e8e5bcfc6d3d
Proxims/PythonLessons
/Lesson_13_Input.py
863
4.09375
4
# Lesson-13-Input name = input("Please enter ypur name: ") print("Privet " +name) print("------------------------\n") num1 = input("Enter X: ") num2 = input("Enter Y: ") # По умолчанию Input вводит строчные значения, summa = int(num1) + int(num2) # конвертируем в цифровые при помощи int() print(summa) print("------------------------\n") message ="" while message != 'sekret': message = input("Enter password ") print(message + " Wrong password") else: print(message + " Correct password") print("------------------------\n") mylist = [] msg= "" while msg.upper() != 'STOP': msg = input("Enter new item, and STOP to finish: ") if msg.upper() == 'STOP': break else: mylist.append(msg) print(mylist)
b3d0535f7f2180d3cd66c83e4b94d65f333e8975
brenddesigns/learning-python
/7. Conditions/conditions.py
1,804
4.46875
4
# Project Name: Conditions # Version: 1.0 # Author: Brendan Langenhoff (brend-designs) # Description: Boolean logic to evaluate conditions. x = 2 print(x == 2) # Prints out True (Logic: is 'x' equal to 2?) print(x == 3) # Prints out False (Logic: is 'x' equal to 3?) print(x < 3) # Prints out False (Logic: is 'x' less than 3?) print(x > 1) # Prints out True (Logic: is 'x' greater than 1?) print(x >= 2) # Prints out True (Logic: is 'x' greater than OR equal to 2?) print(x <= 3) # Prints out True (Logic: is 'x' less than OR equal to 3?) print(x != 2) # Prints out False (Logic: is x is not equal to 2?) name = "John" age = 23 # Returns True (Logic: is their name 'John' AND is there age equal to 23?) if name == "John" and age == 3: print("Your name is John, and you are also 23 years old.") # Returns True (Logic: is their name 'John' OR is there name 'Rick'?) if name == "John" or name == "Rick": print("Your name is either John or Rick.") # Return True (Logic: is their name in a iterable object (such as a list) which contains 'John' and 'Rick'?) if name in ["John", "Rick"]: print("Your name is either John or Rick.") # Example of 'if, else if then else' statement statement = False another_statement = True if statement is True: # do something pass elif another_statement is True: # else if statement # do something else pass else: # do another thing pass # Example of "is" operator x = [1, 2, 3] y = [1, 2, 3] print(x == y) # Prints out True (Logic: Does x match the values of y? (Variable wise)) # Prints out False (Logic: Is y the instance of x? (Not comparing values of the variables)) print(x is y) # Example of "not" operator to invert a boolean expression. print(not False) # Prints out True print((not False) == (False)) # Prints out true
e7d65db3e70e1c2371b731d8ab883613d030c2cc
pageza/dojo_Python
/Python_Fundamentals/coin_tosses.py
788
4
4
# Coin Tosses # Write a function that simulates tossing a coin 5,000 times. # Your function should print how many times the head/tail appears. import random def toss_coin(): result = random.randint(0,1) return result def tosses(num): print "Starting to toss coins..." heads_count = 0 tails_count = 0 for i in range(1,num): print "Tossing now...." flip = toss_coin() if flip == 1 : heads_count += 1 print "Attempt #"+str(i)+" results in heads! You have "+str(heads_count)+"head(s) and "+str(tails_count)+"tail(s) so far!" else : tails_count += 1 print "Attempt #"+str(i)+" results in tails! You have "+str(heads_count)+"head(s) and "+str(tails_count)+"tail(s) so far!" tosses(500)
25e005062bc23eff142fcb13c1251cf7381b44fb
marekkowal/LearnPythonTheHardWay
/ex43.py
3,498
4.21875
4
__author__ = 'marek' from sys import exit class Scene(object): def enter(self): print "You've just entered a scene! But you should not be really" \ " seeing this message. This is the master class's method. " \ "Implement the right one in the actual subclass." exit(1) class Engine(object): def __init__(self, scene_map): print "Starting the game engine." self.scene_map = scene_map print "I was initiated with ", scene_map, " as the starting scene." def play(self): print "Ok, let's play. First, I will open the scene, and then go into " \ "an endless loop (here), playing subsequent scenes." current_scene = self.scene_map.opening_scene() print "The first scene to play is", current_scene while True: print "\n----------" next_scene_name = current_scene.enter() print "Next scene:", next_scene_name current_scene = self.scene_map.next_scene(next_scene_name) print "I am given the next scene:", current_scene class Death(Scene): def enter(self): print "Ouch, you die! Game over!" exit(1) class CentralCorridor(Scene): def enter(self): print "Hi, welcome to central corridor!" print "There's a pill lying on the floor, and there is a door too." print "What do you do? take the pill or open the door?" answer = raw_input("> ") if answer == "take the pill": print "Ok. Taking the pill" return "death" elif answer == "open the door": print "Ok. Opening the door." return "the bridge" else: print "What???" return "death" class LaserWeaponArmory(Scene): def enter(self): print "Welcome to Laser Weapon Armory. The room is empty. There's only" \ "a door behind you. Which door to open?" answer = raw_input("> ") if answer == "behind": return "the bridge" else: return "death" class TheBridge(Scene): def enter(self): print "Welcome to the bridge. There's a monster here, asking you a" \ "question. But there is also a door at the left, right, and" \ " behind you. Which one do you open?" answer = raw_input("> ") if answer == "left": return "laser weapon armory" elif answer == "right": return "escape pod" elif answer == "behind": return "central corridor" else: return "death" class EscapePod(Scene): def enter(self): print "Congratulations! You have reached the escape pod. Now, enter" \ " the password to safely escape!" exit(1) class Map(object): scenes = {"central corridor": CentralCorridor(), "the bridge": TheBridge(), "death": Death(), "laser weapon armory": LaserWeaponArmory(), "escape pod": EscapePod()} def __init__(self, start_scene): self.start_scene = start_scene print "Start_scene in __init__:", start_scene def next_scene(self, scene_name): print "Serving the object of Next scene" val = Map.scenes.get(scene_name) return val def opening_scene(self): return self.next_scene(self.start_scene) a_map = Map('central corridor') a_game = Engine(a_map) a_game.play()
39988f2c5832ece346e70fc673318840e5ebd25a
luigi-borriello00/Metodi_SIUMerici
/sistemi_lineari/esercizi/Test5.py
1,272
3.515625
4
# -*- coding: utf-8 -*- """ Test 5 testiamo come utilizzando il pivoting i |moltiplicatori| sono tutti < 1 """ import funzioni_Sistemi_lineari as fz import numpy as np scelta = input("Seleziona Matrice ") matrici = { "1" : [np.array([[3,1,1,1], [2,1,0,0], [2,0,1,0], [2,0,0,1]],dtype=float), np.array([[4],[1],[2],[4]],dtype=float), np.array([1,-1,0,2],dtype=float).reshape((4,1))], "2" : [np.array([[1,0,0,2], [0,1,0,2], [0,0,1,2], [1,1,1,3]],dtype=float), np.array([[4],[1],[2],[4]],dtype=float), np.array([2,-1,0,1],dtype=float).reshape((4,1))], } A, b, xEsatto = matrici.get(scelta) P,L,U,flag = fz.LU_nopivot(A) if flag != 0: print("Non risolvibile senza pivoting") else: uMax = np.max(np.abs(U)) lMax = np.max(np.abs(L)) x, flag = fz.LUsolve(L,U,P, b) print(f"Usando no-pivot \n {x}") print("Elemento max di U = ",uMax,", elemento max di L = ",lMax) P,L,U,flag = fz.LU_pivot(A) if flag != 0: print("Non risolvibile con pivoting") else: uMax = np.max(np.abs(U)) lMax = np.max(np.abs(L)) x, flag = fz.LUsolve(L,U,P, b) print(f"Usando pivot \n {x}") print("Elemento max di U = ",uMax,", elemento max di L = ",lMax)
9c6dc6e290cb758384b4d10b6b5dbebc087c4eee
ROOPAUS/Python_LeetCode
/Find words that can be formed by characters.py
532
3.78125
4
class Solution: def countCharacters(self, words:[str], chars: str) -> int: from collections import Counter count=0 charcount=Counter(chars) for s in words: scount=Counter(s) if(scount & charcount==scount): count=count+len(s) return count n=int(input("Enter number of words in list: ")) chars=input("Enter characters") words=[] for i in range(n): words.append(input("Enter element")) result=Solution().countCharacters(words,chars) print(result)
fbbf5b904f2df758cb0df76683d0a438d052db35
Jingliwh/python3-
/pythonio.py
3,039
3.5
4
#python-IO学习 #open("路径","r/w") #读写字符注意编码错误 #绝对路径与相对路径 #1读文件 #1.1文件打开 ''' f1=open("c:/Users/Administrator/Desktop/python_stydy/py3test/py3test.py","r") str1=f1.read() print(str1) f1.close() ''' #1.2打开文件捕获异常 ''' try: f = open("py3test/py3test.py","r") print(f.read()) except Exception as e: print("file not found") finally: print("finally") if f: f.close() ''' #1.3with语句来自动调用close()方法 ''' with open("py3test/py3test.py","r") as f: print(f.read()) #f.read()一次性读取完 #f.readlines()按行读取,可用于读取配置文件 #f.read(size) 按固定size读取文件,在不知道文件具体大小的情况下 ''' #1.4读二进制文件 ''' f = open('mode/haha.jpg', 'rb') print(f.read()) ''' #2写文件 #2.1写入文件 ''' with open('py3test/py3test.py', 'w') as f: f.write('Hello, world!---') print("写入成功") ''' #按某种编码读取,有错就忽略 ''' f1 = open('minmax.py', 'r', encoding='UTF-8', errors='ignore') print(f1.read()) ''' #3StringIO and BytesIO #3.1StringIO 读取内存中的字符串 ''' from io import StringIO f=StringIO() f.write("hello") f.write("hehe") f.write("000000") print(f.getvalue()) ''' #3.2BytesIO 读取内存中的二进制数据 ''' from io import BytesIO f = BytesIO() f.write('中文'.encode('utf-8')) print(f.getvalue()) ''' #4操作文件和目录 #4.1判断操作系统 #nt 表示windows posix表示Linux Unix macos ''' import os print(os.name)#操作系统名 #print(os.uname())#操作系统详情,只在Linux等上提供 print(os.environ) #环境变量 print(os.environ.get('path')) ''' #4.2操作文件和目录 ''' import os print(os.path.abspath('.')) #当前绝对路径 cdir=os.path.abspath('.') #os.mkdir(os.path.join(cdir, 'testdir'))#在此路径下创建dir,存在会报错 FileExistsError: #os.rmdir(os.path.join(cdir, 'testdir'))#在此路径下删除dir #os.path.split('/Users/michael/testdir/file.txt')拆分路径 #os.path.splitext('/path/to/file.txt')#直接获取文件名 f0=os.path.split('/Users/michael/testdir/file.txt') print(f0[1])#file.txt f1=os.path.splitext('/path/to/file.txt') print(f1[1])#.txt print([x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py'])#输出当前目录下所有的.py文件 ''' #4.3序列化 #Python提供了pickle模块来实现序列化。 #4.3.1保存到文件 ''' import pickle d = dict(name="lijing",age=24,addres="cq") f = open('dump.txt', 'wb') pickle.dump(d,f) f.close() ''' #4.3.2从文件读取 ''' import pickle f = open('dump.txt', 'rb') d = pickle.load(f) f.close() print(d) ''' #4.4 json数据 #对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON import json d = dict(name="hello",age=24,addres="cq") e = {"name":"hello","age":24,"addres":"cq"} f = open('dump.txt', 'wb') json.dump(e,f) f.close()
7baffbe3a806925dbbc93633428f21ad6e66a202
lindaverse/edx6.00
/Week 1/problem1.py
923
3.703125
4
numbob = 0 state = 0 s = 'sjshsbobbobsdhfjkafsdjkncvakhufvjkhvckjvcjkvjdackljasvdkljvlkacsjkvljcaxklavc' for letter in s: if state == 0: if letter == "b": state = 1 elif state == 1: if letter == "o": state = 2 elif letter == "b": state = 1 else: state = 0 elif state == 2: if letter == "b": numbob += 1 state = 3 else: state = 0 elif state == 3: if letter == "o": state = 2 elif letter == "b": state = 1 else: state = 0 print(numbob) from re import findall print(len(findall("(?=bob)", s))) #----------------------------------------- numbobs = 0 for num in range(len(s)): if s[num:num+3] == "fvjkhvc": numbobs += 1 print(numbobs) #------------------------------------------ numbobs = 0 while
d63dccf64ebb313639bef486522cfea02768793e
Willian-PD/Exercicios-do-Curso-de-programacao-para-leigos-do-basico-ao-avancado
/Exercícios de python/secao-3-parte-5.py
100
3.546875
4
altura = float(input('Digite a sua altura: ')) print(f'Seu peso ideal é {(72.7 * altura) - 58}')
0a7dd139541bb011ca1303e3b4478715a6d5b119
gguilherme42/Livro-de-Python
/Cap_7/ex7.3.py
219
4.0625
4
s1 = list(input('String 1: ').upper()) s2 = list(input('String 2: ').upper()) lista = [] for l in s2: if l not in s1: lista.append(l) for l in s1: if l not in s2: lista.append(l) print(lista)
7d50efcac28c0c6b510c5759b866a1a323732365
vidhyaveera/vidhyaveeradurai
/sorted.py
109
3.5625
4
m=int(input("") n=list(map(int,input().split())) b=sorted(n) if b==n: print("yes") else: print("no")
ddfea4ef8a9c6ecc90fe1fa421cdba608a1fdb3a
CarlosVRL/daily-coding-problem
/src/tests/problem_83_tests.py
2,039
3.5
4
""" Module problem_83 tests """ import unittest import sys sys.path.append("../problems") import problem_83 class TestMethods(unittest.TestCase): def test_simple_case_is_valid(self): # Initialize the nodes a = problem_83.Node("a") b = problem_83.Node("b") c = problem_83.Node("c") # Initial Tree root = a root.left = b root.right = c # Inverted Tree expected_output = problem_83.Node("a") expected_output.left = c expected_output.right = b inverted = problem_83.invert_binary_tree(root) self.assertEqual(expected_output.val, inverted.val) self.assertEqual(expected_output.left.val, inverted.left.val) self.assertEqual(expected_output.right.val, inverted.right.val) def test_second_level_case_is_valid(self): # Initialize the nodes a = problem_83.Node("a") b = problem_83.Node("b") c = problem_83.Node("c") d = problem_83.Node("d") e = problem_83.Node("e") f = problem_83.Node("f") # Initial Tree root = a root.left = b b.left = d b.right = e root.right = c c.left = f inverted = problem_83.invert_binary_tree(root) # Inverted Tree expected_output = problem_83.Node("a") expected_output.left = c expected_output.left.right = f expected_output.right = b expected_output.right.left = e expected_output.right.right = d self.assertEqual(expected_output.val, inverted.val) self.assertEqual(expected_output.left.val, inverted.left.val) self.assertEqual(expected_output.right.val, inverted.right.val) self.assertEqual(expected_output.left.right.val, inverted.left.right.val) self.assertEqual(expected_output.right.left.val, inverted.right.left.val) self.assertEqual(expected_output.right.right.val, inverted.right.right.val) if __name__ == '__main__': unittest.main()
5e1c76466b5a4e309b8e53ced65d3f651168969e
anujns/Predictive-Analytics
/Assignment 2/Submission/mapper2.py
1,104
3.703125
4
#!/usr/bin/python3 import sys import re import string for line in sys.stdin: words = line.split() words = re.findall(r'\w+', line.strip()) length = len(words) i = 0 while (i+2 < length): first = words[i] first = first.strip(string.punctuation).lower() second = words[i+1] second = second.strip(string.punctuation).lower() third = words[i+2] third = third.strip(string.punctuation).lower() tri_temp = [first, second, third] delim = '_' if (first == 'science' or first == 'sea' or first == 'fire' or first == 'sciences' or first == 'seas' or first == 'fires'): tri_temp = ['$', second, third] tri = delim.join(tri_temp) print(tri,1) elif (second == 'science' or second == 'sea' or second == 'fire' or second == 'sciences' or second == 'seas' or second == 'fires'): tri_temp = [first, '$', third] tri = delim.join(tri_temp) print(tri,1) elif (third == 'science' or third == 'sea' or third == 'fire' or third == 'sciences' or third == 'seas' or third == 'fires'): tri_temp = [first, second, '$'] tri = delim.join(tri_temp) print(tri,1) i += 1
e465bf117aef5494bb2299f3f2aaa905fb619b52
purple-phoenix/dailyprogrammer
/python_files/project_239_game_of_threes/game_of_threes.py
1,346
4.25
4
## # Do not name variables "input" as input is an existing variable in python: # https://stackoverflow.com/questions/20670732/is-input-a-keyword-in-python # # By convention, internal functions should start with an underscore. # https://stackoverflow.com/questions/11483366/protected-method-in-python ## ## # @param operand: number to operate on. # @return boolean: If inputs are valid. ## def game_of_threes(operand: int) -> bool: # Check for invalid inputs first if operand < 1: print("Invalid input. Starting number must be greater than zero") return False if operand == 1: print(operand) return True # As prior functional blocks all return, there is no need for "elif" control blocks if _divisible_by_three(operand): print(str(operand) + " 0") return game_of_threes(int(operand / 3)) if _add_one_divisible_by_three(operand): print(str(operand) + " 1") return game_of_threes(operand + 1) if _sub_one_divisible_by_three(operand): print(str(operand) + " -1") return game_of_threes(operand - 1) def _divisible_by_three(num: int) -> bool: return num % 3 == 0 def _add_one_divisible_by_three(num: int) -> bool: return (num + 1) % 3 == 0 def _sub_one_divisible_by_three(num: int) -> bool: return (num - 1) % 3 == 0
da376b2371aaf992f321d37f8e83881d3b384a3a
csiggydev/crashcourse
/3-1_names.py
193
3.578125
4
#! /usr/bin/env python # 3-1 Names names = ['Mike', 'Jason', 'Matt'] print(names) # Print Mike only print(names[0]) # Print Jason only print(names[1]) # Print Matt only print(names[2])
447077741c6922c3a942c5f77b377f84f9f1d549
windniw/just-for-fun
/leetcode/328.py
949
3.671875
4
""" link: https://leetcode.com/problems/odd-even-linked-list problem: 给链表,要求拆分成奇数项在前,偶数项在后的形式,时间O(n),空间O(1) solution: 拆链表保存奇偶项表头和表尾 """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if not head or not head.next: return head odd_head, odd_tail, even_head, even_tail, cnt = head, head, head.next, head.next, 3 t = head.next.next while t: k = t t = t.next if cnt & 1: odd_tail.next = k odd_tail = k else: even_tail.next = k even_tail = k cnt += 1 odd_tail.next = even_head even_tail.next = None return odd_head