text
stringlengths
37
1.41M
# -*- coding:utf-8 -*- # 把变量从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling # 局限:只能用于python,并且可能不同版本的Python彼此都不兼容 # dumps():把任意对象序列化成一个bytes //dump(),直接把对象序列化后写入一个file-like Object: # loads(): 把序列化的对象反序列化写入内存 //load(),从一个file-like Object中直接反序列化出对象 import pickle d = dict(name='Bob', age=20, score=88) print(pickle.dumps(d)) with open('dump.txt', 'wb') as f: pickle.dump(d, f) with open('dump.txt', 'rb') as f: d = pickle.load(f) print(d) # JSON: # 要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML/JSON等 # JSON表示出来就是一个字符串,可以被所有语言读取 # JSON 类型 Python 类型 # {} dict # [] list # "string" str # 123.45 int/float # true/false True/False # null NULL import json d = dict(name='Bill', age=20, score=88) print(json.dumps(d)) json_str = '{"age": 20, "score": 88, "name": "Bob"}' print(json.loads(json_str))
#Lynijah Russell #Challenge! # Program that shows Fibonacci numbers up to 100th term. count = 0 numOfTerms=100 number1, number2 = 0, 1 print("Fibonacci sequence:") while (count < numOfTerms): print(number1) counting = number1 + number2 number1 = number2 number2 = counting count += 1
###1 ## ##def what_day_is_it(x): ## if x==0: ## print("Today is Sunday") ## elif x==1: ## print("Today is Monday") ## elif x==2: ## print("Today is Tuesday") ## elif x==3: ## print("Today is Wednesday") ## elif x==4: ## print("Today is Thursday") ## elif x==5: ## print("Today is Friday") ## elif x==6: ## print("Today is Saturday") ## else: ## print("You have the wrong number, try again") ## return ###2 ## ##def you_are_in_jail(day, time): ## total=day+time ## x=total%6 ## what_day_is_it(x) ## ##day = int(input("What day is it?")) ##time =int( input("How long will you be staying?")) ## ##you_are_in_jail(day,time) ###6 ##def whats_my_grade(x): ## if x>=75: ## print("First") ## elif 70<=x<75: ## print("Upper Second") ## elif 60<=x<70: ## print("Second") ## elif 50<=x<60: ## print("Third") ## elif 45<=x<50: ## print("F1 Supp") ## elif 40<=x<45: ## print("F2",) ## else: ## print("F3",) ##xs=[83,75,74.9,70, 69.9, 65, 60, 59.9, 55, 50,49.9, 45, 44.9, 40, 39.9, 2, 0] ##for i in xs: ## whats_my_grade(i) #This one is for the turtle chart import turtle xs=[48, 117, 200, 240, 160, 260, 220] def draw_bar_chart(t, height): t.left(90) t.forward(height) t.right(90) t.forward(40) t.right(90) t.forward(height) t.left(90) t.penup() t.forward(10) t.pendown() richie=turtle.Turtle() wn=turtle.Screen() wn.bgcolor("lightgreen") for i in xs: draw_bar_chart(richie, i) wn.mainloop()
# The following is/are string manipulation name = "My Name is Jesh Amera Founder and CEO of GMN" print(name) print(name.lower()) print(name.upper()) print(name.upper().isupper()) print(name.upper().islower()) print(len(name)) print(name.index("J")) print(name[10:22]) print(name.replace("GMN", "Grand Media Network"))
#!/usr/bin/python3 import math # Define the function f = lambda x : x*math.log(x) a = 1.0 # from b = 2.0 # to n = 4 # number of points -1 h = (b - a) / n odd_sum = 0.0 even_sum = 0.0 # Summing the f(x_{2j}), ie the even j numbers for j in range(2, n-1, 2): even_sum += f(a + j*h) # Summing the f(x_{2j - 1}), ie the odd j numbers for j in range(1, n, 2): odd_sum += f(a + j*h) integral = (h/3)*(f(a) + 2*even_sum + 4*odd_sum + f(b)) print("Integral = ", integral)
# -*- coding: utf-8 -*- """ Created on Tue Mar 26 15:00:00 2019 @author: sachin0922 """ class Greeter(object): lastName="" def __init__(self,name): self.name=name self.lastName=" Champ" def sayHi(self): print("Hi "+self.name+self.lastName) def sayBye(self): print("Bye "+self.name+self.lastName)
def two_sum(list, k): subtracted = set() # we create a set containing all possible k - num # since we are looking for a num in list that fulfills # num + x = k we can store all possible k - num # then, if another num2 = k - num we know that num + num2 = k for num in list: if num in subtracted: return True subtracted.add(k - num) return False print two_sum([4,7,1,-3,2], 5) # True print two_sum([5,1,2,3], 6)
from collections import defaultdict def processInstructions(filename): '''Takes in a file with instructions in the form 'reg op value if reg comparison value'. Executes the operations and returns the maximum register value at the end of the program, and the maximum register value ever reached. Registers default to a value of 0''' with open(filename,'r') as f: instructions = f.readlines() maxval = 0 regs = defaultdict(int) for instruction in instructions: reg, cmd, amt, _, cond_reg, op, cond_val = instruction.split() inc = 1 if cmd == 'inc' else -1 if eval(str(regs[cond_reg]) + op + cond_val): regs[reg] += inc * int(amt) maxval = max(maxval, regs[reg]) return max(regs.values()), maxval print(processInstructions('in.in'))
def minMaxChecksum(filename): '''Reads in a file containing lines of numeric values seperated by whitespace. Returns a 'checksum' found by summing the difference between the max and the min value in each row''' with open(filename, 'r') as f: lines = f.read().splitlines() rows = [convert(line) for line in lines] return sum([max(row) - min(row) for row in rows]) def divisionChecksum(filename): '''Reads in a file containing lines of numeric values seperated by whitespace. Returns a 'checksum' found my summing the quotient of the only possible integer division with no remainder on each line''' with open(filename, 'r') as f: lines = f.read().splitlines() orderedRows = [sorted(convert(line)) for line in lines] return sum([findDivision(row) for row in orderedRows]) def convert(line): '''Splits on whitespace and casts strings to ints''' strRow = line.split() return [int(x) for x in strRow] def findDivision(orderedRow): '''Takes in a sorted list (ascending) of ints and returns the quotient of the first successful integer division found or None if none are found''' for i in range(len(orderedRow)): divisor = orderedRow[i] for dividend in orderedRow[i+1:]: if not(dividend % divisor): return dividend // divisor
# for i in range(10): # if i == 4: # continue # print(i) # 函数/方法,自定义方法 def checkname(username): """ 自动判断账号长度时5-8位,且账号必须以小写字母开头 """ if len(username)>=5 and len(username)<=8: if username[0] in "qwertyuioplkjhgfdsazxcvbnm": print(ok) else: print("账号的首字母必须小写字母开头") else: print("账号长度仅支持5-8位") #def 方法的声明 #checkname 方法的名字 #username方法的参数 #方法的逻辑代码 checkname('2343')
# indexing/slicing in numpy array import numpy as np arr = np.array([[-1, 2, 0, 4], [4, -0.5, 6, 0], [2.6, 0, 7, 8], [3, -7, 4, 2.0] ]) print('Initial Array: ') print(arr) sliced_arr = arr[:2, ::2] print('Array with first two rows ' 'and alternate column[0 to 2]: \n', sliced_arr) Index_arr = arr[[1, 1, 0, 3], [3, 2, 1, 0]] print ("\nElements at indices (1, 3), " "(1, 2), (0, 1), (3, 0):\n", Index_arr)
import random def num_guess(): print("Guess a number between 1 and 100 inclusive.") randNum = random.randint(1,100) counter = 0 while True: try: numGuess = int(input("> ")) except: print("Please enter an integer.") break counter += 1 if numGuess < 1 or numGuess > 100: print('Please enter a valid number between 1 and 100 inclusive.') break elif numGuess == randNum: print("Congrats, you guessed the number {} correctly in {} guess(es)!".format(randNum, counter)) break elif numGuess < randNum: print("Your guess was too low. Please try again!") continue elif numGuess > randNum: print("Your guess was too high. Please try again!") continue num_guess()
import random numberofGuesses = 0 number = random.randint(1,100) name = raw_input("Hello! Who are you? ") print (name + ", I have random numbers between 1 to 100. Can you guess what number it is?") while numberofGuesses < 10: guess = raw_input("Take a guess") guess = int(guess) numberofGuesses += 1; guessesLeft = 10 - numberofGuesses; if guess < number: guessesLeft = str(guessesLeft) print("Your guess is close, you can do better! You have " + guessesLeft + " guesses Left") if guess > number: guessesLeft = str(guessesLeft) print("Your guess is way too high! You have " + guessesLeft + " guesses Left") #if guess == number: #break if guess == number: numberofGuesses = str(numberofGuesses) print ("Well done! You guessed the number correctly in " + numberofGuesses + " tries") break if guess!= number: number = str(number) print("Sorry. The number I was thinking " + number)
import random guess_num = random.randint(1,50) user_guess =input("what number did you guess?") while (int(user_guess) != guess_num): print("Ouch!it's wrong") if(int(user_guess) > guess_num): print ("Guess is high") user_guess =input("Will you try guessing again?") elif(int(user_guess) < guess_num): print ("Guess is low") user_guess =input("Will you try guessing again?") if (int(user_guess)== guess_num): print ("That's very correct")
# -*- coding: utf-8 -*- """ Created on Fri Jul 13 19:48:06 2018 @author: ntf-42 """ class Enemy: life = 3 def attack(self): print('ouch') self.life -= 1 def checkLife(self): if self.life <= 0: print("dead") else: print(str(self.life)) enmeny1 = Enemy() enmeny1.attack() enmeny1.checkLife()
# 1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем. Об # окончании ввода данных свидетельствует пустая строка. try: with open(r'files/task1.txt', "w", encoding='utf8') as task1: while True: string = input( "Введите строку для записи в файл. Для завершения ввода нажмите Enter. >>> ") if string == "": break print(string, file=task1) except IOError: print("Произошла ошибка ввода-вывода!")
# 5. Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает # фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее # сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке). # Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника. rev = int(input("Введите выручку фирмы >>> ")) exp = int(input("Введите издержки фирмы >>> ")) pr = rev - exp if pr > 0: print("Прибыль = {}; Финансовый результат - прибыль".format(pr)) ren = pr / rev print("Рентабельность выручки = {:.2f}".format(ren)) empl_num = int(input("Введите численность сотрудников фирмы >>> ")) empl_pr = pr / empl_num print("Прибыль фирмы в расчете на одного сотрудника = {:.2f}".format(empl_pr)) elif pr < 0: print("Прибыль = {:.2f}; Финансовый результат - убыток".format(pr)) else: print("Выручка равна издержкам. Финансовый результат не определен.")
# Jaden Smith, the son of Will Smith, is the star of # films such as The Karate Kid (2010) and After Earth # (2013). Jaden is also known for some of his philosophy # that he delivers via Twitter. When writing on Twitter, # he is known for almost always capitalizing every word. # For simplicity, you'll have to capitalize each word, # check out how contractions are expected to be in the example # below. # Your task is to convert strings to how they would be written # by Jaden Smith. The strings are actual quotes from Jaden Smith, # but they are not capitalized in the same way he originally typed # them. # Example: # Not Jaden-Cased: "How can mirrors be real if our eyes aren't real" # Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real" # Link to Jaden's former Twitter account @officialjaden via archive.org str = "How can mirrors be real if our eyes aren't real" def to_jaden_case(string): val = string.split(" ") phrases = [] for i in val : num = -1 words = [] for j in i : num = num + 1 if num == 0 : words.append(j.upper()) else : words.append(j) phrases.append(''.join(words)) return ' '.join(phrases) print(to_jaden_case(str))
# template for "Stopwatch: The Game" import simplegui # define global variables counter = 0 stop_time = 0 suc_time = 0 is_run = False # define helper function format that converts time # in tenths of seconds into formatted string A:BC.D def format(t): #pass int_D = t % 10 int_BC = t // 10 if int_BC >= 60: int_A = int_BC//60 int_BC = int_BC % 60 else: int_A = 0 if int_BC < 10: ft = str(int_A)+":0"+str(int_BC)+"."+str(int_D) else: ft = str(int_A)+":"+str(int_BC)+"."+str(int_D) return ft # define event handlers for buttons; "Start", "Stop", "Reset" def start_handler(): timer.start() global is_run is_run = True def stop_handler(): timer.stop() global stop_time, suc_time global is_run if is_run == True: is_run = False stop_time+=1 if counter%10 == 0: suc_time += 1 def reset_handler(): global counter, stop_time, suc_time, is_run timer.stop() is_run = False counter = 0 stop_time = 0 suc_time = 0 # define event handler for timer with 0.1 sec interval def timer_handler(): global counter counter += 1 # define draw handler def draw_handler(canvas): canvas.draw_text(format(counter), [100,150], 30, "White") canvas.draw_text(str(suc_time)+"/"+str(stop_time), [260,15],15, "White") # create frame frame = simplegui.create_frame("Stopwatch", 300, 300) # register event handlers timer = simplegui.create_timer(100, timer_handler) frame.set_draw_handler(draw_handler) frame.add_button("Start", start_handler, 100) frame.add_button("Stop", stop_handler, 100) frame.add_button("Reset", reset_handler,100) # start frame frame.start() # Please remember to review the grading rubric
# class Employee: # pass # emp=Employee() # em2=Employee() # emp='lohit' # em2='susumu terashi' # print(emp) # print(em2) # print('________________________') # # emp="Lohit" # print(emp) # print('________________________') # class Person: # pass # name=Person() # email=Person() # address=Person() # phone=Person() # name='New' # print(name) # class MyClass: # x = 5 # print(MyClass) # print('_________________________') # class MyClass: # x = 5 # p1 = MyClass() # print(p1.x) # The __init__() Function # The examples above are classes and objects in their simplest form, and are not really useful in real life applications. # To understand the meaning of classes we have to understand the built-in __init__() function. # All classes have a function called __init__(), which is always executed when the class is being initiated. # Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created: class Person: def __init__(self, name, age,email): self.name = name self.age = age self.email=email p1 = Person("John", 36,'[email protected]') print('____________________________') print(p1.name) print(p1.age) print(p1.email) # Note: The __init__() function is called automatically every time the class is being used to create a new object.
def lohit(dictionary): for key,val in dictionary.items(): print(f'Im a {key} and this is {val}') lohit_pgram= {} while True: lohit_name= input('enter name of programming') lohit_frame=input('enter the name of frame work') lohit_pgram[lohit_name]=[lohit_frame] another=input('add another program? (y/n)') if another=='y': continue else: break lohit(lohit_pgram)
def belt_count(dictionary): belts = list(dictionary.values()) for belt in belts: num = belts.count(belt) print(f'there are {num} {belt} belts ') lohit_belts = {} while True: lohit_program = input('enter name of belt :') lohit_frame = input('enter the name of belt color: ') lohit_belts[lohit_program] = [lohit_frame] another = input('add another program? (y/n)') if another == 'y': continue else: break belt_count(lohit_belts)
# this program is to increase the number of empployees each time the new emp is add class emplpyee: add_emp=0 increase=2 def __init__(self,pay,name,age): self.pay=pay self.name=name self.age=age emplpyee.add_emp+=1 def fullname(self): return '{} {}'.format(self.name,self.age) def salery_hike(self): self.pay = int(self.pay * self.increase) # countes the number of employess print(emplpyee.add_emp) lohit=emplpyee(2,'lohit',21) print(emplpyee.add_emp) rekha=emplpyee(3,'rekha',23) print(emplpyee.add_emp) lohi=emplpyee(3,2,43) #countes the number of employess print(emplpyee.add_emp)
# name=input('hello is from me:') # age=input('my age is:') # variabe=mane # print(name, age,variabe) # print(name+age) # print("helllo") name=input('tell me your name:') age=input(' and you are age is :') print("hello there" + name , "and your age is", age, 'this')
def main(): print("Python Guessing Game") print("====================\n") ans = "zebra" while True: print("I'm thinking of an animal.\n") guess = input("Enter the name of an animal: ").strip().lower() if guess == ans: print("\nCongratulations, you win!") feedback = input("\nDo you like this animal? Enter 'y' or 'n': ").strip().lower() if feedback == "y": print("\nI'm glad. Thank you for playing!") elif feedback == "n": print("\nI'm sorry you feel that way. Thank you for playing!") break elif guess[0] == "q" : print("\nThank you for playing!") break else: print("\nSorry, try again.\n") main()
"""lambdata - helper functions for cleaning dataframes""" import pandas as pd import numpy as np from sklearn.model_selection import train_test_split def null_count(df): """ Returns total amount of null values in the DataFrame. """ nulls = df.isnull().sum() return nulls def train_test_split_func(df, frac): """ Does a train-test-split using sklearn. """ train, test = train_test_split(df, train_size=frac, test_size=(1-frac), random_state=42) return train, test class ColAvg(pd.DataFrame): """ Returns average of each int columns in a given DataFrame. """ def calculate(self): avgs = [] for col in self.columns: if self[col].dtype == 'int64': avg = self[col].sum() / len(self[col]) avgs.append(avg) else: avgs.append(None) return avgs if __name__ == "__main__": pass
#!/usr/bin/python from Crypto.Cipher import AES # import AES Chiper Algorithm from termcolor import cprint #import cprint to print text with colors from Crypto.Util import Counter #import Counter to use in CTR AES mode. file_to_save = raw_input("[~]Please enter file name to save the cipher text >> ") #file to save the ciphertext key = raw_input("[~]Please Enter the key (16 or 24 or 32 byte) >> ") #KEY ctr=Counter.new(128) #counter length mode = AES.MODE_CTR #Counter Mode encryptor = AES.new(key, mode,counter=ctr) #Create a new AES cipher text = raw_input("[~]Please Enter your text >> ") #TEXT ciphertext = encryptor.encrypt(text) #encrypt the data try: f = open(file_to_save,"w") #open file to save f.write(ciphertext) # write chiper text to this file f.close() # close file cprint("[+]Chiper Text is saved to file {0}".format(file_to_save),"green") except: cprint("[!]Error while writing to {0}".format(file_to_save),"red")
class Dog: paws = 4 def __init__(self, name, age): self.name = name self.age = age @classmethod def bark(cls, times): print('The dog barks {} times and has {} paws'.format( times, cls.paws)) @staticmethod def get_description(): return 'Собака - млекопитающее с 4 лапами и хвостом. Умеет лаять' def temp(self): print('Im temp') print(Dog.bark(3)) d = Dog('Lola', 12) d.paws = 15 print(d.paws) print(d.bark(7)) print(Dog.temp()) import datetime class MyInterval: class_end = datetime.datetime.now() def __init__(self, end=None): if end is None: self.end = self.class_end def get_len(self): return self.class_end - self.end def reset_get(self): self.class_end = datetime.datetime(1991, 1, 1) my_int = MyInterval(datetime.datetime(2018,11,24,8,13,0)) print(my_int.class_end) my_int.reset_get() print(MyInterval.class_end) print(my_int.class_end)
import math class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return '({}, {})'.format(self.x, self.y) p1 = Point(-2, 2) p2 = Point(5, 5) class Line(Point): delta_x = -3 # сдвиг всего отрезка по оси ОХ: если значение положительное - вправо, отрицательное - влево, 0 - нет сдвига delta_y = 1 # сдвиг всего отрезка по оси ОУ: если значение положительное - вверх, отрицательное - вниз, 0 - нет сдвига def __repr__(self): return 'Координаты прямой: ({}, {})'.format(p1, p2) def sdvig_xy(self): self.x1 = p1.x + self.delta_x self.y1 = p1.y + self.delta_y self.x2 = p2.x + self.delta_x self.y2 = p2.y + self.delta_y return 'Координаты линии после сдвига линии на {} по ОХ, на {} по ОУ: ({}, {}),({}, {})'.format(self.delta_x, self.delta_y, self.x1, self.y1, self.x2, self.y2) def dlina(self): self.dl = '{:.2f}'.format(((p2.x-p1.x)**2 + (p2.y-p1.y)**2 )**.5) return 'Длина отрезка равна {}'.format(self.dl) def ygol(self): self.yg = math.degrees(math.atan((p2.y-p1.y)/(p2.x-p1.x))) return 'Угол наклона прямой к оси ОХ: {}'.format(self.yg) l = Line(p1, p2) print(p1) # вывод коорд точки р1 print(p2) # вывод коорд точки р2 print(l) # вывод коорд прямой l print(l.sdvig_xy()) print(l.dlina()) print(l.ygol())
from random import randint opciones = { 1: 'Piedra', 2: 'Papel', 3: 'Tijeras' } rival = opciones[randint(1, 3)] miOpcion= input() if miOpcion=='Piedra': if rival=='Piedra': print("EMPATE, Rival: {}".format(rival)) if rival=='Papel': print("GANA EL RIVAL, Rival: {}".format(rival)) if rival=='Tijeras': print("GANAS TÚ, Rival: {}".format(rival)) elif miOpcion=='Papel': if rival=='Piedra': print("GANAS TÚ, Rival: {}".format(rival)) if rival=='Papel': print("EMPATE, Rival: {}".format(rival)) if rival=='Tijeras': print("GANA EL RIVAL, Rival: {}".format(rival)) elif miOpcion=='Tijeras': if rival=='Piedra': print("GANA EL RIVAL, Rival: {}".format(rival)) if rival=='Papel': print("GANAS TÚ, Rival: {}".format(rival)) if rival=='Tijeras': print("EMPATE, Rival: {}".format(rival))
# connect4.py # --------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to Clemson University and the authors. # # Authors: Pei Xu ([email protected]) and Ioannis Karamouzas ([email protected]) # """ Project 3: Adversarial Games Team Members: 1: Kalpit Vadnerkar 2: Dhananjay Nikam """ """ In this assignment, the task is to implement the minimax algorithm with depth limit for a Connect-4 game. To complete the assignment, you must finish these functions: minimax (line 196), alphabeta (line 237), and expectimax (line 280) in this file. In the Connect-4 game, two players place discs in a 6-by-7 board one by one. The discs will fall straight down and occupy the lowest available space of the chosen column. The player wins if four of his or her discs are connected in a line horizontally, vertically or diagonally. See https://en.wikipedia.org/wiki/Connect_Four for more details about the game. A Board() class is provided to simulate the game board. It has the following properties: b.rows # number of rows of the game board b.cols # number of columns of the game board b.PLAYER1 # an integer flag to represent the player 1 b.PLAYER2 # an integer flag to represent the player 2 b.EMPTY_SLOT # an integer flag to represent an empty slot in the board; and the following methods: b.terminal() # check if the game is terminal # terminal means draw or someone wins b.has_draw() # check if the game is a draw w = b.who_wins() # return the winner of the game or None if there # is no winner yet # w should be in [b.PLAYER1,b.PLAYER2, None] b.occupied(row, col) # check if the slot at the specific location is # occupied x = b.get(row, col) # get the player occupying the given slot # x should be in [b.PLAYER1, b.PLAYER2, b.EMPTY_SLOT] row = b.row(r) # get the specific row of the game described using # b.PLAYER1, b.PLAYER2 and b.EMPTY_SLOT col = b.column(r) # get a specific column of the game board b.placeable(col) # check if a disc can be placed at the specific # column b.place(player, col) # place a disc at the specific column for player # raise ValueError if the specific column does not have available space new_board = b.clone() # return a new board instance having the same # disc placement with b str = b.dump() # a string to describe the game board using # b.PLAYER1, b.PLAYER2 and b.EMPTY_SLOT Hints: 1. Depth-limited Search We use depth-limited search in the current code. That is we stop the search forcefully, and perform evaluation directly not only when a terminal state is reached but also when the search reaches the specified depth. 2. Game State Three elements decide the game state. The current board state, the player that needs to take an action (place a disc), and the current search depth (remaining depth). 3. Evaluation Target The minimax algorithm always considers that the adversary tries to minimize the score of the max player, for whom the algorithm is called initially. The adversary never considers its own score at all during this process. Therefore, when evaluating nodes, the target should always be the max player. 4. Search Result The pesudo code provided in the slides only returns the best utility value. However, in practice, we need to select the action that is associated with this value. Here, such action is specified as the column in which a disc should be placed for the max player. Therefore, for each search algorithm, you should consider all valid actions for the max player, and return the one that leads to the best value. """ # use math library if needed import math import random def get_child_boards(player, board): """ Generate a list of succesor boards obtained by placing a disc at the given board for a given player Parameters ---------- player: board.PLAYER1 or board.PLAYER2 the player that will place a disc on the board board: the current board instance Returns ------- a list of (col, new_board) tuples, where col is the column in which a new disc is placed (left column has a 0 index), and new_board is the resulting board instance """ res = [] for c in range(board.cols): if board.placeable(c): tmp_board = board.clone() tmp_board.place(player, c) res.append((c, tmp_board)) return res def evaluate(player, board): """ This is a function to evaluate the advantage of the specific player at the given game board. Parameters ---------- player: board.PLAYER1 or board.PLAYER2 the specific player board: the board instance Returns ------- score: float a scalar to evaluate the advantage of the specific player at the given game board """ adversary = board.PLAYER2 if player == board.PLAYER1 else board.PLAYER1 # Initialize the value of scores # [s0, s1, s2, s3, --s4--] # s0 for the case where all slots are empty in a 4-slot segment # s1 for the case where the player occupies one slot in a 4-slot line, the rest are empty # s2 for two slots occupied # s3 for three # s4 for four score = [0]*5 adv_score = [0]*5 # Initialize the weights # [w0, w1, w2, w3, --w4--] # w0 for s0, w1 for s1, w2 for s2, w3 for s3 # w4 for s4 weights = [0, 1, 4, 16, 1000] # Obtain all 4-slot segments on the board seg = [] invalid_slot = -1 left_revolved = [ [invalid_slot]*r + board.row(r) + \ [invalid_slot]*(board.rows-1-r) for r in range(board.rows) ] right_revolved = [ [invalid_slot]*(board.rows-1-r) + board.row(r) + \ [invalid_slot]*r for r in range(board.rows) ] for r in range(board.rows): # row row = board.row(r) for c in range(board.cols-3): seg.append(row[c:c+4]) for c in range(board.cols): # col col = board.col(c) for r in range(board.rows-3): seg.append(col[r:r+4]) for c in zip(*left_revolved): # slash for r in range(board.rows-3): seg.append(c[r:r+4]) for c in zip(*right_revolved): # backslash for r in range(board.rows-3): seg.append(c[r:r+4]) # compute score for s in seg: if invalid_slot in s: continue if adversary not in s: score[s.count(player)] += 1 if player not in s: adv_score[s.count(adversary)] += 1 reward = sum([s*w for s, w in zip(score, weights)]) penalty = sum([s*w for s, w in zip(adv_score, weights)]) return reward - penalty def minimax(player, board, depth_limit): """ Minimax algorithm with limited search depth. Parameters ---------- player: board.PLAYER1 or board.PLAYER2 the player that needs to take an action (place a disc in the game) board: the current game board instance depth_limit: int the tree depth that the search algorithm needs to go further before stopping max_player: boolean Returns ------- placement: int or None the column in which a disc should be placed for the specific player (counted from the most left as 0) None to give up the game """ max_player = player placement = None next_player = board.PLAYER2 if player == board.PLAYER1 else board.PLAYER1 score = -math.inf ### Please finish the code below ############################################## ############################################################################### def value(player, board, depth_limit): if depth_limit == 0 or board.terminal(): return [evaluate(max_player, board), None] if player == max_player: return max_value(player,board,depth_limit) else: return min_value(player,board,depth_limit) def max_value(player, board, depth_limit): v = -math.inf for child in get_child_boards(player, board): next_value = value(next_player, child[1], depth_limit-1)[0] if v <= next_value: v = next_value action = child[0] return [v, action] def min_value(player, board, depth_limit): v = math.inf for child in get_child_boards(player, board): next_value = value(max_player, child[1], depth_limit-1)[0] if v >= next_value: v = next_value action = child[0] return [v, action] score, placement = value(player, board, depth_limit) ############################################################################### return placement def alphabeta(player, board, depth_limit): """ Minimax algorithm with alpha-beta pruning. Parameters ---------- player: board.PLAYER1 or board.PLAYER2 the player that needs to take an action (place a disc in the game) board: the current game board instance depth_limit: int the tree depth that the search algorithm needs to go further before stopping alpha: float beta: float max_player: boolean Returns ------- placement: int or None the column in which a disc should be placed for the specific player (counted from the most left as 0) None to give up the game """ max_player = player placement = None next_player = board.PLAYER2 if player == board.PLAYER1 else board.PLAYER1 score = -math.inf ### Please finish the code below ############################################## ############################################################################### def value(player, board, depth_limit, alpha, beta): if depth_limit == 0 or board.terminal(): return [evaluate(max_player, board), None] if player == max_player: return max_value(player, board, depth_limit, alpha, beta) else: return min_value(player, board, depth_limit, alpha, beta) def max_value(player, board, depth_limit, alpha, beta): v = -math.inf for child in get_child_boards(player, board): next_value = value(next_player, child[1], depth_limit-1, alpha, beta)[0] if v <= next_value: v = next_value action = child[0] if v >= beta: return [v, action] alpha = max(alpha, v) return [v, action] def min_value(player, board, depth_limit, alpha, beta): v = math.inf for child in get_child_boards(player, board): next_value = value(max_player, child[1], depth_limit-1, alpha, beta)[0] if v >= next_value: v = next_value action = child[0] if v <= alpha: return [v, action] beta = max(beta, v) return [v, action] score, placement = value(player, board, depth_limit, -math.inf, math.inf) ############################################################################### return placement def expectimax(player, board, depth_limit): """ Expectimax algorithm. We assume that the adversary of the initial player chooses actions uniformly at random. Say that it is the turn for Player 1 when the function is called initially, then, during search, Player 2 is assumed to pick actions uniformly at random. Parameters ---------- player: board.PLAYER1 or board.PLAYER2 the player that needs to take an action (place a disc in the game) board: the current game board instance depth_limit: int the tree depth that the search algorithm needs to go before stopping max_player: boolean Returns ------- placement: int or None the column in which a disc should be placed for the specific player (counted from the most left as 0) None to give up the game """ max_player = player placement = None next_player = board.PLAYER2 if player == board.PLAYER1 else board.PLAYER1 score = -math.inf ### Please finish the code below ############################################## ############################################################################### def value(player, board, depth_limit): if depth_limit == 0 or board.terminal(): return [evaluate(max_player, board), None] if player == max_player: return max_value(player,board,depth_limit) else: return exp_value(player,board,depth_limit) def max_value(player, board, depth_limit): v = -math.inf for child in get_child_boards(player, board): next_value = value(next_player, child[1], depth_limit-1)[0] if v <= next_value: v = next_value action = child[0] return [v, action] def exp_value(player, board, depth_limit): v = 0 actions = [] probability = 1/(len(get_child_boards(player, board))) for child in get_child_boards(player, board): v += probability * value(next_player, child[1], depth_limit-1)[0] actions.append(child[0]) return [v, random.choice(actions)] score, placement = value(player, board, depth_limit) ############################################################################### return placement if __name__ == "__main__": from utils.app import App import tkinter algs = { "Minimax": minimax, "Alpha-beta pruning": alphabeta, "Expectimax": expectimax } root = tkinter.Tk() App(algs, root) root.mainloop()
# Multiple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, -1].values print(X) # Encoding categorical data from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [3])], remainder='passthrough') X = np.array(ct.fit_transform(X)) print(X) X = X[:,1:] X = np.append(arr = np.ones((50,1)).astype(float),values=X,axis=1) import statsmodels.api as sm X_opt = X[:,[0,3,5]] X_opt = np.array(X_opt, dtype=float) regressor_OLS = sm.OLS(endog=y, exog=X_opt).fit() regressor_OLS.summary() # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_opt, y, test_size = 0.2, random_state = 0) # Training the Multiple Linear Regression model on the Training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) # Predicting the Test set results y_pred = regressor.predict(X_test) np.set_printoptions(precision=2) print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))
class Tool(object): # 使用赋值语句定义类属性,记录创建工具对象的总数 count = 0 def __init__(self,name): self.name = name # 让类属性的值+1 Tool.count += 1 @classmethod def tool_show_count(cls): print("创建了%d"%Tool.count) print("创建了%d"%cls.count) # 1.创建工具对象 tool1 = Tool("斧头") tool2 = Tool("榔头") tool3 = Tool("水桶") Tool.tool_show_count() # 2.输出工具对象的总数 # print(Tool.count) # tool1.count = 4 # print(Tool.count) # print(tool1.count) # print(tool2.count)
class Dog(): # __init__ 叫初始化化方法 魔法方法(系统方法) def __init__(self,new_name): # 属性 self.name = new_name def print_self_name(self): print(self.name) def print_self_color(self,color): return color dog1 = Dog('张三') dog1.print_self_name() dog1.color = "yellow" print(id(dog1)) print(dog1.color) print(dog1.print_self_color('yellow')) print("*"*20) dog2 = Dog("李四") dog2.print_self_name() print(id(dog2))
class Car(): def move(self): print('移动') def stop(self): print('停止') bwm = Car() bwm.move() bwm.stop() print('*'*20) bc = Car() bc.move() bc.stop() print('*'*20) qq = Car() qq.move() qq.stop()
class SweetPotato(object): """烤地瓜类""" def __init__(self): # 这个属性是地瓜的生熟程度 self.cookedLever = 0 # 返回给用户的字符串 self.cookedString = "生的" # 地瓜的配料列表 self.condiments = [] def __str__(self): msg = "" if len(self.condiments) >0: for test in self.condiments: msg = msg + test return_msg = "当前的地瓜是%s,调料有%s"%(self.cookedString,msg) return return_msg def addCondiments(self,name): self.condiments.append(name) def cook(self,time): """这是烤地瓜的方法,需要给我传时间""" self.cookedLever += time if self.cookedLever>8: self.cookedString = "烤糊了" elif self.cookedLever>5: self.cookedString = "烤熟了" elif self.cookedLever>3: self.cookedString = "半生不熟" else: self.cookedString = "生的" djs_kaodigua = SweetPotato() djs_kaodigua.cook(3) djs_kaodigua.addCondiments("番茄酱") print(djs_kaodigua) djs_kaodigua.cook(1) djs_kaodigua.addCondiments("汁") print(djs_kaodigua)
from datetime import datetime data = [] with open('/home/pi/Programming/AdventOfCode/2020/Day10/test_input_short.txt','r') as f: data = [int(i.strip()) for i in f.readlines()] data.append(0) data.sort() volt_dict = {1:0,3:1} # 3:1 exists because our phone has a default +3 setting previous_voltage = 0 for adapter in data: volt_difference = adapter - previous_voltage previous_voltage = adapter if volt_difference in volt_dict: volt_dict[volt_difference] += 1 else: volt_dict[volt_difference] = 1 # data = [1,4,5,6] data.append(data[-1]+3) print(data) print(volt_dict) adapter_dict = {} def search_adapters(index): if index in adapter_dict: # we've already discovered this return adapter_dict[index] elif index == len(data) - 1: # Success!, We've hit the last node return 1 elif index >= len(data): # We've gone too far return 0 else: # We take the next three indexes on the list a,b,c = index +1, index +2, index +3 current_targets = [data[index]+1, data[index]+2, data[index]+3] val_a, val_b, val_c = 0,0,0 if (data[index+1]) in current_targets: val_a = search_adapters(a) if (index+2 < len(data)) and (data[index + 2]) in current_targets: val_b = search_adapters(b) if (index+3 < len(data)) and (data[index + 3]) in current_targets: val_c = search_adapters(c) current_values = val_a + val_b + val_c adapter_dict[index] = current_values return current_values start = datetime.now() print(search_adapters(0)) print(dict(sorted(adapter_dict.items()))) time = datetime.now() - start print(time)
import time def set_up(data): nodeA = Node(data[0]) prevNode = nodeA lastNode = None for i in range(1,len(data)): newNode = Node(data[i]) prevNode.right = newNode prevNode = newNode lastNode = newNode lastNode.right = nodeA nodeA.left = lastNode return nodeA def set_up_part2(data): nodeA = Node(data[0]) prevNode = nodeA lastNode = None for i in range(1,len(data)): newNode = Node(data[i]) prevNode.right = newNode prevNode = newNode lastNode = newNode for i in range(10,1000001): newNode = Node(i) prevNode.right = newNode prevNode = newNode lastNode = newNode lastNode.right = nodeA nodeA.left = lastNode return nodeA class Node: def __init__(self, val): self.val = int(val) self.left = None self.right = None def __repr__(self): return str(self.val) def __str__(self): return str(self.val) def display(self): rtnString = str(self.val) nxtNode = self.right while nxtNode.val != self.val: rtnString += str(nxtNode.val) nxtNode = nxtNode.right return rtnString def move(current_cup, maxi, node_dict): # Splice three cups to the right spliced_start = current_cup.right spliced_stop = current_cup.right.right.right spliced_values = [spliced_start.val, spliced_start.right.val, spliced_stop.val] #Connect the current cup to the cup after the splice spliced_stop.right.left = current_cup current_cup.right = spliced_stop.right next_cup = current_cup.right original_value = current_cup.val value = maxi for i in range (current_cup.val-1, current_cup.val -4, -1): if i not in spliced_values: value = i break if value <=0: value = maxi while value in spliced_values: value -= 1 # maxi = current_cup.val # while value != next_cup.val: # # if next_cup.val == original_value: # # value -= 1 # # if value <= 0: # # value = maxi # # if maxi < next_cup.val: # # maxi = next_cup.val # next_cup = next_cup.right next_cup = node_dict[value] next_cup.right.left = spliced_stop spliced_stop.right = next_cup.right next_cup.right = spliced_start spliced_start.left = next_cup return current_cup.right if __name__=='__main__': # sample = '389125467' sample = '853192647' # part 1 # a = set_up(sample) # start_node = a # node_dict = {a.val:a} # a = a.right # while a != start_node: # node_dict[a.val] = a # a = a.right # for i in range(2,102): # a = move(a,9, node_dict) # print(f'{i} : {a.display()}') # print(a.display()) # while a.val != 1: # a = a.right # print(a.display()) # part 2 start = time.time() print(f'Start: {start}') a = set_up_part2(sample) # print(a.display()) print('Creating Node Dictionary') start_node = a node_dict = {a.val:a} a = a.right while a != start_node: node_dict[a.val] = a a = a.right print('Parsed input') currentloop = time.time()+ 30 last_i = 2 highestNode = max(node_dict) print(highestNode) for i in range(2,10000002): a = move(a, highestNode, node_dict) if time.time() > currentloop: loop_time = time.time() - (currentloop - 30) remaining_seconds = ((10000002 - i)/ (i-last_i)) * loop_time print(f'{i}/10000002 in {time.time()- start} seconds. {round(loop_time)} for {i - last_i } values. Estimate {round(remaining_seconds)/60} minutes remaining') last_i = i currentloop = time.time()+ 30 # print(f'{i} : {a.display()}') # print(a.display()) while a.val != 1: a = a.right # print(a.display()) print(f"Finished in {round(time.time()- start)} seconds") print(a.right.val, a.right.right.val, "=", a.right.val * a.right.right.val)
import math directions = { 'E':{ 'move':(1,0), 'degrees':90 }, 'W':{ 'move':(-1,0), 'degrees':270 }, 'N':{ 'move':(0,-1), 'degrees':0 }, 'S':{ 'move':(0,1), 'degrees':180 } } directions_two = { 'E':{ 'move':(1,0), 'degrees':90 }, 'W':{ 'move':(-1,0), 'degrees':270 }, 'N':{ 'move':(0,1), 'degrees':0 }, 'S':{ 'move':(0,-1), 'degrees':180 } } def getData(fileName = 'input.txt'): data = [] with open(fileName) as f: data = f.read().splitlines() return data def change_course(course, change, action): degrees = directions[course]['degrees'] if action == 'R': degrees = (degrees + change)%360 else: degrees = (degrees - change)%360 # degrees = (degrees + change)%360 for k,v in directions.items(): if v['degrees'] == degrees: return k print('Failed to find change_course()') return None def rotate_waypoint(x,y ,action, value): # change = change % 360 # if change not in [0,90,180,270]: # print('Failed in rotate_waypoint') # return waypoint # y = y * -1 # Our grid is flipped (it's like an array ) if action == 'R': value *= -1 # X' = x*cos(theta) - y*sin(theta) # Y' = y*cos(theta) + x*sin(theta) value = math.radians(value) x1 = x*math.cos(value) - y * math.sin(value) y1 = y*math.cos(value) + x*math.sin(value) return (round(x1), round(y1)) def partOne(data): x,y = 0,0 course = 'E' for line in data: action = line[0] value = int(line[1:]) if action == 'F': x += directions[course]['move'][0] * value y += directions[course]['move'][1] * value elif action in 'NSEW': x += directions[action]['move'][0] * value y += directions[action]['move'][1] * value elif action in 'LR': course = change_course(course, value, action) # x += directions[course]['move'][0] * value # y += directions[course]['move'][1] * value else: 'Something went wrong in partOne()' print(f'x,y: {x,y}') print(f'Manhattan distance: {abs(x)+abs(y)}') def partTwo(data): ship_position = {'x':0,'y':0} way_point = {'x':10,'y':1} for line in data: action = line[0] value = int(line[1:]) if action in 'NSEW': # move way_point NSEW way_point['x'] += directions_two[action]['move'][0] * value way_point['y'] += directions_two[action]['move'][1] * value if action in 'RL': #rotate way_point new_coords = rotate_waypoint(way_point['x'],way_point['y'], action, value) way_point['x'] = new_coords[0] way_point['y'] = new_coords[1] if action == 'F': # move ship towards waypoint ship_position['x'] += way_point['x'] * value ship_position['y'] += way_point['y'] * value # print(f'{line} :: {ship_position} - waypoint {way_point}') print(f'Ship position: {ship_position} - waypoint {way_point}') print(f"Manhattan distance: {abs(ship_position['x']) + abs(ship_position['y'])}") return ship_position if __name__=='__main__': data = getData('/home/pi/Programming/AdventOfCode/2020/Day12/input.txt') # data = ['E10','W10','N10','S10','F10', 'R90', 'F10'] # data = ['F10','N3','F7', 'R90','F11'] # partOne(data) partTwo(data)
xiaoming_dic = {"name": "小明", "age": 18, "gender": True, "height": 1.75} # 1、从字典中取值 print(xiaoming_dic["name"]) # 2、增加/修改 xiaoming_dic["age"] = 19 xiaoming_dic["name1"] = "小小明" # 3、删除 xiaoming_dic.pop("name") # 统计键值对数量 print(len(xiaoming_dic)) # 合并字典 temp_dic = {"weight": 70, "height": 176} xiaoming_dic.update(temp_dic) print(xiaoming_dic) for keys in xiaoming_dic: print("%s: %s" % (keys, xiaoming_dic[keys])) print("%s 的年龄是%s, 身高是%s" % (xiaoming_dic["name1"], xiaoming_dic["age"], xiaoming_dic["height"]))
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 01:12:01 2020 @author: Logan Rowe Given an array of integers, find the maximal absolute difference between any two of its adjacent elements. Example For inputArray = [2, 4, 1, 0], the output should be arrayMaximalAdjacentDifference(inputArray) = 3. Input/Output [execution time limit] 4 seconds (py3) [input] array.integer inputArray Guaranteed constraints: 3 ≤ inputArray.length ≤ 10, -15 ≤ inputArray[i] ≤ 15. [output] integer The maximal absolute difference. """ import numpy as np def arrayMaximalAdjacentDifference(inputArray): inputArray=np.array(inputArray) diff=inputArray[1:]-inputArray[:-1] minimum=min(diff) maximum=max(diff) if -minimum>maximum: return(-minimum) else: return(maximum)
# -*- coding: utf-8 -*- """ Created on Thu Feb 27 23:56:31 2020 @author: Logan Rowe Given two arrays of integers a and b, obtain the array formed by the elements of a followed by the elements of b. Example For a = [2, 2, 1] and b = [10, 11], the output should be concatenateArrays(a, b) = [2, 2, 1, 10, 11]. Input/Output [execution time limit] 4 seconds (py3) [input] array.integer a Guaranteed constraints: 1 ≤ a.length ≤ 10, 1 ≤ a[i] ≤ 15. [input] array.integer b Guaranteed constraints: 0 ≤ b.length ≤ 10, 1 ≤ b[i] ≤ 15. [output] array.integer """ def concatenateArrays(a, b): c=a+b return c
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 01:03:45 2020 @author: Logan Rowe Call two arms equally strong if the heaviest weights they each are able to lift are equal. Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms. Given your and your friend's arms' lifting capabilities find out if you two are equally strong. Example For yourLeft = 10, yourRight = 15, friendsLeft = 15, and friendsRight = 10, the output should be areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = true; For yourLeft = 15, yourRight = 10, friendsLeft = 15, and friendsRight = 10, the output should be areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = true; For yourLeft = 15, yourRight = 10, friendsLeft = 15, and friendsRight = 9, the output should be areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = false. Input/Output [execution time limit] 4 seconds (py3) [input] integer yourLeft A non-negative integer representing the heaviest weight you can lift with your left arm. Guaranteed constraints: 0 ≤ yourLeft ≤ 20. [input] integer yourRight A non-negative integer representing the heaviest weight you can lift with your right arm. Guaranteed constraints: 0 ≤ yourRight ≤ 20. [input] integer friendsLeft A non-negative integer representing the heaviest weight your friend can lift with his or her left arm. Guaranteed constraints: 0 ≤ friendsLeft ≤ 20. [input] integer friendsRight A non-negative integer representing the heaviest weight your friend can lift with his or her right arm. Guaranteed constraints: 0 ≤ friendsRight ≤ 20. [output] boolean true if you and your friend are equally strong, false otherwise. """ def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight): if max(yourLeft,yourRight)==max(friendsLeft,friendsRight) and min(yourLeft,yourRight)==min(friendsLeft,friendsRight): return True else: return False
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 00:57:59 2020 @author: Logan Rowe Given a string, find out if its characters can be rearranged to form a palindrome. Example For inputString = "aabb", the output should be palindromeRearranging(inputString) = true. We can rearrange "aabb" to make "abba", which is a palindrome. Input/Output [execution time limit] 4 seconds (py3) [input] string inputString A string consisting of lowercase English letters. Guaranteed constraints: 1 ≤ inputString.length ≤ 50. [output] boolean true if the characters of the inputString can be rearranged to form a palindrome, false otherwise. """ ''' thoughts: this one seems faily straight forward: 1) check each character to see if it occurs an even number of times 2) up to 1 character may occur an odd numer of times ''' def palindromeRearranging(inputString): #track how many characters occur an odd number of times odd_char=0 #track letters already checked letters=[] for letter in inputString: if letter in letters: continue if inputString.count(letter)%2==1: odd_char+=1 letters.append(letter) else: letters.append(letter) if odd_char>1: return False else: return True
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 23:39:18 2020 @author: Logan Rowe Given an array of equal-length strings, you'd like to know if it's possible to rearrange the order of the elements in such a way that each consecutive pair of strings differ by exactly one character. Return true if it's possible, and false if not. Note: You're only rearranging the order of the strings, not the order of the letters within the strings! Example For inputArray = ["aba", "bbb", "bab"], the output should be stringsRearrangement(inputArray) = false. There are 6 possible arrangements for these strings: ["aba", "bbb", "bab"] ["aba", "bab", "bbb"] ["bbb", "aba", "bab"] ["bbb", "bab", "aba"] ["bab", "bbb", "aba"] ["bab", "aba", "bbb"] None of these satisfy the condition of consecutive strings differing by 1 character, so the answer is false. For inputArray = ["ab", "bb", "aa"], the output should be stringsRearrangement(inputArray) = true. It's possible to arrange these strings in a way that each consecutive pair of strings differ by 1 character (eg: "aa", "ab", "bb" or "bb", "ab", "aa"), so return true. Input/Output [execution time limit] 4 seconds (py3) [input] array.string inputArray A non-empty array of strings of lowercase letters. Guaranteed constraints: 2 ≤ inputArray.length ≤ 10, 1 ≤ inputArray[i].length ≤ 15. [output] boolean Return true if the strings can be reordered in such a way that each neighbouring pair of strings differ by exactly one character (false otherwise). """ ''' Thoughts: 1) create a dictionary for whree each string is a key and its value is True if there is at least 1 other string with 1 or less character difference 2) If any string returns False then return False ''' import numpy as np from itertools import permutations def stringsRearrangement(inputArray): inputArray=np.array(inputArray) #Build a dictionary consisting of all other strings within one permutation #i.e. {'abc':['abb','bbc','aac','abc',...]} string_dict={} #iterate through strings comparing each key string to all other strings for idx in range(len(inputArray)): key=inputArray[idx] string_dict[key]=[] for string in np.concatenate([inputArray[:idx],inputArray[idx+1:]]): #check to see if key is within one letter of the string count=np.sum([k!=s for (k,s) in zip(key,string)]) #do not add value to key if value==key or 2 or more letters are different if count>1 or count==0: continue else: #Add string to dictionary as a value if it is within 1 letter from the key string_dict[key]+=[string] #from now on we do not need to compute whether string1 is within 1 letter change from #string2 since it is stored in our dictionary #Given that there will be 10 strings or less in the given input array #it is not too expensive to check all possible permutations arr_len=len(inputArray) for permutation in list(permutations(range(arr_len))): #order inputArray values according to each permutation arr=inputArray[np.array(permutation)] #Count how many adjacent strings are more than 1 letter different discontinuities=np.sum([arr[idx+1] not in string_dict[arr[idx]] for idx in range(arr_len-1)]) if discontinuities==0: #Made it to the end of the permutation and found no discontinuities. A solution exists! return True #Went through all permutations and all of them had at least one discontinuity. No solution exists. return False if __name__=="__main__": inputArrays=[["aba", "bbb", "bab"],["ab", "bb", "aa"],["ab", "ad", "ef", "eg"]] results=[False,True,False] for (inputArray,result) in zip(inputArrays,results): if stringsRearrangement(inputArray)==result: print("passed test") else: print('actual:',str(result)) print()
# -*- coding: utf-8 -*- """ Created on Wed Feb 12 14:23:10 2020 @author: Logan Rowe Given a string, return its encoding defined as follows: First, the string is divided into the least possible number of disjoint substrings consisting of identical characters for example, "aabbbc" is divided into ["aa", "bbb", "c"] Next, each substring with length greater than one is replaced with a concatenation of its length and the repeating character for example, substring "bbb" is replaced by "3b" Finally, all the new strings are concatenated together in the same order and a new string is returned. Example For s = "aabbbc", the output should be lineEncoding(s) = "2a3bc". Input/Output [execution time limit] 4 seconds (py3) [input] string s String consisting of lowercase English letters. Guaranteed constraints: 4 ≤ s.length ≤ 15. [output] string Encoded version of s. """ def lineEncoding(s): split_letters='' prev_letter=s[0] for letter in s: if letter==prev_letter: split_letters+=letter else: split_letters+=','+letter prev_letter=letter encoded_list=[str(len(i))+i[0] for i in split_letters.split(',')] idx=0 for i in encoded_list: if i[0]=='1' and len(i)==2: encoded_list[idx]=i[1] idx+=1 encoded_string=''.join(encoded_list) return(encoded_string) if __name__=='__main__': strings = ["aabbbc",'ccccccccccccccc'] for s in strings: print(lineEncoding(s))
# -*- coding: utf-8 -*- """ Created on Sun Feb 9 17:24:15 2020 @author: Logan Rowe Given an array of strings, return another array containing all of its longest strings. Example For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be allLongestStrings(inputArray) = ["aba", "vcd", "aba"]. Input/Output [execution time limit] 4 seconds (py3) [input] array.string inputArray A non-empty array. Guaranteed constraints: 1 ≤ inputArray.length ≤ 10, 1 ≤ inputArray[i].length ≤ 10. [output] array.string Array of the longest strings, stored in the same order as in the inputArray. """ def allLongestStrings(inputArray): #Find the longest string in the input array L=[len(string) for string in inputArray] L=max(L) #Make a new array consisting of the longest strings in the initial array new_L=[string for string in inputArray if len(string)==L] return(new_L)
# -*- coding: utf-8 -*- """ Created on Thu Feb 27 23:58:56 2020 @author: Logan Rowe Remove a part of a given array between given 0-based indexes l and r (inclusive). Example For inputArray = [2, 3, 2, 3, 4, 5], l = 2, and r = 4, the output should be removeArrayPart(inputArray, l, r) = [2, 3, 5]. Input/Output [execution time limit] 4 seconds (py3) [input] array.integer inputArray Guaranteed constraints: 2 ≤ inputArray.length ≤ 104, -105 ≤ inputArray[i] ≤ 105. [input] integer l Left index of the part to be removed (0-based). Guaranteed constraints: 0 ≤ l ≤ r. [input] integer r Right index of the part to be removed (0-based). Guaranteed constraints: l ≤ r < inputArray.length. [output] array.integer """ def removeArrayPart(inputArray, l, r): return inputArray[:l]+inputArray[r+1:]
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 22:09:37 2020 @author: Logan Rowe Check if all digits of the given integer are even. Example For n = 248622, the output should be evenDigitsOnly(n) = true; For n = 642386, the output should be evenDigitsOnly(n) = false. Input/Output [execution time limit] 4 seconds (py3) [input] integer n Guaranteed constraints: 1 ≤ n ≤ 109. [output] boolean true if all digits of n are even, false otherwise. [Python3] Syntax Tips """ def evenDigitsOnly(n): n=str(n) for integer in n: if integer%2!=0: return False return Truedef evenDigitsOnly(n): n=str(n) for integer in n: if int(integer)%2!=0: return False return True
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 00:22:32 2020 @author: Logan Rowe Given a rectangular matrix of characters, add a border of asterisks(*) to it. Example For picture = ["abc", "ded"] the output should be addBorder(picture) = ["*****", "*abc*", "*ded*", "*****"] Input/Output [execution time limit] 4 seconds (py3) [input] array.string picture A non-empty array of non-empty equal-length strings. Guaranteed constraints: 1 ≤ picture.length ≤ 100, 1 ≤ picture[i].length ≤ 100. [output] array.string The same matrix of characters, framed with a border of asterisks of width 1. """ import numpy as np def addBorder_arr(picture): picture=np.array(picture) width=len(picture[0]) height=len(picture) #let us make a new array that is the known size of the bordered picture #so as to conserve memory new_picture=np.full((height+2,width+2),'*') #Fill the inside with the original picture new_picture[1:-1,1:-1]=picture return(new_picture) ''' We are given a list not a matrix so below is the solution used to satisfy CodeSignal ''' def addBorder(picture): width=len(picture[0])+2 new_picture=['*'*width] for row in picture: new_picture.append('*'+row+'*') new_picture.append('*'*width) return(new_picture) if __name__=='__main__': picture=['abc','def'] for i in picture: print(i) print() for i in addBorder(picture): print(i)
# -*- coding: utf-8 -*- """ Created on Sun Feb 16 13:09:37 2020 @author: Logan Rowe You are given an array of up to four non-negative integers, each less than 256. Your task is to pack these integers into one number M in the following way: The first element of the array occupies the first 8 bits of M; The second element occupies next 8 bits, and so on. Return the obtained integer M. Note: the phrase "first bits of M" refers to the least significant bits of M - the right-most bits of an integer. For further clarification see the following example. Example For a = [24, 85, 0], the output should be arrayPacking(a) = 21784. An array [24, 85, 0] looks like [00011000, 01010101, 00000000] in binary. After packing these into one number we get 00000000 01010101 00011000 (spaces are placed for convenience), which equals to 21784. Input/Output [execution time limit] 4 seconds (py3) [input] array.integer a Guaranteed constraints: 1 ≤ a.length ≤ 4, 0 ≤ a[i] < 256. [output] integer """ def arrayPacking(a): M='' leading_zeros='0'*8 for value in a[::-1]: binary_value=bin(value)[2:] M+=leading_zeros[:-len(binary_value)]+binary_value return(int(M,2)) if __name__=='__main__': a = [24, 85, 0] print(arrayPacking(a))
# -*- coding: utf-8 -*- """ Created on Tue Feb 11 17:31:25 2020 @author: Logan Rowe Given the positions of a white bishop and a black pawn on the standard chess board, determine whether the bishop can capture the pawn in one move. The bishop has no restrictions in distance for each move, but is limited to diagonal movement. Check out the example below to see how it can move: Example For bishop = "a1" and pawn = "c3", the output should be bishopAndPawn(bishop, pawn) = true. For bishop = "h1" and pawn = "h3", the output should be bishopAndPawn(bishop, pawn) = false. Input/Output [execution time limit] 4 seconds (py3) [input] string bishop Coordinates of the white bishop in the chess notation. Guaranteed constraints: bishop.length = 2, 'a' ≤ bishop[0] ≤ 'h', 1 ≤ bishop[1] ≤ 8. [input] string pawn Coordinates of the black pawn in the same notation. Guaranteed constraints: pawn.length = 2, 'a' ≤ pawn[0] ≤ 'h', 1 ≤ pawn[1] ≤ 8. [output] boolean true if the bishop can capture the pawn, false otherwise. """ def bishopAndPawn(bishop, pawn): ''' Bishop Rules: bishop: g2 --> [7,2] bishop[0] and bishop[1] must change by the same ammount to be valid bishop[0] and bishop[1] must be in [1:8,1:8] ''' location_dict={ 'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8 } bishop=[location_dict[bishop[0]],int(bishop[1])] pawn=[location_dict[pawn[0]],int(pawn[1])] bishop_potential=[] for i in range(1,9): for j in range(1,9): if abs(i-bishop[0])==abs(j-bishop[1]): bishop_potential.append((i,j)) if (pawn[0],pawn[1]) in bishop_potential: return True else: return False
# -*- coding: utf-8 -*- """ Created on Fri Feb 28 23:40:11 2020 @author: Logan Rowe Find the number of ways to express n as sum of some (at least two) consecutive positive integers. Example For n = 9, the output should be isSumOfConsecutive2(n) = 2. There are two ways to represent n = 9: 2 + 3 + 4 = 9 and 4 + 5 = 9. For n = 8, the output should be isSumOfConsecutive2(n) = 0. There are no ways to represent n = 8. Input/Output [execution time limit] 4 seconds (py3) [input] integer n A positive integer. Guaranteed constraints: 1 ≤ n ≤ 104. [output] integer """ def isSumOfConsecutive2(n): possible_combinations=0 start=int(n/2)+2 tail=start numbers=[] while start>=0: if sum(numbers)>n or tail<=0: numbers=[] start-=1 tail=start elif sum(numbers)<n: numbers.append(tail-1) tail-=1 else: numbers=[] possible_combinations+=1 start-=1 tail=start return(possible_combinations) print(isSumOfConsecutive2(9)) print(isSumOfConsecutive2(8))
# -*- coding: utf-8 -*- """ Created on Tue Feb 11 17:19:34 2020 @author: Logan Rowe Given a string, output its longest prefix which contains only digits. Example For inputString = "123aa1", the output should be longestDigitsPrefix(inputString) = "123". Input/Output [execution time limit] 4 seconds (py3) [input] string inputString Guaranteed constraints: 3 ≤ inputString.length ≤ 100. [output] string [Python3] Syntax Tips """ import string def longestDigitsPrefix(inputString): idx=0 digits=string.digits for character in inputString: if character in digits: idx+=1 else: break return(inputString[:idx])
# -*- coding: utf-8 -*- """ Created on Thu Feb 6 00:03:30 2020 @author: Logan Rowe Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1. For a = [2, 1, 3, 5, 3, 2], the output should be firstDuplicate(a) = 3. net coding time: 5 minutes """ import numpy as np def firstDuplicate(a): number_dictionary={} for number in a: if number not in number_dictionary: number_dictionary[number]=1 elif number in number_dictionary: #first duplicate found return(number) #no duplicates found return(-1) if __name__ == '__main__': a=np.array([2,1,3,5,3,2]) print(firstDuplicate(a))
#!/bin/python import os #The fields are separated by commas (hence the "csv" suffix on the filename: csv stands for Comma Separated Values) #Print out the gene names for all genes from the species Drosophila melanogaster or Drosophila simulans. #Print out the gene names for all genes that are between 90 and 110 bases long. #Print out the gene names for all genes whose AT content is less than 0.5 and whose expression level is greater than 200. #Print out the gene names for all genes whose name begins with "k" or "h" except those belonging to Drosophila melanogaster. #For each gene, print out a message giving the gene name and saying whether its AT content is high (greater than 0.65), low (less than 0.45) or medium (between 0.45 and 0.65). mosca3=open("data.csv") #archivo con una \n al final por eso se la quita con rstrip #split() corta donde hay espacios, por eso si lo uso de esa manera corta el nombredel genero y el resto lo agrupa en la especie. #si lo uso asi tienes las separaciones que quieres, cada elemento separado por una coma pero el problema es que no lo tienes en diferentes lineas y lo peor de todo es que tienes esto '485\nDrosophila yakuba' mosca_read=mosca3.read().rstrip().split("\n") mosca_read #tienes toda la linea de nombre, sequencia, gen y expresion, separados de los demás pero aun no los tenes en diferentes lineas. Para eso ya toca usar un foor loop. for everyelement in mosca_read: everyelement=everyelement.split(",") #split makes a string into a list. It separated it by coma. The thing is how it distinguishes between everset. Is it because between is set there is a "" # print(everyelement) names=everyelement[0] # print(names) geneseqs=everyelement[1].upper() # print(geneseqs) seqlenghts=len(everyelement[1]) #now we learnt that each character of a string has its position. # print(seqlenghts) genenames=everyelement[2] # print(genenames) expressionlevel=int(everyelement[3]) #has to make it an integer because it is a string # print(expressionlevel) ATcontent=(geneseqs.count('A')+geneseqs.count('T'))/(seqlenghts) # print(ATcontent) if 90 >= seqlenghts <= 100: print(genenames + " has a lenght of " + str(seqlenghts)) if ATcontent < 0.65 and expressionlevel > 200: print(genenames + " has an AT content of " + str(ATcontent) + " and an expression level of " + str(expressionlevel)) if ((genenames[0] == "k" or genenames[0] == "h")) and not names == "Drosophila melanogaster": print(genenames + " starts with k or h and are not Drosophila melanogaster") if ATcontent > 0.65: print(genenames + "has an AT content that is higher than 0.65") elif ATcontent < 0.45: print(genenames + "has an AT content that is less than 0.45") else: print(genenames + "has an AT content between 0.45 and 0.65")
n1 = int(input("Digite um numero: ")) n2 = int(input("Digite outro numero: ")) n3 = int(input("Digite outro numero: ")) resto = ((n3*2)+(n2*3)+(n1*4))%11 resultado = 11 - resto print ('Digito verificador: {}'.format(resultado))
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def getData(self): return self.data def setData(self, newData): self.data = newData def getNext(self): return self.next def setNext(self, nextNode): self.next = nextNode class Solution: # @return a ListNode def addTwoNumbers(self, l1, l2): carry = 0 root = n = ListNode(0) while l1 or l2 or carry: v1 = v2 = 0 if l1: v1 = l1.val l1 = l1.next if l2: v2 = l2.val l2 = l2.next carry, val = divmod(v1+v2+carry, 10) n.next = ListNode(val) n = n.next return root.next l1 = ListNode(1) l1.setNext(2) l2 = ListNode(2) l2.setNext(3) Solution.addTwoNumbers(0,l1,l2)
#Required modules have been imported import math as mt from scipy.special import lambertw import warnings #Function to check which radius is to be chosen from two radii according to critical radius def rad_check_condition(r1,r2,critical_radius): if (((r1<critical_radius)and(r2<critical_radius))or((r1>critical_radius)and(r2>critical_radius))): print "\nSome values are unreal since the values of r1 and r2 are greater than critical radius or both are less than critical radius i.e",round(r1,3),round(r2,7),"." Insulation_Radius = 0 else: if ((r1 or r2)<0): if (r1<0): if (r2>Outer_Radius): Insulation_Radius = r2 else: print "\nSome values are unreal since one solution is negative and other is less than outer radius." if (r2<0): if (r1>Outer_Radius): Insulation_Radius = r2 else: print "\nSome values are unreal since one solution is negative and other is less than outer radius." else: if (critical_radius>Outer_Radius): if ((r1<critical_radius)and(r1>Outer_Radius)): Insulation_Radius = r1 if ((r2<critical_radius)and(r2>Outer_Radius)): Insulation_Radius = r2 if ((r1<critical_radius)and(r1<Outer_Radius)): Insulation_Radius = r2 if ((r2<critical_radius)and(r2<Outer_Radius)): Insulation_Radius = r1 else: if(r1>Outer_Radius): Insulation_Radius = r1 if(r2>Outer_Radius): Insulation_Radius = r2 return Insulation_Radius while True: print '''\nThis Program provides solution for insulation (90% reduction in energy loss) over a wall, tube and sphere." Cost of Insulation is also calculated.\n''' #Table for material to be chosen by user. Table_Material =[["Aluminium(Pure) ",204], ["Al-Cu(Duralumin) ",164], ["Al-Si(Silumin,copper-bearing)",137], ["Al-Si(Alusil) ",161], ["Al-Mg-Si(97%Al,1%Mg,1%Si,1%Mn",177], ["Nickel Steel(Ni-0%) ",73], ["Nickel Steel(Ni-40%) ",10], ["Inwar(36%Ni) ",10.7], ["Chrome Steel(Cr-0%) ",73], ["Chrome Steel(Cr-1%) ",61], ["Chrome Steel(Cr-5%) ",40], ["Steel (C 0.5%) ",54], ["Steel (C 1.0%) ",43], ["Steel (C 1.5%) ",36]] #Printing the Table_Material print "\t\tINSULATING MATERIAL\t\tCONDUCTIVITY(SI)" for i in range(len(Table_Material)): print i+1,"\t\t",Table_Material[i][0],"\t\t",Table_Material[i][1] #Taking user input from Table_Material choice = int(raw_input("\nPlease Select any material from above list by entering its corresponding number: ")) while(choice>14): print "Please input correctly from list." choice = int(raw_input("Please Select any material from above list by entering its corresponding number: ")) #Printing out user's choice print "\nSo, Your choice is",Table_Material[(choice-1)][0],"whose thermal conductivity is",Table_Material[(choice-1)][1] #Table for insulating material. Table_Ins = [["Asbestos,loosely packed ",0.154,520,180], ["Asbestos,cement ",0.74,520,180], ["Balsam wood ",0.04,35,30476], ["Cardboard,corrugated ",0.064,240,45], ["Celotex ",0.048,30,1088], ["Corkboard ",0.043,160,167], ["Cork,regranulated ",0.045,82.5,167], ["Diamond,Type IIa,insulator",2300,3500,1188443750], ["Diatomaceous earth ",0.061,320,27], ["Felt,hair ",0.036,165,155], ["Felt,wool ",0.052,330,180], ["Fiber,insulating board ",0.048,240,150], ["Glass wool ",0.038,240.7,300], ["Glass fiber,duct liner ",0.038,32,250], ["Glass fiber,loose blown ",0.043,16,250], ["Ice ",2.22,910,30], ["Kapok ",0.035,290,250], ["Magnesia ",0.073,270,2500], ["Paper (avg) ",0.12,900,285], ["Rock wool ",0.040,160,25], ["Sawdust ",0.059,210,6], ["Silica aerogel ",0.024,140,125], ["Styrofoam ",0.033,50,160]] #Printing the Table_Ins print "\n\t\tINSULATING MATERIAL\t\tCONDUCTIVITY(SI)\tDENSITY(SI)\tCOST(Rs/kg)\n" for i in range(len(Table_Ins)): print i+1,"\t\t",Table_Ins[i][0],"\t\t",Table_Ins[i][1],"\t\t",Table_Ins[i][2],"\t\t",Table_Ins[i][3] #Taking user input from Table_Ins choice1 = int(raw_input("\nPlease Select your insulating material from above list by entering its corresponding number: ")) while(choice1>23): print "Please input correctly from list." choice1 = int(raw_input("Please Select your insulating material from above list by entering its corresponding number: ")) #Printing out user's choice print "\nSo, Your choice is",Table_Ins[(choice1-1)][0],"whose thermal conductivity is",Table_Ins[(choice1-1)][1],"W/m.K,\nwhose density is",Table_Ins[(choice1-1)][2],"kg per cubic metre and whose cost is Rs.",Table_Ins[(choice1-1)][3],"per kg." print '''\nWhat do you want to insulate ? 1. Wall 2. Tube 3. Sphere ''' #Taking input from user to specify which object to insulate choice2 = int(raw_input("\nSelect object from above list by entering its corresponding number: ")) while(choice2>3): print "Please input correctly from list." choice2 = int(raw_input("Select object from above list by entering its corresponding number: ")) #Taking user inputs for inside Temprature, surrounding temprature, convective heat transfer coefficient. Ti = float(raw_input("Enter the inside temprature of your material in kelvin: ")) Ts = float(raw_input("Enter the surrounding temprature of your material in kelvin: ")) h = float(raw_input("Enter the convective heat transfer coefficient(SI-units W/m2k): ")) #Taking values from Tables according to user's choice of material. k = Table_Material[(choice-1)][1] k_ins = Table_Ins[(choice1-1)][1] Density_Insulation = Table_Ins[(choice1-1)][2] Rate_Insulation = Table_Ins[(choice1-1)][3] #Program if user chooses wall if(choice2==1): #Taking dimensions from user Initial_Thickness = float(raw_input("Enter initial thickness of the wall in metres: ")) Length = float(raw_input("Enter length of the wall in metres: ")) Breadth = float(raw_input("Enter breadth of the wall in metres: ")) #Heat loss per unit Area formula heat_loss_qbyA = abs((((Ti-Ts)*1.0))/((Initial_Thickness/(k*1.0))+(1/(h*1.0)))) #Printing out current heat loss and user's expectation of heat loss(i.e 90% reduction in heat loss) print"\nNow heat lost by object is",round(heat_loss_qbyA,3),"W/m^2." print"By adding insulation we want to reduce heat loss to",round(((0.1)*(heat_loss_qbyA)),3),"W/m^2." #Calculating Insulation Thickness and printing it Insulation_Thickness = ((9.0*k_ins*1.0)*((Initial_Thickness/(k*1.0))+(1/(h*1.0)))) print"\nThe thickness of insulating material required is",round(Insulation_Thickness,3),"m." #Calculating Weight and Total Cost and displaying it Weight_Insulation = Length*Breadth*Insulation_Thickness*Density_Insulation*1.0 Total_Cost_Insulation = Rate_Insulation*Weight_Insulation*1.0 print"\nTotal Weight of Insulation is",round(Weight_Insulation,3),"kg and total COST of Insulation is Rupees",round(Total_Cost_Insulation,3) #Program if user chooses tube if(choice2==2): #Taking Dimensions of Tube from User Inner_Radius = float(raw_input("Enter the inner radius of the tube in metres: ")) Outer_Radius = float(raw_input("Enter the outer radius of the tube in metres: ")) Length = float(raw_input("Enter the length of tube in metres: ")) #Heat loss per unit Area formula heat_loss_qbyA = abs((((2.0*(mt.pi))*((Ti-Ts)*1.0))/(((mt.log(Outer_Radius/(Inner_Radius*1.0)))/(k*1.0))+(1/(Outer_Radius*h*1.0))))) #Printing out current heat loss and user's expectation of heat loss(i.e 90% reduction in heat loss) print"\nNow heat lost by object is",round(heat_loss_qbyA,3),"W/m^2." print"\nBy adding insulation we want to reduce heat loss to",round(((0.1)*(heat_loss_qbyA)),3),"W/m^2." #Critical Radius where heat loss is maximum critical_radius = (k_ins/(h*1.0)) print "\nThe critical radius of insulation is",critical_radius,"m." #There are warnings due to complex roots of lambert function which are needed to be ignored in Output so this loop has been started with warnings.catch_warnings(): warnings.filterwarnings("ignore") #An equation is formed in terms of lnx and 1/x whixh is solved using lambert function, r1,r2 are solutions. a = (h/(k_ins*1.0)) b = Outer_Radius c = (k_ins)*((9.0*((mt.log(Outer_Radius/(Inner_Radius*1.0)))/(k*1.0)))+(10.0/(Outer_Radius*h*1.0))) z = -(1/(a*b*mt.exp(c)*1.0)) w1 = lambertw(z,k=0) w2 = lambertw(z,k=-1) r1 = (b*(mt.exp(w1+c))) r2 = (b*(mt.exp(w2+c))) #print r1,r2 #Function is called to check which is the appropriate insulation radius among the two r1,r2 and insulation radius is printed. Insulation_Radius = rad_check_condition(r1,r2,critical_radius) print"\nThe radius of insulating material is",round(Insulation_Radius,3),"m, and the Thickness is",round((Insulation_Radius-Outer_Radius),3),"m." #Weight and Total Cost of Insulation is calculated and printed. Weight_Insulation = (mt.pi)*(Length)*(((Insulation_Radius)**2)-(((Outer_Radius)**2)))*Density_Insulation*1.0 Total_Cost_Insulation = Rate_Insulation*Weight_Insulation*1.0 print"\nTotal Weight of Insulation is",round(Weight_Insulation,3),"kg and total COST of Insulation is Rupees",round(Total_Cost_Insulation) #Program if user chooses sphere if(choice2==3): #Taking Dimensions of Tube from User Inner_Radius = float(raw_input("Enter the inner radius of the sphere in metres: ")) Outer_Radius = float(raw_input("Enter the outer radius of the sphere in metres: ")) #Heat loss per unit Area formula heat_loss_qbyA = abs((((4.0*(mt.pi))*((Ti-Ts)*1.0))/(((((1.0/(Inner_Radius*1.0))-(1.0/(Outer_Radius*1.0)))/(k*1.0))+(1/(h*Outer_Radius*Outer_Radius*1.0)))*1.0))) #Printing out current heat loss and user's expectation of heat loss(i.e 90% reduction in heat loss) print"\nNow heat lost by object is",round(heat_loss_qbyA,3),"W/m^2." print"\nBy adding insulation we want to reduce heat loss to",round(((0.1)*(heat_loss_qbyA)),3),"W/m^2." #A quadratic equation a(1/r^2) +b(1/r) +c = 0 is formed according to given hypothesis which calculates the insulation radius. a = (1/(h*1.0)) b = -(1/(k_ins*1.0)) c = -((9/(k*1.0))*((1/(Inner_Radius*1.0))-(1/(Outer_Radius*1.0)))+((10)/(h*Outer_Radius*Outer_Radius*1.0))-(1/(k_ins*Outer_Radius*1.0))) delta = (b**2) - (4*a*c) if(delta<0): print "\nSome values are unreal since delta is negative." else: solution1 = (-b-mt.sqrt(delta))/(2*a*1.0) solution2 = (-b+mt.sqrt(delta))/(2*a*1.0) r1 = (1/(solution1*1.0)) r2 = (1/(solution2*1.0)) #print r1,r2 #Critical Radius where heat loss is maximum critical_radius = ((2*k_ins)/(h*1.0)) print "\nThe critical radius of insulation is",critical_radius,"m." #Function is called to check which is the appropriate insulation radius among the two r1,r2 and insulation radius is printed. Insulation_Radius = rad_check_condition(r1,r2,critical_radius) print"\nThe radius of insulating material is",round(Insulation_Radius,3),"m, and the Thickness is",round((Insulation_Radius-Outer_Radius),3),"m." #Weight and Total Cost of Insulation is calculated and printed. Weight_Insulation = (4.0/3.0)*(mt.pi)*(((Insulation_Radius)**3)-(((Outer_Radius)**3)))*Density_Insulation*1.0 Total_Cost_Insulation = Rate_Insulation*Weight_Insulation*1.0 print"\nTotal Weight of Insulation is",round(Weight_Insulation,3),"kg and total COST of Insulation is Rupees",round(Total_Cost_Insulation,3) #This block of code is written to allow user to decide whether to continue or not. while True: answer = raw_input("\nRun again? (Y/N): ") if answer in ("Y", "N","y","n"): break print "Invalid input." if answer == "Y" or answer == "y": continue else: print "\n--------------------------------------------------------THANK YOU--------------------------------------------------------" break
number = 23 running = True while running: guess = int(input('Введите целое число')) if guess == number: print('Поздравляю вы победили') running = False elif guess < number: print('Число немного больше этого') else: print('Число меньше заданного') else: print('Цикл While - завершен') print("""Завершение программы Парам-пам -пам Тадам!""")
you = "hello" if you == "": roobot_brain = "I can't hear you, try again" elif you == "hello": roobot_brain = "Hello Su" elif you == "today": roobot_brain = "thu 6" else: roobot_brain = "I'm fine thank you and you" print(roobot_brain)
import random; def GenerateRandomKey (numberOfElements, minValue, maxValue) : randomList = []; while len(randomList) <= numberOfElements-1 : randomElement = random.randint(minValue, maxValue); if randomElement in randomList : continue; randomList.append(randomElement); return randomList; def getGameConfiguration (games, choosedGame) : for game in games : if game['gameId'] == choosedGame : return game; return {}; def LoadGameConfiguration () : gameConfiguration = [ { 'gameId':1, 'game':'Euromillions', 'gameNumbers' : 5, 'gameNumberMinValue' : 1, 'gameNumberMaxValue' : 50, 'gameStars' : 2, 'gameStarsMinValue' : 1, 'gameStarsMaxValue' : 12 }, { 'gameId':2, 'game':'Totoloto', 'gameNumbers' : 5, 'gameNumberMinValue' : 1, 'gameNumberMaxValue' : 49, 'gameStars' : 0, 'gameStarsMinValue' : 0, 'gameStarsMaxValue' : 0 } ]; return gameConfiguration; print('Welcome to Euromillions (and other games) generator.'); while True : gameConfiguration = {}; randomKey = ''; randomStarts = ''; choosedGame = -1; games = LoadGameConfiguration(); print('Available Games:'); for i in games : print(str(i['gameId']) + ' - ' + str(i['game'])); while choosedGame < 0 : choosedGame = input("Choose the number of game, or press 0 to exit :"); try : choosedGame = int(choosedGame); except : choosedGame = -1; continue; if choosedGame == 0 : continue; gameConfiguration = getGameConfiguration (games, choosedGame); if len(gameConfiguration) == 0 : choosedGame = -1; continue; if choosedGame == 0 : break; ## special trick :) superbPotencial = ''; dummyNumber = random.randint(1,100); if dummyNumber >= 90 : superbPotencial = '(this key has great potencial... :) Good Luck!)'; randomKeyList = GenerateRandomKey(gameConfiguration['gameNumbers'], gameConfiguration['gameNumberMinValue'], gameConfiguration['gameNumberMaxValue']); randomStartsList = GenerateRandomKey(gameConfiguration['gameStars'], gameConfiguration['gameStarsMinValue'], gameConfiguration['gameStarsMaxValue']); for i in randomKeyList : randomKey += ' ' + str(i) + ' '; for i in randomStartsList : randomStarts += ' ' + str(i) + ' '; print('*'*10); print('Generated key ' + superbPotencial); print(randomKey + '*' + randomStarts); print('*'*10); print('\n');
#Question - https://leetcode.com/problems/binary-tree-paths class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: if root is None: return [] def helper(root,curr_list,result): if root is None: return curr_list.append(str(root.val)) if not root.left and not root.right: result.append('->'.join(curr_list.copy())) if root.left: helper(root.left,curr_list,result) curr_list.pop() if root.right: helper(root.right,curr_list,result) curr_list.pop() result=[] helper(root,[],result) return result
#Question - https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/570/week-2-december-8th-december-14th/3563/ class Solution: def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode: def getDepthAndTargetSubtree(root): if not root: return (0, None) leftDepth, leftTargetSubtree = getDepthAndTargetSubtree(root.left) rightDepth, rightTargetSubtree = getDepthAndTargetSubtree(root.right) if leftDepth == rightDepth: return (1+leftDepth, root) elif leftDepth < rightDepth: return (1+rightDepth, rightTargetSubtree) else: return (1+leftDepth, leftTargetSubtree) return getDepthAndTargetSubtree(root)[1]
class TreeNode: def __init__(self, key): self.left = None self.right = None self.val = key def is_bst(root): print(root.val) if root: if root.left and root.val<root.left.val: return False if root.right and root.val<root.right.val: return False if is_bst(root.left)==False or is_bst(root.right)==False: return False return True else: return True a = TreeNode(5) a.left = TreeNode(3) a.right = TreeNode(7) a.left.left = TreeNode(1) a.left.right = TreeNode(4) a.right.left = TreeNode(6) print(a) print(is_bst(a))
#Question - https://leetcode.com/problems/design-parking-system class ParkingSystem: def __init__(self, big: int, medium: int, small: int): self.big=big self.medium=medium self.small=small def addCar(self, carType: int) -> bool: if carType==1 and self.big>0: self.big-=1 return True elif carType==2 and self.medium>0: self.medium-=1 return True elif carType==3 and self.small>0: self.small-=1 return True return False
class Solution: def reverseWords(self, string): ans='' arr=string.split(' ') for word in arr: ans+=word[::-1]+' ' return ans print(Solution().reverseWords("The cat in the hat")) # ehT tac ni eht tah
""" Solution to the Word Search Problem -> https://leetcode.com/problems/word-search/ Solution is very similiar to the Gold Mine Based on backtracking and recursion Return True if solution is found """ class Solution: def exist(self, board: List[List[str]], word: str) -> bool: ans=False def helper(i,j,k,current): found=False if i<0 or i>=len(board) or j<0 or j>=len(board[0]) or k>=len(word) or board[i][j]=='ZZ': return False elif k==len(word)-1 and board[i][j]==word[k]: return True else: val=board[i][j] board[i][j]='ZZ' found=helper(i+1,j,k+1,current+val) | helper(i,j+1,k+1,current+val) | helper(i-1,j,k+1,current+val) | helper(i,j-1,k+1,current+val) board[i][j]=val return found for i in range(len(board)): for j in range(len(board[0])): if board[i][j]==word[0]: ans=helper(i,j,0,'') if ans: return True return ans
#Question - https://leetcode.com/problems/prime-palindrome/ class Solution: def primePalindrome(self, N: int) -> int: if N<=2: return 2 def isPalidrome(n): for i in range(len(n)//2): if n[i]!=n[len(n)-i-1]: return False return True def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True if N%2==0: N+=1 while True: if isPalidrome(str(N)) and isPrime(N): return N N+=2
""" Explanation Approach 1 - Store left elements and right elements in two different lists check for the occurence of each number till it satisfy the conditions """ class Solution: def findJudge(self, N: int, trust: List[List[int]]) -> int: if (N==1): return N """ Approach 1- left,right=map(list, zip(*trust)) for i in range(1,N+1): if right.count(i)==N-1 and left.count(i)==0: return i elif right.count(i)==N and left.count(i)==1 and [i,i] in trust: return i else: ans=-1""" #Approach 2- ans=[0 for i in range(N+1)] for i in trust: ans[i[0]]-=1 ans[i[1]]+=1 for i in range(1,N+1): if ans[i]==N-1: return i return -1
x = input("Enter a string") y = input("Enter a string") z = input("Enter a string") for i in range(10): print("This is some output from the lab ",i) print("Your input was " + x) print("Your input was " + y) print("Your input was " + z)
class LNode: """ 定义链表对象 """ def __init__(self, x): self.data = x self.next = None """ 题目描述: 将Head->1->2->3->4->5->6->7->8逆序 为head->8->7->6->5->4->3->2->1 方法:就地逆序 """ def NofirstNodeReverse(head): if head is None or head.next is None: return cur = None pre = None next = None #处理第一个节点 cur = head next = cur.next cur.next = None pre = cur cur = next while cur.next != None: next = cur.next cur.next = pre pre = cur cur = next #添加头节点 cur.next = pre head=cur return head if __name__ == '__main__': i=1 head=LNode(i) cur=head tmp = None while i<=8: i+=1 tmp=LNode(i) cur.next=tmp cur=tmp print("BeforeReverse:") cur = head while cur != None: print(cur.data) cur = cur.next print("\nAfterReverse:") head=NofirstNodeReverse(head) cur = head while cur != None: print(cur.data) cur = cur.next
#队列:入队列、出队列、查看队列首尾元素、查看队列是否为空、查看队列大小等功能、清空队列。先进先出 #方法:链表实现 #front指向队列首,rear指向队列尾 #新元素加在链表尾部,出队列时将第一个节点的值返回并删掉该节点 class LNode: def __init__(self,arg): self.data=arg self.next=None class MyQueue: #模拟队列 def __init__(self): #phead=LNode(None) self.data=None self.next=None self.front=self#指向队列首 self.rear=self#指向队列尾 #判断队列是否为空,如果为空返回True,否则返回false def isEmpty(self): return self.front==self.rear #返回队列的大小 def size(self): p=self.front size=0 while p.next!=self.rear.next: p=p.next size+=1 return size #返回队列首元素 def top(self): if not self.isEmpty(): return self.front.next.data else: print("队列为空") return None #返回队列尾元素 def bottom(self): if not self.isEmpty(): return self.rear.data else: print("队列为空") return None #出队列 def pop(self): if self.size()==1: data=self.front.next self.rear=self return data.data elif not self.isEmpty(): data=self.front.next self.front.next=self.front.next.next print("出队列成功") return data.data else: print("队列已为空") return None #入队列 def push(self,item): tmp=LNode(item) self.rear.next=tmp self.rear=self.rear.next print("入队列成功") #清空队列 def destroy(self): self.next=None print("队列已清空") #打印队列 def showQueue(self): if not self.isEmpty(): p=self.front.next while p != self.rear.next: print(p.data) p=p.next if __name__ == '__main__': s=MyQueue() s.push(4) s.push(5) s.push(7) s.push(4) s.push(5) s.push(9) print("size:",s.size()) print("front:",s.top()) print("rear:", s.bottom()) s.pop() print("size:",s.size()) print("front:",s.top()) print("rear:", s.bottom()) s.showQueue() while not s.isEmpty(): print(s.pop()) s.pop() s.pop() s.pop() s.destroy() print("size:",s.size())
""" 给定一个数组[3,4,7,10,20,9,8],可以找出两个数队(3,8),(4,7)=>3+7=8+4 """ import random class Pair: """docstring for pair""" def __init__(self,first,second): self.first=first self.second=second def findPairs(arr): Dict={} i=0 n=len(arr) while i<n: j=i+1 while j<n: pair=Pair(arr[i],arr[j]) sum=arr[i]+arr[j] if sum not in Dict: Dict[sum]=pair else: p=Dict[sum] print("数队:("+str(pair.first)+","+str(pair.second)+")与("+str(p.first)+","+str(p.second)+")符合题目要求") Dict[sum] = pair j+=1 i+=1 return False if __name__ == '__main__': arr=[] for i in range(6): arr.append(random.randint(0,9)) print(arr) findPairs(arr) print(arr)
class SqQueue(object): def __init__(self, maxsize): self.queue = [None] * maxsize self.maxsize = maxsize self.front = 0 self.rear = 0 """ ------------------ 队列的存储结构中使用的最多的是循环队列。循环队列包括两个指针, front 指针指向队头元素, rear 指针指向队尾元素的下一个位置。 队列为空的判断条件是: front == rear 队列满的判断条件是: (rear+1)%maxsize == front 队列长度的计算公式: (rear-front+maxsize)%maxsize ------------------ """ # 返回当前队列的长度 def QueueLength(self): return self.rear - self.front #return (self.rear - self.front + self.maxsize) % self.maxsize # 如果队列未满,则在队尾插入元素,时间复杂度O(1) def EnQueue(self, data): if (self.rear + 1) % self.maxsize == self.front: #可以扩充 print("The queue is full!") else: self.queue[self.rear] = data # self.queue.insert(self.rear,data) self.rear = (self.rear + 1) % self.maxsize print("EnQueue is done!") # 如果队列不为空,则删除队头的元素,时间复杂度O(1) def DeQueue(self): if self.rear == self.front: print("The queue is empty!") else: data = self.queue[self.front] self.queue[self.front] = None self.front = (self.front + 1) % self.maxsize print("DeQueue is done!") return data # 输出队列中的元素 def ShowQueue(self): for i in range(self.maxsize): print(self.queue[i],end=',') print(' ') # 测试程序 if __name__ == "__main__": # 建立大小为15的循环队列 q = SqQueue(15) # 0~9入队列 for i in range(10): q.EnQueue(i) q.ShowQueue() # 删除队头的5个元素:0~4 for i in range(5): q.DeQueue() q.ShowQueue() # 从队尾增加8个元素:0~7 for i in range(8): q.EnQueue(i) q.ShowQueue() #--------------------- #作者:windwm #来源:CSDN #原文:https://blog.csdn.net/u012626619/article/details/80658397 #版权声明:本文为博主原创文章,转载请附上博文链接!
import random class LNode: def __init__(self,arg): self.data=arg self.next=None """ 题目描述: 给定链表Head->1->1->3->3->5->7->7->8 单链表倒数第k=3个元素为7 要求: 方法:建立两个指针slow和fast,fast先于slow k步,当fast指向链表最后一个元素时,slow刚好指向倒数第k个元素 """ def creatLink(x): i = 1 head = LNode(None) tmp = None cur = head while i <= x: n = random.randint(1, 9) tmp = LNode(n) cur.next = tmp cur = tmp i += 1 return head def FindLastButK(head,k): i=0 slow=head.next fast=head.next while k-1>0: fast=fast.next k-=1 #exec('''"fast=head.next"+".next"*(k-1)''') if head.next is not None: while fast.next is not None: #print("s",slow.data) #print("f",fast.data) slow=slow.next fast=fast.next return slow.data return None if __name__ == '__main__': head=creatLink(10) print("head:") cur = head.next while cur != None: print(cur.data) cur = cur.next k=int(input("请输入k:\n")) item=FindLastButK(head,k) print("链表倒数第%d个元素为:"%k,item)
import random class LNode: def __init__(self,arg): self.data=arg self.next=None """ 题目描述: 给定链表Head->1->2->3->4->5->7->7->8 反转为链Head->2->1->4->3->7->5->8->7 要求: 方法:建立两个指针slow和fast,fast比slow快一步,步长均为2,两个一组,在pre和next进行交换。 """ def creatLink(x): i = 1 head = LNode(None) tmp = None cur = head while i <= x: n = random.randint(1, 9) tmp = LNode(n) cur.next = tmp cur = tmp i += 1 return head def function(head): if head.next is None or head.next.next is None: return head pre=head slow=head.next fast=slow.next next=None while fast.next is not None and fast.next.next is not None: next = fast.next pre.next=fast fast.next=slow slow.next=next pre=slow slow=next fast=slow.next next = fast.next pre.next = fast fast.next = slow slow.next = next return head if __name__ == '__main__': head = creatLink(10) print("head:") cur = head.next while cur != None: print(cur.data) cur = cur.next head = function(head) print("\nAfterReverse:") cur = head.next while cur != None: print(cur.data) cur = cur.next
import os import csv filename = "budget_data.csv" #open and read csv with open(filename) as csvfile: csvreader = csv.reader(csvfile,delimiter=",") #skip the headers next(csvreader) #create an empty list to store the date months=[] #create a variable to store the net_total net_total =0 #create an empty list to store the profitloss list=[] #loop through each row in the dataset for row in csvreader: #convert the list "profit/loss" into integer profitloss=int(row[1]) #add the date into the list months.append(row[0]) #add profit/loss to the net_total net_total=net_total+profitloss #add all the profit/loss into the list list.append(profitloss) change=0 greatest_increase=0 greatest_decrease=0 #loop through all the profitloss value in the list for i in range(len(list)-1): #calculate the average of the changes in "Profit/Losses" over the entire period, round to 2 d.p change=change+((list[i+1])-list[i]) average_change=round(change/(len(months)-1),2) #find the greatest increase in profits if ((list[i+1])-list[i])>greatest_increase: greatest_increase=((list[i+1])-list[i]) #find the index for the greatest increase in profits greatest_increase_index=i+1 #find the greatest decrease in profits if ((list[i+1])-list[i])<greatest_decrease: greatest_decrease=((list[i+1])-list[i]) #find the index for the greatest decrease in profits greatest_decrease_index=i+1 print("Financial Analysis") print("-----------------------------") #print the total number of months included in the dataset print("Total Months: "+str(len(months))) #print the net total amount of profit/lossess over the entire period print("Total: $"+str(net_total)) #print the average of the changes in "Profit/Lossess"over the entire period print("Average Change: $"+str(average_change)) #print the greatest increase in profits (date and amount) over the entire period print("Greatest Increase in Profits: "+months[greatest_increase_index]+" ($"+str(greatest_increase)+")") #print the greatest increase in profits (date and amount) over the entire period print("Greatest Decrease in Profits: "+months[greatest_decrease_index]+" ($"+str(greatest_decrease)+")") #export the result to a text file output_path=os.path.join("Analysis","pybank.txt") txt_file=open("output_path","w") txt_file.write("Financial Analysis\n") txt_file.write("-----------------------------\n") txt_file.write(f"Total Months: {len(months)}\n") txt_file.write(f"Total: ${net_total}\n") txt_file.write(f"Average Change: ${average_change}\n") txt_file.write(f"Greatest Increase in Profits: {months[greatest_increase_index]} (${greatest_increase})\n") txt_file.write(f"Greatest Decrease in Profits: {months[greatest_decrease_index]} (${greatest_decrease})\n") txt_file.close()
class HuffmanFactory: """Class used to create a Huffman tree and compress the input text based on that huffman tree. >>> import HuffmanCompression >>> sample_input = "sample" >>> huff = HuffmanCompression.HuffmanFactory(sample_input) >>> print(huff.compressed_string) 1001010100111110 # bit representation (as string) >>> huff.compression_dictionary {'a': '101', 'p': '00', 'e': '110', 's': '100', 'm': '01', 'l': '111'} >>> huff.compare_lengths() Original String Length (bits): 48 bits. Compressed String Length (bits): 16 bits. Compression decreases space required by ~66.67%. """ raw_string = "" huffman_tree = None compression_dictionary = {} compressed_string = "" class HuffmanNode: """Class used to represent each node in a Huffman tree. Will always have two branches. """ right = None left = None value = 0 letter = "" def __init__(self, value, letter = "", left = None, right = None): self.value = value self.letter = letter self.left = left self.right = right def is_leaf(self): """Return if the node has any branches or not. """ return (self.left == None and self.right == None) def __gt__(self, other): return self.value > other.value def __ge__(self, other): return self.value >= other.value def __lt__(self, other): return self.value < other.value def __le__(self, other): return self.value <= other.value def __eq__(self, other): return self.letter == other def depth(self): if is_leaf(self): return 0 else: return 1 + max(depth(self.left), depth(self.right)) def __repr__(self): print() def __init__(self, inp): self.raw_string = inp node_list = HuffmanFactory.generate_node_list(self.raw_string) self.huffman_tree = HuffmanFactory.generate_tree(node_list) self.compression_dictionary = HuffmanFactory.generate_dict(self.huffman_tree) self.compressed_string = HuffmanFactory.compress_string(self.raw_string, self.compression_dictionary) def generate_node_list(inp, nodes = []): """Create list of HuffmanNodes. If the HuffmanNode for a letter doesn't exist in the list, add it. If it does, increment its value by 1. """ for i in inp: if i not in nodes: nodes.append(HuffmanFactory.HuffmanNode(1, i)) else: for k in nodes: if k.letter == i: k.value = k.value + 1 break nodes = sorted(nodes)[::-1] return nodes def generate_tree(nodes): """Merge nodes together, building from bottom to top, to create a Huffman tree. Given pairs [e, 7], [t, 2], and [l, 1], creates a tree that looks like this: ( ) / \ ( ) (e) / \ (t) (l) Letters that appear more frequently will appear closer to the top of the tree, and so have a shorter representation. """ nodes = sorted(nodes)[::-1] while len(nodes) > 1: node1 = nodes.pop() node2 = nodes.pop() new_node = HuffmanFactory.HuffmanNode(node1.value + node2.value, "", node1, node2) nodes.append(new_node) nodes = sorted(nodes)[::-1] return nodes[0] def generate_dict(tree, dic = {}): """Create dictionary based on the Huffman tree. Left branch is represented by a 0, and right branch is represented by a 1. ( ) / \ ( ) (e) / \ (t) (l) In this case, e is represented by "1", t is represented by "00", and l is represented by "01". """ def helper(tree, path): nonlocal dic if tree.is_leaf(): dic[tree.letter] = path else: helper(tree.left, path + "0") helper(tree.right, path + "1") helper(tree, "") return dic def compress_string(inp, dic): """Create compressed string based on the dictionary created in earlier steps. >>> dict = {'a': '101', 'p': '00', 'e': '110', 's': '100', 'm': '01', 'l': '111'} >>> compressed = compress_string("sample", dict) >>> print(compressed) 1001010100111110 """ s = "" for i in inp: s += dic[i] return s def compare_lengths(self): """Compare amount of memory required to store the string pre-compression and post-compression, printing out the individual bit requirements and then the percent difference. """ len_difference = (len(self.raw_string) * 8) - len(self.compressed_string) percent_difference = (len_difference / (len(self.raw_string) * 8)) * 100 print("Original String Length (bits): " + str(len(self.raw_string) * 8) + " bits.") print("Compressed String Length (bits): " + str(len(self.compressed_string)) + " bits.") print("Compression decreases space required by ~" + "{0:.2f}".format(percent_difference) + "%.")
import psycopg2 def db_get_connection(): """ Return a database connection or None if error occurs """ try: connection = psycopg2.connect(user="duong", password="P@ssw0rd", host="127.0.0.1", port="5432", database="snoopy_kitty") return connection except Exception as error: print(error) return None def create_tables(): """ Create tables """ try: connection = db_get_connection() if not connection: print('ERROR: Connection db fail') return cur = connection.cursor() query = """ CREATE TABLE IF NOT EXISTS predict_correction ( id SERIAL NOT NULL PRIMARY KEY, upload_file_path TEXT NOT NULL, label INTEGER NOT NULL, created_on TIMESTAMP ); """ cur.execute(query) connection.commit() except Exception as error: print('ERROR: Create table fail -', error) connection.rollback() finally: cur.close() connection.close() def insert_row(data, table_name, default=True): """Insert data into table_name """ # print("INFO: Insert data into {}".format(table_name)) try: connection = db_get_connection() if not connection: print('ERROR: Connection db fail') return cur = connection.cursor() cols = 'DEFAULT,' if default else '' for i in range(len(data)-1): cols = cols + '%s,' cols = cols + '%s' query = 'INSERT INTO ' + table_name + ' VALUES (' + cols + ');' cur.execute(query, data) connection.commit() except Exception as error: print('ERROR: Insert into DB fail -', error) connection.rollback() finally: cur.close() connection.close()
import random import math def fill(minsize, maxsize, constant, random_on_x = False, random_range = 10) -> set: size = random.randint(minsize, maxsize) answer = set() while len(answer) < size: random_value = random.randint(0, random_range) if random_on_x: value = (random_value, constant) else: value = (constant, random_value) if value not in answer: answer.add(value) return answer def confs(): answer = [] cat = (5, 5) for i in range(100): wall_amount = random.randint(0, 5) walls = [ ( random.randint(0, 10), random.randint(0, 10) ) for _ in range(wall_amount) ] if cat in walls: walls.remove(cat) #goals_amount = math.ceil(random.randint(25, 35)//3) goals = fill(25 // 3, 35 // 3, 0, True) goals.union(fill(25 // 3, 35 // 3, 10, True)) goals.union(fill(25 // 3, 35 // 3, 0, False)) answer.append(["{}".format(cat), "{}".format(walls), "{}".format(goals) ]) return answer
from Cell import Cell class Path: def __init__(self, begin_cell : Cell, reversed_direction = False): pass self.instructions = [] temp = begin_cell self.add_node(begin_cell, reversed_direction) while temp.previous is not None: self.add_node(temp.previous, reversed_direction) temp = temp.previous self.distance = len(self.instructions) - 1 def get_distance(self): return self.distance def get_positions(self): return list(map(lambda instruction: instruction[0], self.instructions)) def get_directions(self): return list(map(lambda instruction : instruction[1], self.instructions))[1:] def get_directions_str(self): return '\n'.join(self.get_directions()) def add_node(self, cell:Cell, inReverse): direction = None if cell.previous is not None: if inReverse: direction = cell.neighbors[cell.previous].invert() else: direction = cell.neighbors[cell.previous] value = ( (cell.xpos, cell.ypos), str(direction) ) if inReverse: self.instructions = [value] + self.instructions else: self.instructions.append(value) def __str__(self): return str(self.instructions)
def partition(A, p, r): x = A[r] i = p-1 for j in range(p, r): if A[j] <= x: i = i + 1 temp = A[i] A[i] = A[j] A[j] = temp temp = A[i+1] A[i+1] = A[r] A[r] = temp return i + 1 def quicksort(A, p, r): if p < r: q = partition(A, p, r) print(A, '\t', q) quicksort(A, p, q-1) quicksort(A, q+1, r) A1 = [2, 2, 2, 1, 3, 4, 3, 4, 3] print(A1) r = len(A1) - 1 p = 0 quicksort(A1, p, r) print(A1)
def check_pass(password): double_number = False for i in range(1, len(password)): if password[i - 1] > password[i]: return False if password[i - 1] == password[i]: double_number = True return double_number def check_pass_not_in_quad(password): double_number = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(1, len(password)): if password[i - 1] > password[i]: return False if password[i - 1] == password[i]: double_number[int(password[i])] = double_number[int(password[i])] + 1 for ele in double_number: if ele == 1: return True return False def parse_input(f): limits = list() for line in f: limits = line.split('-') limits[len(limits) - 1] = str(limits[len(limits) - 1]).replace('\n', '') return limits
''' Description: Version: 1.0 Author: hqh Date: 2021-05-11 10:31:13 LastEditors: hqh LastEditTime: 2021-05-11 10:51:04 ''' # # @lc app=leetcode.cn id=653 lang=python3 # # [653] 两数之和 IV - 输入 BST # # @lc code=start # 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 findTarget(self, root: TreeNode, k: int) -> bool: return self.findTar(root, k, root) def findTar(self, root, k, rt): if not root: return False t = k - root.val if t != root.val and self.findVal(rt, t): return True return self.findTar(root.left, k, rt) or self.findTar(root.right, k, rt) def findVal(self, rt, v): if not rt: return False if rt.val < v: return self.findVal(rt.right, v) if rt.val > v: return self.findVal(rt.left, v) return True # 大佬 # 遍历二叉树+HashSet # @lc code=end
''' Description: Version: 1.0 Author: hqh Date: 2021-05-15 23:13:08 LastEditors: hqh LastEditTime: 2021-05-15 23:26:14 ''' # # @lc app=leetcode.cn id=705 lang=python3 # # [705] 设计哈希集合 # # @lc code=start class MyHashSet: def __init__(self): """ Initialize your data structure here. """ self.d = {} def add(self, key: int) -> None: self.d[key] = True def remove(self, key: int) -> None: self.d[key] = False def contains(self, key: int) -> bool: """ Returns true if this set contains the specified element """ if key not in self.d: return False return self.d[key] # Your MyHashSet object will be instantiated and called as such: # obj = MyHashSet() # obj.add(key) # obj.remove(key) # param_3 = obj.contains(key) # @lc code=end
''' Description: Version: 1.0 Author: hqh Date: 2021-05-10 00:09:34 LastEditors: hqh LastEditTime: 2021-05-10 00:36:25 ''' # # @lc app=leetcode.cn id=606 lang=python3 # # [606] 根据二叉树创建字符串 # # @lc code=start # 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 tree2str(self, root: TreeNode) -> str: if root: l = self.tree2str(root.left) r = self.tree2str(root.right) v = str(root.val) if l: v += '(' + l + ')' elif r: v += '()' if r: v += '(' + r + ')' return v # @lc code=end
# # @lc app=leetcode.cn id=20 lang=python3 # # [20] 有效的括号 # # @lc code=start class Solution: def isValid(self, s: str) -> bool: st = [] for i in s: if i == '(' or i == '[' or i == '{': st.append(i) if i == ')': if st != [] and st[-1] == '(': st.pop() else: return False if i == ']': if st != [] and st[-1] == '[': st.pop() else: return False if i == '}': if st != [] and st[-1] == '{': st.pop() else: return False return st == [] # @lc code=end
def get_next(m, x, y): for next_y in range(y+1, 9): if m[x][next_y] == 0: return x, next_y for next_x in range(x+1, 9): for next_y in range(0, 9): if m[next_x][next_y] == 0: return next_x, next_y return -1, -1 def value(m, x, y): i, j = x//3, y//3 grid = [m[i*3+r][j*3+c] for r in range(3) for c in range(3)] v = set([x for x in range(1,10)]) - set(grid) - set(m[x]) - \ set(list(zip(*m))[y]) return v def start_pos(m): for x in range(9): for y in range(9): if m[x][y] == 0: return x, y return -1, -1 def try_sudoku(m, x, y): for v in value(m, x, y): if m[x][y] == 0: m[x][y] = v next_x, next_y = get_next(m, x, y) if next_y == -1: print(m) return True else: end = try_sudoku(m, next_x, next_y) if end: return True m[x][y] = 0 def sudoku(m): x, y = start_pos(m) for v in value(m, x, y): m[x][y] = v next_x, next_y = get_next(m, x, y) try_sudoku(m, next_x, next_y) if __name__ == "__main__": m = [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9] ] sudoku(m)
#! /usr/bin/python3 import time class Timer(): """Usage: with Timer(verbose=True) as t: timing_function() """ def __init__(self, verbose=False): self.verbose = verbose def __enter__(self): self.start = time.time() return self def __exit__(self, exc_type, exc_val, exc_tb): self.end = time.time() self.secs = self.end - self.start self.msecs = self.secs * 1000 if self.verbose: print('Running time {} s'.format(self.secs))
## Hacer un programa que dado un número de DNI obtenga la letra del NIF. ## La letra correspondiente a un número de DNI se calcula mediante el ## siguiente algoritmo: ## a) Se obtiene el resto de dividir el número de DNI entre 23. ## b) El número resultante nos indica la posición de la letra ## correspondiente a ese DNI, en la siguiente cadena: ## (Mirar lista/diccionario de Asignación) diccionarioAsignacion={ 0:"T", 1:"R", 2:"W", 3:"A", 4:"G", 5:"M", 6:"Y", 7:"F", 8:"P", 9:"D", 10:"X", 11:"B", 12:"N", 13:"J", 14:"Z", 15:"S", 16:"Q", 17:"V", 18:"H", 19:"L", 20:"C", 21:"K", 22:"E" } listaAsignacion=["T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E"] def calcularLetraNIF(dni): for numero in dni: def esCorrecto(DNI): if len(DNI) != 9: print("No has introducido un DNI") return False for posicion in DNI: if 0 <= DNI.index(posicion) <= 7 and posicion.isdigit() != True: return False else DNI.index(posicion) == 8 and posicion.islower() and (posicion.isalpha() or posicion.isdigit()): return False return True
# coding = utf-8 class Cliente: def __init__(self, nombre, apellidos, direccion, telefono, nif, saldo=0): self.nombre = nombre self.apellidos = apellidos self.direccion = direccion self.telefono = telefono self.nif = nif self.saldo = saldo def __repr__(self): return self.nombre + " " + self.apellidos + ", " + self.direccion + ", " + str(self.telefono) + ", " + str(self.nif) + ", " + str(self.saldo) def setNombre(self, nombre): self.nombre = nombre def getNombre(self): return self.nombre def setApellidos(self, apellidos): self.apellidos = apellidos def getApellidos(self): return self.apellidos def setDireccion(self, direccion): self.direccion = direccion def getDireccion(self): return self.direccion def setTelefono(self, telefono): self.telefono = telefono def getTelefono(self): return self.telefono def setNif(self, nif): self.nif = nif def getNif(self): return self.nif def setSaldo(self, saldo): self.saldo = self.saldo def getSaldo(self): return saldo def retirarDinero(self, cantidad): if cantidad <= self.saldo: self.saldo -= cantidad else: print("No dispones de suficiente Saldo") def ingresarDinero(self, cantidad): self.saldo += cantidad def consultarCuenta(self): return print(self) def saldoNegativo(self): if self.saldo < 0: return True return False def crearCliente(): nombre = input("Introduce el nombre del Cliente\n") apellidos = input("Introduce los apellidos del Cliente\n") direccion = input("Introduce la dirección del Cliente\n") telefono = input("Introduce el teléfono del Cliente\n") nif = input("Introduce el NIF del Cliente\n") saldo = input("Introduce el saldo del Cliente\n") cliente = Cliente(nombre, apellidos, direccion, telefono, nif, saldo) return cliente def almacenarCliente(cliente, nif): clientes[nif] = cliente clientes = {} def nuevoCliente(): cliente = crearCliente() almacenarCliente(cliente, cliente.getNif()) #class CuentaCorriente: #def __init__(self) #guille = Cliente("Guille", "Cirer", "casa", 123456, 43215678) #lluis = Cliente("Lluis", "Cifre Font", "casa", 123456, 43215678, 100) numeroClientes = input("Cuantos nuevos clientes quieres introducir") for numCliente in range(0, numeroCliente, 1) nuevoCliente()
# Escribe un programa que pida por teclado el radio de una circunferencia, y que a continuación # calcule y escriba en pantalla la longitud de la circunferencia y del área del círculo. # # Autor: Luis Cifre # # Casos tipo: # # Radio = 5, Longuitud = 2·pi·Radio, Área = pi·Radio^2 import math radio = int(input("Escribe el radio de una circunferencia: ")) print "La longuitud de la circunferencia es: ", radio*2*math.pi print "El área de la circunferencia es: ", math.pi*radio**2
#-*- coding: UTF-8 -*- tal = raw_input('Captcha? ') #submit the number given talc = len(tal)/2 q = len(tal) - 1 svar = 0 for i in range(len(tal)): global svar if (i + talc) <= q: if tal[i] == tal[i+talc]: svar += int(tal[i]) else: if tal[i] == tal[i-talc]: svar += int(tal[i]) print svar
"""CSC111 Winter 2021 Assignment 3: Graphs, Recommender Systems, and Clustering (Part 1) Instructions (READ THIS FIRST!) =============================== This Python module contains the modified graph and vertex classes you'll be using as the basis for this assignment, as well as additional functions for you to complete in this part. Copyright and Usage Information =============================== This file is provided solely for the personal and private use of students taking CSC111 at the University of Toronto St. George campus. All forms of distribution of this code, whether as given or with any changes, are expressly prohibited. For more information on copyright for CSC111 materials, please consult our Course Syllabus. This file is Copyright (c) 2021 David Liu and Isaac Waller. """ from __future__ import annotations import csv from typing import Any # Make sure you've installed the necessary Python libraries (see assignment handout # "Installing new libraries" section) import networkx as nx # Used for visualizing graphs (by convention, referred to as "nx") class _Vertex: """A vertex in a book review graph, used to represent a user or a book. Each vertex item is either a user id or book title. Both are represented as strings, even though we've kept the type annotation as Any to be consistent with lecture. Instance Attributes: - item: The data stored in this vertex, representing a user or book. - kind: The type of this vertex: 'user' or 'book'. - neighbours: The vertices that are adjacent to this vertex. Representation Invariants: - self not in self.neighbours - all(self in u.neighbours for u in self.neighbours) - self.kind in {'user', 'book'} """ item: Any kind: str neighbours: set[_Vertex] def __init__(self, item: Any, kind: str) -> None: """Initialize a new vertex with the given item and kind. This vertex is initialized with no neighbours. Preconditions: - kind in {'user', 'book'} """ self.item = item self.kind = kind self.neighbours = set() def degree(self) -> int: """Return the degree of this vertex.""" return len(self.neighbours) ############################################################################ # Part 1, Q3 ############################################################################ def similarity_score(self, other: _Vertex) -> float: """Return the similarity score between this vertex and other. See Assignment handout for definition of similarity score. """ if other.degree() == 0 or self.degree() == 0: return 0 else: sim_items = {item for item in self.neighbours if item in other.neighbours} total_items = self.neighbours.union(other.neighbours) return len(sim_items) / len(total_items) class Graph: """A graph used to represent a book review network. """ # Private Instance Attributes: # - _vertices: # A collection of the vertices contained in this graph. # Maps item to _Vertex object. _vertices: dict[Any, _Vertex] def __init__(self) -> None: """Initialize an empty graph (no vertices or edges).""" self._vertices = {} def add_vertex(self, item: Any, kind: str) -> None: """Add a vertex with the given item and kind to this graph. The new vertex is not adjacent to any other vertices. Do nothing if the given item is already in this graph. Preconditions: - kind in {'user', 'book'} """ if item not in self._vertices: self._vertices[item] = _Vertex(item, kind) def add_edge(self, item1: Any, item2: Any) -> None: """Add an edge between the two vertices with the given items in this graph. Raise a ValueError if item1 or item2 do not appear as vertices in this graph. Preconditions: - item1 != item2 """ if item1 in self._vertices and item2 in self._vertices: v1 = self._vertices[item1] v2 = self._vertices[item2] v1.neighbours.add(v2) v2.neighbours.add(v1) else: raise ValueError def adjacent(self, item1: Any, item2: Any) -> bool: """Return whether item1 and item2 are adjacent vertices in this graph. Return False if item1 or item2 do not appear as vertices in this graph. """ if item1 in self._vertices and item2 in self._vertices: v1 = self._vertices[item1] return any(v2.item == item2 for v2 in v1.neighbours) else: return False def get_neighbours(self, item: Any) -> set: """Return a set of the neighbours of the given item. Note that the *items* are returned, not the _Vertex objects themselves. Raise a ValueError if item does not appear as a vertex in this graph. """ if item in self._vertices: v = self._vertices[item] return {neighbour.item for neighbour in v.neighbours} else: raise ValueError def get_all_vertices(self, kind: str = '') -> set: """Return a set of all vertex items in this graph. If kind != '', only return the items of the given vertex kind. Preconditions: - kind in {'', 'user', 'book'} """ if kind != '': return {v.item for v in self._vertices.values() if v.kind == kind} else: return set(self._vertices.keys()) def to_networkx(self, max_vertices: int = 5000) -> nx.Graph: """Convert this graph into a networkx Graph. max_vertices specifies the maximum number of vertices that can appear in the graph. (This is necessary to limit the visualization output for large graphs.) Note that this method is provided for you, and you shouldn't change it. """ graph_nx = nx.Graph() for v in self._vertices.values(): graph_nx.add_node(v.item, kind=v.kind) for u in v.neighbours: if graph_nx.number_of_nodes() < max_vertices: graph_nx.add_node(u.item, kind=u.kind) if u.item in graph_nx.nodes: graph_nx.add_edge(v.item, u.item) if graph_nx.number_of_nodes() >= max_vertices: break return graph_nx ############################################################################ # Part 1, Q3 ############################################################################ def get_similarity_score(self, item1: Any, item2: Any) -> float: """Return the similarity score between the two given items in this graph. Raise a ValueError if item1 or item2 do not appear as vertices in this graph. >>> g = Graph() >>> for i in range(0, 6): ... g.add_vertex(str(i), kind='user') >>> g.add_edge('0', '2') >>> g.add_edge('0', '3') >>> g.add_edge('0', '4') >>> g.add_edge('1', '3') >>> g.add_edge('1', '4') >>> g.add_edge('1', '5') >>> g.get_similarity_score('0', '1') 0.5 """ if item1 not in self._vertices or item2 not in self._vertices: raise ValueError else: return self._vertices[item1].similarity_score(self._vertices[item2]) ############################################################################ # Part 1, Q4 ############################################################################ def recommend_books(self, book: str, limit: int) -> list[str]: """Return a list of up to <limit> recommended books based on similarity to the given book. The return value is a list of the titles of recommended books, sorted in *descending order* of similarity score. Ties are broken in descending order of book title. That is, if v1 and v2 have the same similarity score, then v1 comes before v2 if and only if v1.item > v2.item. The returned list should NOT contain: - the input book itself - any book with a similarity score of 0 to the input book - any duplicates - any vertices that represents a user (instead of a book) Up to <limit> books are returned, starting with the book with the highest similarity score, then the second-highest similarity score, etc. Fewer than <limit> books are returned if and only if there aren't enough books that meet the above criteria. Preconditions: - book in self._vertices - self._vertices[book].kind == 'book' - limit >= 1 """ dictionary_var = {} list_of_scores = [] list_var = [] for x in self._vertices: if x != book and self._vertices[x].kind == 'book': sim_score = self.get_similarity_score(book, x) if sim_score in dictionary_var: dictionary_var[sim_score].append(x) else: dictionary_var[sim_score] = [x] for score_var in dictionary_var: list_of_scores.append(score_var) list_of_scores_sorted = sorted(list_of_scores, reverse=True) # we will now make the dictionary dictionary_var sorted for y in dictionary_var: dictionary_var[y] = sorted(dictionary_var[y], reverse=True) for z in list_of_scores_sorted: if z != 0: names = dictionary_var[z] for i in names: list_var.append(i) # Keeps everything sorted if len(list_var) > limit: return list_var[:limit] return list_var ################################################################################ # Part 1, Q1 ################################################################################ def load_review_graph(reviews_file: str, book_names_file: str) -> Graph: """Return a book review graph corresponding to the given datasets. The book review graph stores one vertex for each user and book in the datasets. Each vertex stores as its item either a user ID or book TITLE (the latter is why you need the book_names_file). Use the "kind" _Vertex attribute to differentiate between the two vertex types. Edges represent a review between a user and a book. In this graph, each edge only represents the existence of a review---IGNORE THE REVIEW SCORE in the datasets, as we don't have a way to represent these scores (yet). Preconditions: - reviews_file is the path to a CSV file corresponding to the book review data format described on the assignment handout - book_names_file is the path to a CSV file corresponding to the book data format described on the assignment handout >>> g = load_review_graph('data/reviews_small.csv', 'data/book_names.csv') >>> len(g.get_all_vertices(kind='book')) 4 >>> len(g.get_all_vertices(kind='user')) 5 >>> user1_reviews = g.get_neighbours('user1') >>> len(user1_reviews) 3 >>> "Harry Potter and the Sorcerer's Stone (Book 1)" in user1_reviews True """ curr_graph = Graph() # return a dictionary containing book id to book title book_id_to_names = read_book_names(book_names_file) # add user to graph with open(reviews_file) as csv_file: csv_reader = csv.reader(csv_file) for row in csv_reader: curr_graph.add_vertex(row[0], 'user') curr_graph.add_vertex(book_id_to_names[row[1]], 'book') curr_graph.add_edge(row[0], book_id_to_names[row[1]]) return curr_graph def read_book_names(read_file: str) -> dict: """ Helper function that reads the book name file and returns a dictionary mapping the book id to the book name""" dict_books = dict() with open(read_file) as csv_file: csv_reader = csv.reader(csv_file) for row in csv_reader: dict_books[row[0]] = row[1] return dict_books if __name__ == '__main__': # You can uncomment the following lines for code checking/debugging purposes. # However, we recommend commenting out these lines when working with the large # datasets, as checking representation invariants and preconditions greatly # increases the running time of the functions/methods. # import python_ta.contracts # python_ta.contracts.check_all_contracts() import doctest doctest.testmod() import python_ta python_ta.check_all(config={ 'max-line-length': 1000, 'disable': ['E1136'], 'extra-imports': ['csv', 'networkx'], 'allowed-io': ['load_review_graph'], 'max-nested-blocks': 4 })
num = input() first = 0 second = 0 third = 0 for i in range(0, len(num)): if num[i] == '1': first += 1 elif num[i] == '2': second += 1 elif num[i] == '3': third += 1 x = "1+"*first + "2+"*second + "3+"*third print(x[:-1])
#operacion-INDEXACION_14 # 0 10 20 30 40 # 01234567890123456789012345678901234567890123 str="abcdefghijklmnñopqrstuvwxyz0123456789@#+-*/" #No se que decir print("#"*25) print(" "*7+str.upper()[20]+str.upper()[8]+str.upper()[13]+str.upper()[2]+str.upper()[0]+" "+str.upper()[5] +str.upper()[0]+str.upper()[19]+str.upper()[20]) print("#"*25)
#Ejericicio-ITERACION 08 msg="La serpiente generalmente causa temor en la mayoria" contador_a=0 contador_e=0 contador_i=0 contador_o=0 contador_u=0 for letra in msg: if (letra == 'a'): contador_a+=1 if (letra == 'e'): contador_e+=1 if (letra == 'i'): contador_i+=1 if (letra == 'o'): contador_o+=1 if (letra == 'u'): contador_u+=1 # Contar cuantas vocales existen en la cadena print("A: ",contador_a) print("E: ",contador_e) print("I: ",contador_i) print("O: ",contador_o) print("U: ",contador_u)
-*- coding: utf-8 -*- import pandas as pd from email.parser import Parser def parse_email(row, attribute): email = Parser().parsestr(row['message']) if attribute == 'content': return email.get_payload() else: return email[attribute] def split_email_addresses(line): """To separate multiple email addresses""" if line: addrs = line.split(',') addrs = map(lambda x: x.strip(), addrs) else: addrs = None return addrs def conversation(row): """To mark conversation instances""" if row['Recipients'] is None: return None elif row['Subject2'] == '' or row['Subject2'] == '(no subject)': return None elif row['count'] == 1: return 'single conversation' else: return 'Undefined' file_path = raw_input('CSV file pathname: ') # -------------------------------------------- Process File ------------------------------------------- # Extract required fields from messages emails = pd.read_csv(file_path) emails['Datetime'] = emails.apply(parse_email, axis=1, args=('date',)) emails['Sender'] = emails.apply(parse_email, axis=1, args=('from',)) emails['Recipients'] = emails.apply(parse_email, axis=1, args=('to',)) emails['Subject'] = emails.apply(parse_email, axis=1, args=('subject',)) emails['Content'] = emails.apply(parse_email, axis=1, args=('content',)) # Drop duplicate emails emails = emails.drop_duplicates(subset=['Datetime', 'Sender', 'Recipients', 'Subject', 'Content']) # Sort by Datetime emails['Datetime'] = pd.to_datetime(emails['Datetime']) emails['Time sent'], emails['Date sent'] = emails['Datetime'].apply(lambda x: x.time()), \ emails['Datetime'].apply(lambda x: x.date()) emails = emails.sort_values(by='Datetime', ascending=True) # Clean Recipients (split) and Subject columns emails['Subject2'] = \ emails['Subject'].apply(lambda x: x.replace('RE:', '').replace('Re:', '').replace('FW:', '').strip()) emails['Recipients'] = emails['Recipients'].map(split_email_addresses) # ------------------------------------------ Extract Conversations ------------------------------------- emails['count'] = emails.groupby('Subject2')['Subject2'].transform('count') pd.isnull(emails['Recipients']) # Mark None and 'single conversations' emails['Conversation'] = emails.apply(conversation, axis=1) # ====== Mark conversations between single addresses ======= sub_df = emails[['Sender', 'Recipients', 'Datetime', 'Subject', 'Subject2', 'Content', 'count', 'Conversation']].\ dropna() # drop emails sending to multiple addresses sub_df = sub_df.loc[(sub_df['Recipients'].map(len) == 1) & (sub_df['Conversation'] != 'single conversation')]
import random import random class SimuladorDeDado: def __init__(self): self.valor_minimo = 1 self.valor_maximo = 6 def Iniciar(self): # ler os valores da tela self.eventos, self.valores = self.janela.Read() # fazer alguma coisa com esses valores try: if self.eventos == 'sim' or self.eventos == 's': self.GerarValorDoDado() elif self.eventos == 'Não' or self.eventos == 'n': print('Agrecemos a sua participação!') else: print('Favor digitar sim ou não') except: print('Ocorreu um erro ao receber sua resposta') def GerarValorDoDado(self): print(random.randint(self.valor_minimo,self.valor_maximo)) simulador = SimuladorDeDado() simulador.Iniciar()