text
stringlengths
37
1.41M
import random class BinaryHeap(object): def __init__(self): self.heap = [] # * * * * * # Pushes an element into the heap # * * * * * def push(self, x): self.heap.append(x) self.heapifyUp(self.size() - 1) # * * * * * # Pops an element out of the heap # * * * * * def pop(self): min = self.heap[0] self.heap[0] = self.heap[self.size() - 1] self.heap.pop() if self.size() > 1: self.heapifyDown(0) return min # * * * * * # returns the size of the heap # * * * * * def size(self): return len(self.heap) def smaller_child(self, parent): i = (parent << 1) + 2 if i > (self.size() - 1): return i - 1 elif self.heap[i - 1] < self.heap[i]: return i - 1 else: return i def parent (self, child): if (child != 0): i = (child - 1) >> 1 return i else: return -3 # * * * * * # When you add an element to the heap, we want to # insert it in the last spot and then move it upwards # by comparing to parent nodes, if smaller then # swapping occurs, this is repeated until in order. # * * * * * def heapifyUp (self, current): mother = self.parent(current) while current > 0 and mother>= 0 and self.heap[mother] > self.heap[current]: self.heap[mother], self.heap[current] = self.heap[current], self.heap[mother] current = self.parent(current) mother = self.parent(current) # * * * * * # When you remove an element from the heap # we want to maintain the structure of the heap # so we move everything down a spot by comparing # the key of the parent node with the children, if # children have lower priority, it is swapped, and is # repeated for newly swapped nodes until heap is # re-established # * * * * * def heapifyDown (self, current): while ((current << 1) + 1) <= (self.size() - 1): child = self.smaller_child(current) if self.heap[current] > self.heap[child]: self.heap[current], self.heap[child] = self.heap[child], self.heap[current] current = child # * * * * * # Defines a functional call which allows us to check # whether the BinaryHeap is working properly # * * * * * def main(): a = BinaryHeap() for each in range(10): a.push(random.randint(0,50)) print a.heap for each in range(10): print a.pop()
class MyStack: def __init__(self): self.__myStack = [] def show(self): return self.__myStack def isEmpty(self): return self.__myStack == [] def push(self, x): self.__myStack = [x] + self.__myStack def pop(self): self.__myStack = self.__myStack[1:] def top(self): return self.__myStack[0] class MyQueue: def __init__(self): self.__myQueue = [] def show(self): return self.__myQueue def isEmpty(self): return self.__myQueue == [] def enqueue(self, x): self.__myQueue = self.__myQueue + [x] def dequeue(self): self.__myQueue = self.__myQueue[1:] def head(self): return self.__myQueue[0] class MySet: def __init__(self): self.__mySet = [] def show(self): return self.__mySet def isEmpty(self): return self.__mySet == [] def isEl(self, x): return x in self.__mySet def insert(self, x): if not(self.isEl(x)): self.__mySet = self.__mySet.append(x) # return self def remove(self, x): self.__mySet = self.__mySet.pop(x) # return self stack = MyStack() queue = MyQueue() cool_set = MySet()
from pyfirmata import Arduino, util import time # Class for handling calls to the soil sensor. class SoilSensorValues(object): temperature = 0.0 humidity = 0.0 def __init__(self, board): '''Set up the board callbacks''' self.board = board self.board.add_cmd_handler(0x04, self.handleTemperature) # Attach temperature handler. self.board.add_cmd_handler(0x05, self.handleHumidity) # Attach humidity handler. self.temperature = 0.0 self.temperatureSentinel = False self.humidity = 0.0 self.humiditySentinel = False def getTemperature(self): ''' Make the asynchronous call synchronous. We set a sentinal value and wait until it becomes true. In this naive version we will wait forever.''' self.temperatureSentinel = False board.send_sysex(0x04) # Send the temperature command. while not self.temperatureSentinel: time.sleep(0.01) # Sleep waiting for the value to come back. return self.temperature def getHumidity(self): ''' Make the asynchronous call synchronous. We set a sentinal value and wait until it becomes true. In this naive version we will wait forever.''' self.humiditySentinel = False board.send_sysex(0x05) # Send the temperature command. while not self.humiditySentinel: time.sleep(0.01) # Sleep waiting for the value to come back. return self.humidity def handleTemperature(self, *data): strRes = util.two_byte_iter_to_str(data[2:]) self.temperature = float(strRes) self.temperatureSentinel = True def handleHumidity(self, *data): strRes = util.two_byte_iter_to_str(data[2:]) self.humidity = float(strRes) self.humiditySentinel = True def simpleFunc(s): print '{0:c}'.format(s) def ToBytes(num): h = int(num/100) if (h > 0): num = num - (h*100) t = int(num/10) if (t > 0): num = num - (t*10) o = int(num) return([chr(h),chr(t),chr(o)]) def SetPixel(pixNum, R, G, B): bArray = [] bArray.append(chr(pixNum)) # The pixel number bArray += ToBytes(R) bArray += ToBytes(G) bArray += ToBytes(B) return bArray board = Arduino('/dev/ttyATH0', baudrate=115200) valuesHandler = SoilSensorValues(board) it = util.Iterator(board) it.start() # Start getting data #board.send_sysex(0x03, ['\x01', '\x00', '\x00', '\x00', '\x02', '\x05', '\x05', '\x00', '\x00', '\x00']) #board.send_sysex(0x03, SetPixel(0, 255, 0, 255)) #print 'Have sent sysex' #time.sleep(0.5) for i in range(20): print "Temperature: ", valuesHandler.getTemperature() print "Humidity: ", valuesHandler.getHumidity() time.sleep(0.5) board.exit()
import itertools def dict_cross_product(atosetb): """Takes a dictionary mapping values of type a to sets of values of type b (think of it as having buckets of bs labeled with as) and return an iterable of dicts representing all possible combinations of choosing one element out of each bucket. """ bucket_contents = ( frozenset((a,b) for b in bs) for a,bs in atosetb.items()) return map(dict, itertools.product(*bucket_contents)) def __dict_cross_product(possible_paths): dcp = dict_cross_product(possible_paths) return set(map(lambda d: frozenset().union(*d.values()), dcp))
""" Вычисление среднего суммы и количества """ import random def random_list(length): """ full random list with length length""" numbers = [] for num in range(length): numbers.append(random.randint(0,100)) return numbers def average(values): average = 0.0 for value in values: average+=value return (average/len(values)) def summa(values): summa = 0 for value in values: summa+=value return summa numbers = [] while True: line=input("Enter a number: ") if line =='done': break try: number=int(line) numbers.append(number) print(number) except ValueError: print ('bad number') if len(numbers) ==0: print('Not numbers') else: print (average(numbers),summa(numbers),len(numbers))
friends = ['andrey','tanya','ira'] for friend in friends: print ('Happay',friend) print ('Done') import random def mini(values): smallest = None for value in values: if smallest is None or value<smallest: smallest=value return smallest count = 0 total = 0 largest = 0 for iterval in range(10): count = count + 1 total += iterval value = random.randint(0,100) if largest is None or value>largest: largest = value print ('Value:',value,'Largest:',largest) print ('Count:',count,' Total:',total) list_number=[] for num in range(10): list_number.append(random.randint(0,100)) print (list_number) minimum=mini(list_number) print ('minimum:',minimum)
#get name and age and output year they will turn 100 years old name = str(input("Enter in your name: ")) age = int(input("Enter in your age: ")) hunnid = 100 - age print("Your name is ", name, " and you will be 1 hundred year old in the year ", str(int(2018 + hunnid))) #extras 1: output = int(input("Enter in a number: ")) for i in range(output): print("Your name is ", name, " and you will be 1 hundred year old in the year ", str(int(2018 + hunnid)))
''' Purpose :- To get more familier with if else logic Author :- Dipayan Dutta ''' #read first number first_number = input("Enter First Number[integer only] ") #read second number second_number = input ('Enter second number [integer only] ') #now checking starts if (first_number == second_number): print "Both Numbers are same" elif(first_number > second_number): print "First Number is Greatr Than Second Number" else: print "Second number is Greate Than First Number"
value = input().split() a, b = value a = int(a) b = int(b) if a>b: if a%b == 0: print("Sao Multiplos") else: print("Nao Sao Multiplos") if b>a: if b%a == 0: print("Sao Multiplos") else: print("Nao Sao Multiplos") if a==b: print("Sao multiplos")
x = input().split() x = list(map(float,x)) a, b, c = sorted(x)[::-1] go = True if a>=b+c: print("NAO FORMA TRIANGULO") go = False if a**2 == ((b**2)+(c**2)) and go: print("TRIANGULO RETANGULO") if a**2 > ((b**2)+(c**2)) and go: print("TRIANGULO OBTUSANGULO") if a**2 < ((b**2)+(c**2)) and go: print("TRIANGULO ACUTANGULO") if a==b and a==c and b==c and go: print("TRIANGULO EQUILATERO") if (a==b or b==c) and not (a==b and b==c) and go : print("TRIANGULO ISOSCELES")
import turtle turtle.goto(0,0) up = 0 down = 1 right = 2 left = 3 direction = None def UP(): global direction direction = up print("you pressed the UP key") on_move() turtle.onkey(UP, "Up") #turtle.listen() def DOWN(): global direction direction = down print("you pressed the DOWN key") on_move() turtle.onkey(DOWN,"Down") #turtle.listen() def RIGHT(): global direction direction = right print("you pressed the RIGHT key") on_move() turtle.onkey(RIGHT, "Right") #turtle.listen() def LEFT(): global direction direction = left print("you pressed the LEFT key") on_move() turtle.onkey(LEFT,"Left") turtle.listen() def on_move(): x,y = turtle.pos() if direction == up: turtle.goto(x,y+10) elif direction == down: turtle.goto(x,y-10) elif direction == right: turtle.goto(x+10,y) elif direction == left: turtle.goto(x-10,y)
text = input("Enter Your Text: \n").title() for i in ['.' , '?' , '/' , '!' , '<' , '>' , ','] : text = text.replace(i," ") words_list , counter = list(filter(lambda x : x !="", text.split(" ") )) , dict() for i in set(words_list) : counter[i] = words_list.count(i) for i in counter : print(f" {i} : {counter[i]} ") print("\n Most Repeeted Words : ",list(filter(lambda x : max(counter.values()) in x , counter.items())))
import tkinter as tk from tkinter import StringVar import math win = tk.Tk() win.title("Calculator") win.resizable(False, False) xPos = int(win.winfo_screenwidth()/2 - win.winfo_reqwidth()) yPos = int(win.winfo_screenheight()/2 - win.winfo_reqheight()) win.geometry("+{}+{}".format(xPos, yPos)) win.geometry("347x570") win.config(bg="gray25") #win.attributes("-transparentcolor", "dodger blue") res = StringVar() vara = StringVar() varb = StringVar() save = StringVar() save2 = StringVar() entrya = tk.Entry(win, width=20, textvariable = vara, bg="bisque", justify = tk.CENTER, font = ('courier', 24, 'bold')) entrya.place(x=231, y=10, width=100, height=80) entryb = tk.Entry(win, width=20, textvariable = varb, bg="bisque", justify = tk.CENTER, font = ('courier', 24, 'bold')) entryb.place(x=231, y=95, width=100, height=80) entryres = tk.Label(win, text="RESULT", textvariable = res, relief="solid", font=("Courier",25,'bold'), anchor='w') entryres.place(x=16, y=185, width=315, height=80) saveVal = tk.Label(win, text="SAVE", textvariable = save, font=("Courier",20,'bold'), anchor='w') saveVal.place(x=16, y=130, width = 100) #saveVal2 = tk.Label(win, text="SAVE", textvariable = save2, font=("Courier",30,'bold'), anchor='e') #saveVal2.place(x=231, y=130, width = 100) def add(entrya, entryb, res): aval = entrya.get() bval = entryb.get() try: b = int(bval) a = int(aval) except ValueError: return False res.set(a + b) def diff(entrya, entryb, entryres): aval = entrya.get() bval = entryb.get() try: b = int(bval) a = int(aval) except ValueError: return False res.set(a - b) def multiply(entrya, entryb, entryres): aval = entrya.get() bval = entryb.get() try: b = int(bval) a = int(aval) except ValueError: return False res.set(a * b) def divide(entrya, entryb, entryres): aval = entrya.get() bval = entryb.get() try: b = int(bval) a = int(aval) except ValueError: return False res.set(float(a / b)) def square(entrya, entryres): if vara.get() != "": aval = entrya.get() try: a = int(aval) except ValueError: return False save.set(a) res.set(int(save.get()) * int(save.get())) vara.set("") return else: resval = res.get() try: r = int(resval) except ValueError: return False save.set(r) res.set(int(save.get()) * int(save.get())) def squareRoot(entrya, entryres): if vara.get() != "": sqr = math.sqrt(float(vara.get())) strsqr = str(sqr) if strsqr[len(strsqr)-1] == '0' and strsqr[len(strsqr)-2] == '.': res.set(int(sqr)) else: res.set(sqr) vara.set("") return else: sqr = math.sqrt(float(res.get())) strsqr = str(sqr) if strsqr[len(strsqr)-1] == '0' and strsqr[len(strsqr)-2] == '.': res.set(int(sqr)) else: res.set(sqr) tk.Button(win, text="+", font=("arial", 20, "bold"), bg="salmon3", width=5, height=3, command = lambda: add(entrya, entryb, res)).place(x=16, y=282) tk.Button(win, text="-", font=("arial", 20, "bold"), bg="salmon3", width=5, height=3, command = lambda: diff(entrya, entryb, entryres)).place(x=16, y=421) tk.Button(win, text="X", font=("arial", 20, "bold"), bg="salmon3", width=5, height=3, command = lambda: multiply(entrya, entryb, entryres)).place(x=121, y=282) tk.Button(win, text="/", font=("arial", 20, "bold"), bg="salmon3", width=5, height=3, command = lambda: divide(entrya, entryb, entryres)).place(x=121, y=421) tk.Button(win, text="^2", font=("arial", 20, "bold"), bg="dark slate blue", width=5, height=3, command = lambda: square(entrya, entryres)).place(x= 226, y=282) tk.Button(win, text="√", font=("arial", 20, "bold"), bg="dark slate blue", width=5, height=3, command = lambda: squareRoot(entrya, entryres)).place(x=226, y=421) win.mainloop()
import datetime now = datetime.datetime.now() pre = datetime.datetime(2018,9,8) print(now) print(pre) print(now>pre) #최근 날짜가 더 큼 print(type(now)) print(type(pre)) test_date = "2018-09-07 18:58:09" convert_date = datetime.datetime.strptime(test_date, "%Y-%m-%d %H:%M:%S") print(convert_date) print(type(convert_date)) print(now>convert_date) three_minutes_later = convert_date+ datetime.timedelta(minutes=3) print(three_minutes_later)
# Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь. # https://drive.google.com/file/d/1HukSj3fYH8tXmKDe1MjwcJUlp58W1QMs/view?usp=sharing number = int(input("Введите трёхзначное число")) a = number%10 number = number//10 b = number%10 number = number//10 c = number%10 print(a+b+c) print(a*b*c)
import re pattern = '^[aeiou]\w*[^aeiou]$' #pattern starts with vowel, any alphanumeric in between and ends with cons def isGoodWord(inStr): res = inStr.split() #splits the string using any delimiter. default is space for i in range(0,len(res)): if(re.match(pattern, res[i].lower())): #matches the pattern print(res[i]) # Main Code strx = str(input("Input: ")) isGoodWord(strx)
twice = '' print(type(twice)) freq_dict = {} frequency = 0 while isinstance(twice, int) == False: with open('adventofcode1_input.txt','r') as file: for lines in file: lines = lines.rstrip("\n") frequency += int(lines) if frequency not in freq_dict: freq_dict[frequency] = 1 else: twice = frequency break print(type(twice)) print(twice) print(twice)
words = input().split(' ') searched_word = input() palindromes_words = list(filter(lambda x: x == x[::-1], words)) count = palindromes_words.count(searched_word) print(palindromes_words) print(f'Found palindrome {count} times')
def command(a): result = [] if a == 'even': for even in numbers: if even % 2 == 0: result.append(even) elif a == 'odd': for odd in numbers: if odd % 2 != 0: result.append(odd) elif a == 'negative': for negative in numbers: if negative < 0: result.append(negative) elif a == 'positive': for positive in numbers: if positive >= 0: result.append(positive) return result counter = int(input()) numbers = [] for i in range(counter): numbers.append(int(input())) print(command(input()))
size = int(input()) current = 1 step = 1 for row in range(size * 2): for col in range(0, current): print('*', end='') if current == size: step = -1 current += step print()
command = input() coffees_count = 0 while command != 'END' and coffees_count <= 5: if command.islower(): if command == 'coding': coffees_count += 1 elif command == 'dog' or command == 'cat': coffees_count += 1 elif command == 'movie': coffees_count += 1 elif command.isupper(): if command == 'CODING': coffees_count += 2 elif command == 'DOG' or command == 'CAT': coffees_count += 2 elif command == 'MOVIE': coffees_count += 2 command = input() if coffees_count > 5: print('You need extra sleep') else: print(coffees_count)
def fix_calendar(nums): while True: counter = 0 for i in range(len(nums)): if i < len(nums) - 1: if nums[i] > nums[i + 1]: nums[i], nums[i + 1] = nums[i + 1], nums[i] break else: counter += 1 if counter == len(nums): return nums else: if nums[i] < nums[i - 1]: nums[i], nums[i - 1] = nums[i - 1], nums[i] else: counter += 1 if counter == len(nums): return nums numbers = [42, 37, 41, 39, 38, 40, 43] fixed = fix_calendar(numbers) print(fixed)
n = int(input()) for i in range(1, n + 1): digit = i sum = 0 while i: sum += i % 10 i //= 10 if sum == 5 or sum == 7 or sum == 11: print(f'{digit} -> True') else: print(f'{digit} -> False')
even = set() odd = set() for i in range(1, int(input()) + 1): name_sum = sum([ord(x) for x in input()]) // i if name_sum % 2 == 0: even.add(name_sum) else: odd.add(name_sum) if sum(even) == sum(odd): arg = list(map(str, even.union(odd))) print(", ".join(arg)) elif sum(even) < sum(odd): arg = list(map(str, odd.difference(even))) print(", ".join(arg)) elif sum(even) > sum(odd): arg = list(map(str, even.symmetric_difference(odd))) print(", ".join(arg))
n = int(input()) open = False balanced = True for i in range(n): letter = input() if open: if letter == ')': open = False continue if letter == '(': open = True if letter == ')': balanced = False if not open and balanced: print('BALANCED') else: print('UNBALANCED')
word = input() while word != "end": print(f"{word} = {word[::-1]}") word = input()
class Party: def __init__(self): self.party_people = [] self.party_people_counter = 0 party = Party() people = input() while people != 'End': party.party_people.append(people) party.party_people_counter += 1 people = input() print(f'Going: {", ".join(party.party_people)}') print(f'Total: {party.party_people_counter}')
queue = list(reversed(input().split(', '))) wolf_found = False if queue[0] == 'wolf': print('Please go away and stop eating my sheep') wolf_found = True if not wolf_found: for animal in range(len(queue) - 1, -1, -1): if queue[animal] == 'wolf': print(f'Oi! Sheep number {animal}! You are about to be eaten by a wolf!')
year = int(input()) + 1 year = str(year) not_happy_year = True while not_happy_year: is_valid = True for digit in year: if year.count(digit) > 1: year = int(year) + 1 year = str(year) is_valid = False break if is_valid: not_happy_year = False break print(year)
def smallest_number(num1, num2, num3): smallest = min(num1, num2, num3) return smallest number_1 = int(input()) number_2 = int(input()) number_3 = int(input()) print(smallest_number(number_1, number_2, number_3))
word_to_remove = input() sequence = input() while word_to_remove in sequence: sequence = sequence.replace(word_to_remove, '') print(sequence)
cars_in_parking = set() for _ in range(int(input())): direction, car_number = input().split(", ") if direction == "IN": cars_in_parking.add(car_number) else: cars_in_parking.remove(car_number) if cars_in_parking: print("\n".join(cars_in_parking)) else: print("Parking Lot is Empty")
longest_intersection = [[]] for i in range(int(input())): data = input().split("-") first_start, first_end = list(map(int, data[0].split(","))) second_start, second_end = list(map(int, data[1].split(","))) first = set(x for x in range(first_start, first_end + 1)) second = set(x for x in range(second_start, second_end + 1)) intersection = first.intersection(second) if len(intersection) > len(longest_intersection[0]): longest_intersection.clear() longest_intersection.append(list(intersection)) print(f"Longest intersection is {longest_intersection[0]} with length {len(longest_intersection[0])}")
import math, random print 'Rounded Up 9.5:', math.ceil(9.5) print 'Rounded Down 9.5:', math.floor(9.5) num = 4 print num, 'squared:', math.pow(num, 2) print num, 'squared root:', math.sqrt(num) # 6 random numbers from list nums = random.sample(range(1, 49), 6) print 'Lucky numbers are:', nums # inaccurate item = 0.70 rate = 1.05 tax = item * rate total = item + rate print 'Item: \t', '%.2f' %item print 'Tax: \t', '%.2f' %tax print 'Total: \t', '%.2f' %total print '\nItem: \t', '%.20f' %item print 'Tax: \t', '%.20f' %tax print 'Total: \t', '%.20f' %total # list of Python modules installed in computer import pip installed_packages = pip.get_installed_distributions() installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages]) print installed_packages_list # decimal use when accuracy is very important from decimal import * item = Decimal(0.7) rate = Decimal(1.05) print '\nItem: \t', '%.20f' %item print 'Tax: \t', '%.20f' %tax print 'Total: \t', '%.20f' %total
class Node(object): def __init__(self,value): self.value=value self.nextnode=None self.prevnode=None a=Node(1) b=Node(2) c=Node(3) a.nextnode=b b.nextnode=c c.prevnode=b b.prevnode=a
def insertion_sort_recursive(A,n,next_el): if(next_el>=n-1): return pos = next_el temp = 0 while (pos > 0 and A[pos] < A[pos - 1]): temp = A[pos] A[pos] = A[pos - 1] A[pos - 1] = temp pos = pos - 1 insertion_sort_recursive(A,n,next_el+1) return print(insertion_sort_recursive([1,44,5,77,6,88],6,0))
'''Recursive Version of Binary Search def rec_bin_search(arr,ele): # Base Case! if len(arr) == 0: return False # Recursive Case else: mid = len(arr)/2 # If match found if arr[mid]==ele: return True else: # Call again on second half if ele<arr[mid]: return rec_bin_search(arr[:mid],ele) # Or call on first half else: return rec_bin_search(arr[mid+1:],ele)''' def bin_search(arr,ele): mid_pt=len(arr)//2 if(len(arr)%2!=0): mid_pt=mid_pt+1 if(arr[mid_pt]==ele): return True elif(ele>arr[mid_pt]): i=mid_pt+1 while i < len(arr): if(arr[i]==ele): return True i = i + 1 else: i = 0 while i < len(arr): if (arr[i] == ele): return True i = i + 1 return False print(bin_search([1,2,3],8)) """def binary_search(arr,ele): # First and last index values first = 0 last = len(arr) - 1 found = False while first <= last and not found: mid = (first+last)/2 # or // for Python 3 # Match found if arr[mid] == ele: found = True # Set new midpoints up or down depending on comparison else: # Set down if ele < arr[mid]: last = mid -1 # Set up else: first = mid + 1 return found"""
'''Sentence Reversal Problem Given a string of words, reverse all the words. For example: Given: 'This is the best' Return: 'best the is This' As part of this exercise you should remove all leading and trailing whitespace. So that inputs such as: ' space here' and 'space here ' both become: 'here space' ''' def rev_word1(s): s=s.strip() #print(s,"dee") print(" ".join(reversed(s.split()))) def rev_word2(s): s=s.strip() #print(s,"dee") print(" ".join(s.split()[::-1])) '''While these are valid solutions, in an interview setting you'll have to work out the basic algorithm that is used. In this case what we want to do is loop over the text and extract words form the string ourselves. Then we can push the words to a "stack" and in the end opo them all to reverse. Let's see what this actually looks like: ''' rev_word1("Deepu Mangal") rev_word2('Hi John, are you ready to go?') def rev_word3(s): spaces=[" "] words=[] length=len(s) i=0 while i<length: if(s[i] not in spaces): word_start=i while i<length and s[i] not in spaces: i+=1 words.append(s[word_start:i]) # Add to index i += 1 # Join the reversed words return " ".join(reversed(words)) print(rev_word3("Deepu Mangal"))
''''Finding the sum of n numbers recursively''' def recursion_n_num(n): if(n==1): return 1 elif(n==0): return 0 else: return n+recursion_n_num(n-1) print(recursion_n_num(4))
#implementation of Deques in Python class Deque(): def __init__(self): self.items=[] def addFront(self,item): return self.items.append(item) def addRear(self,item): return self.items.insert(0,item) def removeFront(self): return self.items.pop() def removeRear(self): return self.items.pop(0) def isEmpty(self): return self.items==[] def Size(self): return len(self.items) q=Deque() q.addFront(999) q.addFront("deee") q.addFront("mangal") q.addFront("mangal") print(q.removeFront()) print(q.removeRear()) q.addRear("mangal") print (q.isEmpty())
# save actual stdin in case we need it again later STD_IN = [ '5', '2 3 6 6 5', ] def input(): return STD_IN.pop(0) from itertools import product if __name__ == '__main__': n = int(input()) data = map(int, input().split(' ')) data = sorted(list(set(data))) print(data[-2])
""" Implement a function that replaces 'U'/'you' with 'your sister' Handle duplicate 'u's smartly. """ import re TARGET = 'u' TOKEN = '*' REPLACE_STRING = 'your sister' # def autocorrect(input): # Alternative with regexes! # return re.sub(r'(?i)\b(u|you+)\b', "your sister", input) def autocorrect(input_string): for search_target in ['u', 'you']: input_string = replace_target_alone(input_string, search_target) input_string = replace_startswith_target(input_string, search_target) input_string = replace_endswith_target(input_string, search_target) input_string = replace_target_is_substring(input_string, search_target) input_string = replace_multiple_uuu_case(input_string) return input_string.replace(TOKEN, REPLACE_STRING) def replace_multiple_uuu_case(input_string): regex_target = re.compile(r"^(.*)you(?:u+)(.*)$", re.IGNORECASE) input_string = re.sub(regex_target, r'\1%s\2' % TOKEN, input_string) return input_string def replace_target_is_substring(input_string, search_target): regex_target = re.compile(r'\b%s\b' % search_target, re.IGNORECASE) input_string = re.sub(regex_target, TOKEN, input_string) return input_string def replace_endswith_target(input_string, search_target): regex_target = re.compile(r'(.*)\s%s([!|?|\.|"|\']*)$' % search_target, re.IGNORECASE) input_string = re.sub(regex_target, r"\1 %s\2" % TOKEN, input_string) return input_string def replace_startswith_target(input_string, search_target): regex_target = re.compile(r'^%s\s(.*)' % search_target, re.IGNORECASE) input_string = re.sub(regex_target, r"%s \1" % TOKEN, input_string) return input_string def replace_target_alone(input_string, search_target): regex_target = re.compile(r'^%s$' % search_target, re.IGNORECASE) input_string = re.sub(regex_target, TOKEN, input_string) return input_string import unittest class TestStringMethods(unittest.TestCase): def test_first(self): self.assertEqual(autocorrect("u"), "your sister") self.assertEqual(autocorrect("u abc"), "your sister abc") self.assertEqual(autocorrect("U abc"), "your sister abc") self.assertEqual(autocorrect("abc u"), "abc your sister") self.assertEqual(autocorrect("abc U"), "abc your sister") self.assertEqual(autocorrect("U"), "your sister") self.assertEqual(autocorrect("abc u def"), "abc your sister def") self.assertEqual(autocorrect("abc U def"), "abc your sister def") self.assertEqual(autocorrect("you"), "your sister") self.assertEqual(autocorrect("you you"), "your sister your sister") self.assertEqual(autocorrect("you youuuu"), "your sister your sister") self.assertEqual(autocorrect("YOU"), "your sister") self.assertEqual(autocorrect("youuuuu"), "your sister") self.assertEqual(autocorrect("Youuuuu"), "your sister") self.assertEqual(autocorrect("Youuuuu abc"), "your sister abc") self.assertEqual(autocorrect("you tube"), "your sister tube") self.assertEqual(autocorrect("youtube"), "youtube") self.assertEqual(autocorrect("I miss you!"), "I miss your sister!") self.assertEqual(autocorrect("I miss you."), "I miss your sister.") self.assertEqual(autocorrect("I miss you!'"), "I miss your sister!'") self.assertEqual(autocorrect("I miss you!!!'"), "I miss your sister!!!'") self.assertEqual(autocorrect('I miss you!!!"'), 'I miss your sister!!!"') self.assertEqual(autocorrect('u u youville utube u youyouyou'), 'your sister your sister youville utube your sister youyouyou') self.assertEqual(autocorrect('u u youville utube your sister youyouyou uuu raiyou united your sister your sister your sister'), 'your sister your sister youville utube your sister youyouyou uuu raiyou united your sister your sister your sister')
# coding=utf-8 # Kata: Simulate the game 'SNAP!' # Features: # - Allow variable number of standard 52-card decks # - Allow for several 'matching' conditions: either match just suit, or just rank, or match on both. # ---- # Thanks to (awesome!) 'Fluent Python' book for inspiration for the Deck class. # see: Fluent Python by Luciano Ramalho (O’Reilly). # Copyright 2015 Luciano Ramalho, 978-1-491-94600-8. # and # https://github.com/fluentpython/example-code from collections import namedtuple, defaultdict from random import shuffle, choice # We're going to monkey patch a 'Card' namedtuple with these methods def suitequals(card1, card2): return card1.suit == card2.suit def rankequals(card1,card2): return card1.rank== card2.rank def cardequal(card1, card2): return suitequals(card1, card2) and rankequals(card1,card2) def cardrepr(card): return '{}, suit: {}'.format(card.rank, card.suit) Card = namedtuple('Card', ['deck', 'rank', 'suit']) Card.__eq__ = cardequal Card.__repr__ = cardrepr class Deck(object): ranks = [str(n) for n in range(2, 11)] + list('JQKA') suits = 'spades diamonds clubs hearts'.split() def __init__(self, numberofdecks=1): self._cards = [Card(deck, rank, suit) for suit in self.suits for rank in self.ranks for deck in xrange(0,numberofdecks) ] def __len__(self): return len(self._cards) def __getitem__(self, position): return self._cards[position] def __setitem__(self, position, card): self._cards[position] = card def main(): number_of_decks = initialize_game() players = ['p1','p2'] no_players = len(players) scores = defaultdict(int) deck = Deck(numberofdecks=number_of_decks) shuffle(deck) prev_indx = - no_players # use slicing to step thru N at a time for indx in range(0,len(deck))[::no_players]: print '.', if deck[indx] == deck[indx + 1]: print 'top cards: {} & {}'.format(deck[indx], deck[indx + 1]) round_has_winner(indx, players, prev_indx, scores) prev_indx = indx final_scores(players, scores) def initialize_game(): try: n = raw_input('number of card decks?') n = abs(int(n)) except ValueError: n = 3 print 'default: three packs' card_winning_condition_key = raw_input('How do you win a hand? \n\n' '0:Card exact match \n' '1:Card rank match \n' '2:Card suit match \n' ) cardequalscondition = { 0: cardequal, 1: rankequals, 2: suitequals } try: if int(card_winning_condition_key) not in cardequalscondition: raise ValueError Card.__eq__ = cardequalscondition[card_winning_condition_key] except ValueError: print 'default match: on card rank and suit' return n def round_has_winner(indx, players, prev_indx, scores): winning_player = choice(players) print ' "MATCH!" says {}'.format(winning_player) round_score = (indx - prev_indx) print ' {} gained {} pts'.format(winning_player, round_score) scores[winning_player] += round_score print ' {} now has {} pts'.format(winning_player, scores[winning_player]) def final_scores(players, scores): print "\n\n\n\n" print 'final scores' for player in players: print '{} finished with {} pts'.format(player, scores[player]) print if __name__ == "__main__": main() from unittest import TestCase class TestCardDeck(TestCase): def test_simplecards_deck_not_significant(self): beer_card = Card(0, '7', 'diamonds') self.assertEquals(beer_card, Card(1, rank='7', suit='diamonds')) def test_deck(self): deck = Deck() self.assertEquals(len(deck),52) self.assertEquals(deck[:3], [Card(deck='1',rank='2', suit='spades'), Card(deck='1',rank='3', suit='spades'), Card(deck='1',rank='4', suit='spades')]) self.assertEquals(deck[12::13],[Card(deck='1',rank='A', suit='spades'), Card(deck='1',rank='A', suit='diamonds'), Card(deck='1',rank='A', suit='clubs'), Card(deck='1',rank='A', suit='hearts')] ) self.assertEquals(Card('1','Q', 'hearts') in deck, True) def test_multipledecks(self): # allow for multiple 52 card decks self.assertEquals(len(Deck(2)),52 * 2) self.assertEquals(len(Deck(3)),52 * 3) def test_shuffle(self): # as we have added the setitem method, thus Deck iteratable now supports 'shuffle'! deck1 = Deck() deck2 = Deck() shuffle(deck1) self.assertNotEquals(deck1,deck2) class TestCompareCards(TestCase): def test_exact_equals(self): card1 = Card(deck='1',rank='2', suit='spades') card2 = Card(deck='1',rank='2', suit='spades') self.assertEquals(card1,card2) def test_suit_equals(self): Card.__eq__ = suitequals card1 = Card(deck='1',rank='3', suit='spades') card2 = Card(deck='1',rank='2', suit='spades') self.assertEquals(card1,card2) def test_suit_not_equals(self): Card.__eq__ = suitequals card1 = Card(deck='1',rank='3', suit='hearts') card2 = Card(deck='1',rank='2', suit='spades') self.assertNotEquals(card1,card2) def test_rank_equals(self): Card.__eq__ = rankequals card1 = Card(deck='1',suit='3', rank='spades') card2 = Card(deck='1',suit='2', rank='spades') self.assertEquals(card1,card2) def test_rank_not_equals(self): Card.__eq__ = rankequals card1 = Card(deck='1',suit='3', rank='hearts') card2 = Card(deck='1',suit='2', rank='spades') self.assertNotEquals(card1,card2)
""" Implement a function to check if a Mongo database ID is valid """ from datetime import datetime from collections import namedtuple Mongo_id = namedtuple('Mongo_id', ['timestamp', 'machine_id', 'process_id', 'counter']) class Mongo(object): MONGO_ID_LEN = 24 @classmethod def length_valid(cls, s): return len(str(s)) == Mongo.MONGO_ID_LEN @classmethod def hex_lowercase_valid(cls, s): for c in s: if not (c.islower() or c.isdigit()): return False return True @classmethod def is_valid(cls, s): try: if not (cls.length_valid(s) and cls.hex_lowercase_valid(s)): return False cls.hex_to_decimal(s) return True except (TypeError, ValueError): return False @classmethod def hex_to_decimal(cls, ts): ts = int(ts, 16) return ts @classmethod def get_id_elements(cls, s): return Mongo_id(s[:8], s[9:15], s[16:20], s[21:]) @classmethod def get_timestamp(cls, s): if not cls.is_valid(s): return False id_elements = Mongo.get_id_elements(s) ts = cls.hex_to_decimal(id_elements.timestamp) r = datetime.utcfromtimestamp(ts) return r import unittest class TestFirst(unittest.TestCase): def test_first(self): test = self test.assert_equals = self.assertEqual Test = self Test.assert_equals = self.assertEqual from datetime import datetime test.assert_equals(Mongo.is_valid(False), False) test.assert_equals(Mongo.is_valid([]), False) test.assert_equals(Mongo.is_valid(1234), False) test.assert_equals(Mongo.is_valid('123476sd'), False) test.assert_equals(Mongo.is_valid('507f1f77bcf86cd79943901'), False) test.assert_equals(Mongo.is_valid('507f1f77bcf86cd799439016'), True) test.assert_equals(Mongo.get_timestamp(False), False) test.assert_equals(Mongo.get_timestamp([]), False) test.assert_equals(Mongo.get_timestamp(1234), False) test.assert_equals(Mongo.get_timestamp('123476sd'), False) test.assert_equals(Mongo.get_timestamp('507f1f77bcf86cd79943901'), False) test.assert_equals(Mongo.get_timestamp('507f1f77bcf86cd799439016'), datetime(2012, 10, 17, 21, 13, 27)) # test.assert_equals(Mongo.get_timestamp('507f1f77bcf86cd799439011'),datetime(2012,10,Oct 17 2012 21:13:27 GMT-0700 (Pacific Daylight Time) test.assert_equals(Mongo.get_timestamp('507f1f77bcf86cz799439011'), False) # False test.assert_equals(Mongo.get_timestamp('507f1f77bcf86cd79943901'), False) # False test.assert_equals(Mongo.get_timestamp('111111111111111111111111'),datetime(1979, 1, 28, 0, 25, 53)) # Sun Jan 28 1979 00:25:53 GMT-0800 (Pacific Standard Time) test.assert_equals(Mongo.get_timestamp(111111111111111111111111), False) test.assert_equals(Mongo.get_timestamp('507f1f77bcf86cD799439011'), False) test.assert_equals(Mongo.get_timestamp('52fefe6cb0091856db00030e'), datetime(2014, 2, 15, 5, 43, 8))
from collections import defaultdict, Counter def runoff(voters): """ a function that calculates an election winner from a list of voter selections using an Instant Runoff Voting algorithm. https://en.wikipedia.org/wiki/Instant-runoff_voting Each voter selects several candidates in order of preference. The votes are tallied from the each voter's first choice. If the first-place candidate has more than half the total votes, they win. Otherwise, find the candidate who got the least votes and remove them from each person's voting list. In case of a tie for least, remove all of the tying candidates. In case of a complete tie between every candidate, return None Continue until somebody has more than half the votes; they are the winner. The function takes a list of voter ballots; each ballot will be a list of candidates in descending order of preference. Returns the symbol corresponding to the winning candidate. """ votes_cast_so_far=0 final_tally = Counter() removed_candidates = set() for this_round in range(len(voters[0])): this_round_votes = [voter[this_round] for voter in voters if voter[this_round] not in removed_candidates] if not this_round_votes: # all knocked out return None tally = Counter(this_round_votes) final_tally.update(tally) leader = final_tally.most_common(1) votes_cast_so_far += sum(final_tally.values()) if final_tally[leader] >= votes_cast_so_far / 2.0: return leader lowest_vote = min(tally.values()) knockout_candidates = [candidate for candidate in tally if tally[candidate] == lowest_vote] removed_candidates |= set(knockout_candidates) voters = [ ['c', 'a', 'b', 'd', 'e'], ['b', 'e', 'd', 'c', 'a'], ['b', 'e', 'c', 'a', 'd'], ['d', 'b', 'c', 'a', 'e'], ['c', 'b', 'd', 'a', 'e'] ] assert(runoff(voters) == "b")
""" Given 2 points find the slope of the line between them. """ UNDEFINED_SLOPE = "undefined" def calculate_slope(x1, x2, y1, y2): return (y2 - y1) / (x2 - x1) def find_slope(points): x1, y1, x2, y2 = points try: r = calculate_slope(x1, x2, y1, y2) return str(r) except ZeroDivisionError: return UNDEFINED_SLOPE import unittest class TestFirst(unittest.TestCase): def test_first(self): test = self Test = self test.assert_equals = Test.assertEqual Test.assert_equals = Test.assertEqual test.assert_equals(find_slope([19, 3, 20, 3]), "0") test.assert_equals(find_slope([-7, 2, -7, 4]), "undefined") test.assert_equals(find_slope([10, 50, 30, 150]), "5") test.assert_equals(find_slope([10, 20, 20, 80]), "6") test.assert_equals(find_slope([-10, 6, -10, 3]), "undefined")
#List to act as stack to hold the opening brackets stack = [] #string holding the set of parentheses string = '()[]{}' #validity check validState = False for char in string: if char in '[({': stack.append(char) elif char in '])}': if len(stack) == 0: validState = False break else: parentheses = stack.pop() if (char == ']' and parentheses == '[') or (char == ')' and parentheses == '(') or (char == '}' and parentheses == '{'): validState = True elif validState: validState = False break else: break if len(stack) != 0 and validState: validState = False print(validState)
# https://www.interviewcake.com/free-weekly-coding-interview-problem-newsletter import random def shuffle(l): for i in range(len(l)): swap_index = random.randint(0, len(l) - 1) if swap_index != i: tmp = l[i] l[i] = l[swap_index] l[swap_index] = tmp return l # [8, 3, 6, 4, 7, 5, 2, 6, 1, 2] for j in range(10): a = [random.randint(1, 10) for i in range(10)] print('list:', a, end='') print('shuffled:', shuffle(a))
def solution(arr: []): start = arr[-1] curr = start for _ in range(len(arr)): print('going to the loo') curr = arr[curr] number_in_loop = curr loop_len = 1 while arr[curr] != number_in_loop: curr = arr[curr] loop_len += 1 curr1 = start curr2 = start for _ in range(loop_len): # advabce curr1 loop_len steps print('curr1:', curr1) curr1 = arr[curr1] print('loop_length:', loop_len) while curr1 != curr2: curr2 = arr[curr2] curr1 = arr[curr1] return curr1 # 0 1 2 3 4 5 # print(solution([3, 0, 4, 0, 1, 2])) print(solution([2, 0, 1, 0, 4, 3]))
def add(a: str, b: str) -> str: x, y = int(a, 2), int(b, 2) print('a:', x, 'b:', y) while y: print('x:', bin(x), 'y:', bin(y)) answer = x ^ y carry = (x & y) << 1 x, y = answer, carry return bin(x)[2:] result = add('11111', '1111') print('answer:', result, '({0})'.format(int(result, 2)))
from math import floor, sqrt # def simple_sieve(n): # sieve = [True] * (n + 1) # sieve[0] = sieve[1] = False # # for i in range(2, int(sqrt(n)) + 1): # while i**2 <= n: # if sieve[i]: # if i is still potentially composite # for k in range(i ** 2, n + 1, i): # sieve[k] = False # # return sieve # # def get_smallest_factor_of(n: int): min_factor_of = [0] * (n+1) for i in range(2, int(sqrt(n)) + 1): if min_factor_of[i] == 0: for k in range(i**2, n+1, i): if min_factor_of[k] == 0: min_factor_of[k] = i return min_factor_of def find_factors(x, F): prime_factors_of_x = [] print(f'F: {F}') tmp = x while F[tmp]: print(f'F[{tmp}] = {F[tmp]}') factor = F[tmp] prime_factors_of_x.append(factor) tmp //= factor return prime_factors_of_x # print([i for i, v in enumerate(simple_sieve(16)) if v]) print(f'prime factors: {find_factors(24, get_smallest_factor_of(24))}') # # # # # # # # # # # # # # # find all prime numbers in [2: n] # def sieve(n): # sieve = [True] * (n + 1) # sieve[0] = sieve[1] = False # i = 2 # while i * i <= n: # if sieve[i]: # k = i * i # while k <= n: # sieve[k] = False # k += i # # i += 1 # # return sieve # # # # find the prime factors of n def factors_up_to_n(n): F = [0] * (n + 1) i = 2 while i ** 2 <= n: if F[i] == 0: k = i ** 2 while k <= n: if F[k] == 0: F[k] = i k += i i += 1 return F def factorization(x, F): prime_factors = set() while F[x] > 0: print(f'F[{x}] = {F[x]}') prime_factors.add(F[x]) x //= F[x] prime_factors.add(x) return prime_factors # print(list(enumerate(sieve(25)))) print(list(enumerate(factors_up_to_n(25)))) print(factorization(24, factors_up_to_n(24)))
from math import sqrt, floor # coins 1..n # initially all coins showing heads # n people turn over coins as follows: person i flips coins with numbers that are multiples of i # count the number of coins showing tails after all people have had a turn def coins(n): count = 0 # True - tails, False - heads coin = [False] * (n+1) # ignore 0-th element and use 1..n for simplicity for i in range(1, n+1): for k in range(i, n+1, i): coin[k] = not coin[k] count += int(coin[i]) print(f'coins: {coin[1:]}') return count def faster_solution(n): return floor(sqrt(n)) N = 152 print(f'count: {coins(N)}') print(f'method2: {faster_solution(N)}')
from typing import List # we'll present a single (particular) solution by a list of col positions with indices representing rows # e.g. [1, 3, 0, 2] - queen at row 0 is at column, queen at row 1 is at column 3, etc. def n_queens(n: int) -> List[List[int]]: # find all the ways we can put the n queens result: List[List[int]] = [] solve_n_queens(n=n, row=0, col_placement=[], result=result) return result def solve_n_queens( n: int, row: int, col_placement: List[int], result: List[List[int]] ): if row == n: result.append(col_placement.copy()) else: # for each possible column in current row (curr row is the next in col_placement indices) # try to find solutions for col in range(n): col_placement.append(col) if is_valid(col_placement): solve_n_queens(n, row + 1, col_placement, result) col_placement.pop() def is_valid(col_placements: List[int]) -> bool: curr_row = len(col_placements) - 1 curr_col = col_placements[curr_row] for prev_row in range(len(col_placements) - 1): # all previous rows prev_col = col_placements[prev_row] if (curr_col == prev_col # same column means columns are equal or curr_row - prev_row == abs(curr_col - prev_col)): # travel on x and travel on y is equal return False return True print(n_queens(4)) assert is_valid([0,0]) is False
def gcd(a, b): if b == 0: return a return gcd(b, a % b) # gdc(x, y) will contain the common prime factors of x and y # when we start dividing x and y to the greatest common divisor we will reach either 1 or a primer factor that is # not in gdc(x, y) def solution(A, B): count = 0 for a, b in zip(A, B): g = gcd(a, b) print('\n >> gdc({a}, {b}) ='.format(a=a, b=b), g, '\n\n') while True: d = gcd(a, g) print('a={a:<15} d = gcd({a}, {g}) = {d}'.format(a=a, g=g, d=d)) if 1 == d: # gcd(a, b) is 1, i.e. no common dividers except 1 break assert(a/d == a//d) a //= d print('--------------------') while True: d = gcd(b, g) print('b={b:<15} d = gcd({b}, {g}) = {d}'.format(b=b, g=g, d=d)) if 1 == d: break assert(b//d == b/d) b //= d count += 1 if a == 1 and b == 1 else 0 return count solution([630, 15, 12, 210], [420, 35, 36, 60])
import math from typing import List class Point: def __init__(self, x, y): self.x = x self.y = y def dist_to(self, p: 'Point'): d_pow_2 = (self.x - p.x)**2 + (self.y - p.x)**2 return math.sqrt(d_pow_2) def __add__(self, p: 'Point'): return Point(self.x + p.x, self.y + p.y) def __sub__(self, p: 'Point'): return Point(self.x - p.x, self.y - p.y) def __mul__(self, c: float): return Point(self.x * c, self.y * c) def __truediv__(self, c: float): return Point(self.x / c, self.y / c) def __lt__(self, p: 'Point'): return self.x < p.x or (self.x == p.x and self.y < self.y) def rotate_ccw_90(p: Point) -> Point: return Point(-p.y, p.x) def rotate_cw_90(p: Point) -> Point: return Point(p.y, -p.x) def circleCircleIntersection(a: Point, b: Point, r: float, R: float) -> List[Point]: d = a.dist_to(b) ret = [] return ret def read_number_pair(): return map(lambda s: int(s), input().split()) def main(): a, b = read_number_pair() kim_x, kim_y = read_number_pair() bob_x, bob_y = read_number_pair() jck_x, jck_y = read_number_pair() jan_x, jan_y = read_number_pair() if __name__ == "__main__": main()
# Copyright 2009-2017 Ram Rachum. # This program is distributed under the MIT license. import collections from python_toolbox import sequence_tools class SelectionSpace(sequence_tools.CuteSequenceMixin, collections.abc.Sequence): ''' Space of possible selections of any number of items from `sequence`. For example: >>> tuple(SelectionSpace(range(2))) (set(), {1}, {0}, {0, 1}) The selections (which are sets) can be for any number of items, from zero to the length of the sequence. Of course, this is a smart object that doesn't really create all these sets in advance, but rather on demand. So you can create a `SelectionSpace` like this: >>> selection_space = SelectionSpace(range(10**4)) And take a random selection from it: >>> selection_space.take_random() {0, 3, 4, ..., 9996, 9997} Even though the length of this space is around 10 ** 3010, which is much bigger than the number of particles in the universe. ''' def __init__(self, sequence): self.sequence = \ sequence_tools.ensure_iterable_is_immutable_sequence(sequence) self.sequence_length = len(self.sequence) self._sequence_set = set(self.sequence) self.length = 2 ** self.sequence_length def __repr__(self): return '<%s: %s>' % ( type(self).__name__, self.sequence ) def __getitem__(self, i): if isinstance(i, slice): raise NotImplementedError if (-self.length <= i <= -1): i += self.length if not (0 <= i < self.length): raise IndexError pattern = '{0:0%sb}' % self.sequence_length binary_i = pattern.format(i) assert len(binary_i) == self.sequence_length return set(item for (is_included, item) in zip(map(int, binary_i), self.sequence) if is_included) _reduced = property(lambda self: (type(self), self.sequence)) __hash__ = lambda self: hash(self._reduced) __bool__ = lambda self: bool(self.length) __eq__ = lambda self, other: (isinstance(other, SelectionSpace) and self._reduced == other._reduced) def index(self, selection): '''Find the index number of `selection` in this `SelectionSpace`.''' if not isinstance(selection, collections.abc.Iterable): raise ValueError selection_set = set(selection) if not selection_set <= self._sequence_set: raise ValueError return sum((2 ** i) for i, item in enumerate(reversed(self.sequence)) if item in selection_set)
# Copyright 2009-2017 Ram Rachum. # This program is distributed under the MIT license. from python_toolbox.misc_tools import is_legal_ascii_variable_name def test(): '''Test `is_legal_variable_name` on various legal and illegal inputs.''' legals = ['qwerqw', 'wer23434f3', 'VDF4vr', '_4523ga', 'AGF___43___4_', '_', '__', '___'] illegals = ['1dgfads', 'aga`fdg', '-haeth', '4gag5h+sdfh.', '.afdg', 'fdga"adfg', 'afdga afd'] for legal in legals: assert is_legal_ascii_variable_name(legal) for illegal in illegals: assert not is_legal_ascii_variable_name(illegal)
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: out=None while head: temp=head head=head.next temp.next=out out=temp return out
# 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 findMode(self, root: TreeNode) -> List[int]: cnts = collections.Counter() mv = 0 def helper(node): nonlocal mv if not node: return cnts[node.val] += 1 mv = max(mv, cnts[node.val]) helper(node.left) helper(node.right) helper(root) return [k for k,v in cnts.items() if v == mv]
import math def vol(rad): volume = (4/3)*(math.pi)*(rad**3) return volume print (vol(8)) def ran_check(num,low,high): if num >= low and num <= high: return f"{num} is in the range between {low} and {high}!" else: return f"{num} is not in the range between {low} and {high}." print(ran_check(5,2,4)) def up_low(s): u = 0 l = 0 for letter in s: if letter.isupper(): u += 1 elif letter.islower(): l += 1 print("Original String: ", s) print(f'No. of Upper case Characters : {u}') print(f'No. of Lower case Characters : {l}') up_low('Hello People') def unique_list(lst): my_list = [] for item in lst: if item not in my_list: my_list.append(item) return my_list print(unique_list([1,1,1,1,2,2,3,3,3,3,4,5])) def multiply(numbers): total = 1 for i in numbers: newsum == total * i return newsum print(multiply([1,2,3,-4]))
from turtle import Turtle, Screen import time def snake(): screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("Snake in Python") screen.listen() screen.tracer(0) game_is_on = True snake_bits = [] positions = [(0, 0), (-20, 0), (-40, 0)] for bit in range(0,3): new_snake_bit = Turtle(shape="square") new_snake_bit.penup() new_snake_bit.color("white") new_snake_bit.speed(1) new_snake_bit.goto(positions[bit]) snake_bits.append(new_snake_bit) while game_is_on: screen.update() time.sleep(.1) for bit_num in range(2, 0, -1): new_x = snake_bits[bit_num -1].xcor() new_y = snake_bits[bit_num - 1].ycor() snake_bits[bit_num].goto(new_x, new_y) screen.exitonclick()
# Write a program to read through the mbox-short.txt and # figure out the distribution by hour of the day for each # of the messages. You can pull the hour out from the 'From ' line # by finding the time and then splitting the string a second time using a colon. # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 # Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below. name = raw_input("Enter file:") fileh = open(name) counts = dict() l = list() hours = list() for line in fileh: line = line.rstrip() if not line.startswith("From "): continue pieces = line.split(" ") l.append(pieces [6]) for i in l: hours.append(i[:2]) for hour in hours: counts [hour] = counts.get(hour , 0) + 1 hours1 = list() for i,j in counts.items(): hours1.append((i,j)) hours1.sort() for i,j in hours1: print i,j
''' 3.1 Функции Задача 2 Напишите функцию modify_list(l), которая принимает на вход список целых чисел, удаляет из него все нечётные значения, а чётные нацело делит на два. Функция не должна ничего возвращать, требуется только изменение переданного списка, например: lst = [1, 2, 3, 4, 5, 6] print(modify_list(lst)) # None print(lst) # [1, 2, 3] modify_list(lst) print(lst) # [1] lst = [10, 5, 8, 3] modify_list(lst) print(lst) # [5, 4] Функция не должна осуществлять ввод/вывод информации. ''' def modify_list(l): for i in range(len(l) - 1, -1, -1): if l[i] % 2 == 0: l.insert(i + 1, int(l[i] / 2)) l.pop(i) lst = [1, 2, 3, 4, 5, 6] print(modify_list(lst)) # None print(lst) # [1, 2, 3] modify_list(lst) print(lst) # [1] lst = [10, 5, 8, 3] modify_list(lst) print(lst) # [5, 4] lst = [5] modify_list(lst) print(lst) # [] # Форум решений # def modify_list(l): # l[:] = [i//2 for i in l if not i % 2]
# built-in python library for interacting with .csv files import csv # natural language toolkit is a great python library for natural language processing import nltk # built-in python library for utility functions that introduce randomness import random # built-in python library for measuring time-related things import time def get_length_bucket(tweet_length): """ buckets the tweet length into either short / medium / long """ if tweet_length < 20: return "short" elif tweet_length < 70: return "medium" else: return "long" def contains_exclamation(tweet): if ("!" in tweet): return True else: return False def find_sentiment(tweet): sad_words = ["sad", "sorry", "oops", "disappoint", "oops"] if ("sad" in tweet): return "negative" if ("happy" in tweet): return "positive" else: return "unknown" def twitter_features(tweet): """ Returns a dictionary of the features of the tweet we want our model to be based on, e.g. tweet_length. So if the tweet was "Hey!", the output of this function would be { "length": "short" } If the tweet was "Hey this is a really great idea and I think that we should totally implement this technique", then the output would be { "length": "medium" } """ return { "length": get_length_bucket(len(tweet)), "exclamation": "!" in tweet, "sad" : "sad" in tweet, "happy" : "happy" in tweet, "wow" : ("wow" in tweet or "Wow" in tweet), "thanks" : ("thanks" in tweet or "Thanks" in tweet), "sorry" : ("sorry" in tweet or "Sorry" in tweet), "great" : ("great" in tweet or "Great" in tweet), "good" : ("good" in tweet or "Good" in tweet), "cool" : ("cool" in tweet or "Cool" in tweet), "oops" : ("oops" in tweet or "Oops" in tweet), "excite" : ("excite" in tweet or "Excite" in tweet), "loved" : ("loved" in tweet or "Loved" in tweet), "try" : ("try" in tweet or "Try" in tweet), #"disappoint" : ("disappoint" in tweet or "Disappoint" in tweet), #"check" : ("check" in tweet or "Check" in tweet), #"best" : ("best" in tweet or "Best" in tweet), } def get_feature_sets(): """ # Step 1: This reads in the rows from the csv file which look like this: 0, I'm so sad 1, Happy! where the first row is the label; 0=negative, 1=positive and the second row is the body of the tweet # Step 2: Turn the csv rows into feature dictionaries using `twitter_features` function above. The output of this function run on the example in Step 1 will look like this: [ ({"length": "short"}, 0), # this corresponds to 0, I'm so sad ({"length": "short"}, 1) # this corresponds to 1, Happy! ] You can think about this more abstractly as this: [ (feature_dictionary, label), # corresponding to row 0 ... # corresponding to row 1 ... n ] """ # open the file, which we've placed at /home/vagrant/repos/datasets/clean_twitter_data.csv # 'rb' means read-only mode and binary encoding f = open('/home/vagrant/repos/datasets/clean_twitter_data.csv', 'rb') # let's read in the rows from the csv file rows = [] for row in csv.reader(f): rows.append(row) # now let's generate the output that we specified in the comments above output_data = [] # let's just run it on 100,000 rows first, instead of all 1.5 million rows # when you experiment with the `twitter_features` function to improve accuracy # feel free to get rid of the row limit and just run it on the whole set for row in rows[:200000]: # Remember that row[0] is the label, either 0 or 1 # and row[1] is the tweet body # get the label label = row[0] # get the tweet body and compute the feature dictionary feature_dict = twitter_features(row[1]) # add the tuple of feature_dict, label to output_data data = (feature_dict, label) output_data.append(data) # close the file f.close() return output_data def get_training_and_validation_sets(feature_sets): """ This takes the output of `get_feature_sets`, randomly shuffles it to ensure we're taking an unbiased sample, and then splits the set of features into a training set and a validation set. """ # randomly shuffle the feature sets random.shuffle(feature_sets) # get the number of data points that we have count = len(feature_sets) # 20% of the set, also called "corpus", should be training, as a rule of thumb, but not gospel. # we'll slice this list 20% the way through slicing_point = int(.20 * count) # the training set will be the first segment training_set = feature_sets[:slicing_point] # the validation set will be the second segment validation_set = feature_sets[slicing_point:] return training_set, validation_set def run_classification(training_set, validation_set): # train the NaiveBayesClassifier on the training_set classifier = nltk.NaiveBayesClassifier.train(training_set) # let's see how accurate it was accuracy = nltk.classify.accuracy(classifier, validation_set) print "The accuracy was.... {}".format(accuracy) return classifier def predict(classifier, new_tweet): """ Given a trained classifier and a fresh data point (a tweet), this will predict its label, either 0 or 1. """ return classifier.classify(twitter_features(new_tweet)) # Now let's use the above functions to run our program start_time = time.time() print "Let's use Naive Bayes!" our_feature_sets = get_feature_sets() our_training_set, our_validation_set = get_training_and_validation_sets(our_feature_sets) print "Size of our data set: {}".format(len(our_feature_sets)) print "Now training the classifier and testing the accuracy..." classifier = run_classification(our_training_set, our_validation_set) classifier.show_most_informative_features() end_time = time.time() completion_time = end_time - start_time print "It took {} seconds to run the algorithm".format(completion_time)
import tkinter from tkinter import messagebox from tkinter import * import ImageTk, PIL, Image, os from random import sample import datetime import random Lotto = Tk() Lotto.title("Lotto") Lotto.iconbitmap("images/nlc-logo-1.ico") #LOGO of lotto plus img = Image.open("images/south-african-lotto.jpg") img = img.resize((500, 100), Image.ANTIALIAS) img = ImageTk.PhotoImage(img) panel = Label(Lotto, image=img) panel.image = img panel.place(x=0, y=0) #heading frame heading = Label(Lotto, text="Ithuba National Lottery") heading.configure(font=("Courier", 16, "bold")) heading.place(x=110, y=105) #rules l1 = Label(Lotto, text="Intructions", bg="yellow") l1.place(x=0, y=130) l2 = Label(Lotto, text="The rules are as follows:", bg="yellow") l2.place(x=0, y=150) l3 = Label(Lotto, text="1. Select only 6 numbers", bg="yellow") l3.place(x=0, y=170) l4 = Label(Lotto, text="2. Only choose numbers from 1 - 49", bg="yellow") l4.place(x=0, y=190) #Begin lbl1 = Label(Lotto, text="Please insert your numbers") lbl1.configure(font=("Courier", 10, "bold")) lbl1.place(x=140, y=220) e1 = Entry(Lotto) e1.configure(bd=2, width=4) e1.place(x=145, y=250) e2 = Entry(Lotto) e2.configure(bd=2, width=4) e2.place(x=180, y=250) e3 = Entry(Lotto) e3.configure(bd=2, width=4) e3.place(x=215, y=250) e4 = Entry(Lotto) e4.configure(bd=2, width=4) e4.place(x=250, y=250) e5 = Entry(Lotto) e5.configure(bd=2, width=4) e5.place(x=285, y=250) e6 = Entry(Lotto) e6.configure(bd=2, width=4) e6.place(x=320, y=250) def lotto_list(): num1 = int(e1.get()) num2 = int(e2.get()) num3 = int(e3.get()) num4 = int(e4.get()) num5 = int(e5.get()) num6 = int(e6.get()) list_1 = num1, num2, num3, num4, num5, num6 return list_1 #button game = Button(Lotto, text="Generate Numbers") game.configure() game.place(x=10, y=450) resetbtn = Button(Lotto, text="Reset") resetbtn.place(x=450, y=450) #heading for random numbers head = Label(Lotto, text="Lotto numbers are") head.configure(font=("Courier", 10, "bold")) head.place(x=175, y=300) #Display lables ran_labl1 = Label(Lotto, width=4, bg="yellow") ran_labl1.place(x=145, y=340) ran_labl2 = Label(Lotto, width=4, bg="yellow") ran_labl2.place(x=180, y=340) ran_labl3 = Label(Lotto, width=4, bg="yellow") ran_labl3.place(x=215, y=340) ran_labl4 = Label(Lotto, width=4, bg="yellow") ran_labl4.place(x=250, y=340) ran_labl5 = Label(Lotto, width=4, bg="yellow") ran_labl5.place(x=285, y=340) ran_labl6 = Label(Lotto, width=4, bg="yellow") ran_labl6.place(x=320, y=340) def go(): picks = sample(range(1, 49), 7) picks.sort() ran_labl6.configure(text=picks[5]) ran_labl1.configure(text=picks[0], bg="white") ran_labl2.configure(text=picks[1], bg="white") ran_labl3.configure(text=picks[2], bg="white") ran_labl4.configure(text=picks[3], bg="white") ran_labl5.configure(text=picks[4], bg="white") ran_labl6.configure(text=picks[5], bg="red") game.configure(state=DISABLED) resetbtn.configure(state=NORMAL) count = 0 for number in lotto_list(): if number in picks: count += 1 if count <= 1: message = "Attention" messagebox.showerror(message, str(count) + " " + "Numbers" + "\n payout = R0" ) elif count == 2: message = "Attention" messagebox.showerror(message, str(count) + " " + "Numbers" + "\n payout = R20" ) elif count == 3: message = "Attention" messagebox.showerror(message, str(count) + " " + "Numbers" + "\n payout = R100.50" ) elif count == 4: message = "Attention" messagebox.showerror(message, str(count) + " " + "Numbers" + "\n payout = R2,384.00" ) elif count == 5: message = "Attention" messagebox.showerror(message, str(count) + " " + "Numbers" + "\n payout = R8,584.00" ) elif count == 6: message = "Attention" messagebox.showerror(message, str(count) + " " + "Numbers" + "\n payout = R10, 000 000.00" ) return picks now = datetime.datetime.now() def append(): # appending text f = open("Login.txt", "a+") f.write("Lotto Numbers are: " + str(go()) + " " + "User Numbers: " + str(lotto_list()) + " " + "Numbers Guessed right: " + " " + "Time: " + str(now)) f.close() def reset(): ran_labl1.configure(text='', bg="Yellow") ran_labl2.configure(text='', bg="Yellow") ran_labl3.configure(text='', bg="Yellow") ran_labl4.configure(text='', bg="Yellow") ran_labl5.configure(text='', bg="Yellow") ran_labl6.configure(text='', bg="yellow") e1.delete(0, END) e2.delete(0, END) e3.delete(0, END) e4.delete(0, END) e5.delete(0, END) e6.delete(0, END) game.configure(state=NORMAL) resetbtn.configure(state=DISABLED) game.configure(command=append) resetbtn.configure(command = reset) Lotto.configure(bg="Yellow") Lotto.geometry('500x500') Lotto.mainloop()
from classes import Budget print("\n---iSaveMore Budget App---\n") def errorMsg(): print("Invalid input!") pincode = input("Please enter your 4-digit PIN code: ") if pincode == "0000": selection1 = input("\nPlease select an option: \n1.) Set Budget \n2.) Use Current Budget\n") def overwriteBudget (): file1 = open("food.txt", "w") file1.write(str(food.balance)) file1.close() file2 = open("entertainment.txt", "w") file2.write(str(entertainment.balance)) file2.close() file3 = open("clothing.txt", "w") file3.write(str(clothing.balance)) file3.close() def transferBalance (from_, to_): return from_.withdraw(to_.deposit(int(input("Transfer amount: ")))) def viewBalance(): print(f"\nFood {food}") print(f"Entertainment {entertainment}") print(f"Clothing {clothing}") if selection1 == "1": food = Budget(int(input("Set your food budget: "))) entertainment = Budget(int(input("Set your entertainment budget: "))) clothing = Budget(int(input("Set your clothing budget: "))) overwriteBudget() elif selection1 == "2": file1 = open("food.txt", "r") food_amount = file1.readline() food = Budget(int(food_amount)) file2 = open("entertainment.txt", "r") entertainment_amount = file2.readline() entertainment = Budget(int(entertainment_amount)) file3 = open("clothing.txt", "r") clothing_amount = file3.readline() clothing = Budget(int(clothing_amount)) else: errorMsg() selection2 = input("\nPlease select an option: \n1.) Deposit \n2.) Withdraw \n3.) Transfer\n4.) View Balance\n") if selection2 == "1": print("---DEPOSIT FUNDS---") food.deposit(int(input("Food deposit: "))) entertainment.deposit(int(input("Entertainment deposit: "))) clothing.deposit(int(input("Clothing deposit: "))) overwriteBudget () viewBalance() elif selection2 == "2": print("---WITHDRAW FUNDS---") food.withdraw(int(input("Food withdraw: "))) entertainment.withdraw(int(input("Entertainment withdraw: "))) clothing.withdraw(int(input("Clothing withdraw: "))) overwriteBudget() viewBalance() elif selection2 == "3": print("---TRANSFER FUNDS---") transfer = input("Please select an option: \n1.) Food -> Entertainment \n2.) Food -> Clothing \n3.) Entertainment -> Food \n4.) Entertainment -> Clothing\n5.) Clothing -> Food \n6.) Clothing -> Entertainment \n") if transfer == "1": transferBalance(food,entertainment) if transfer == "2": transferBalance(food,clothing) if transfer == "3": transferBalance(entertainment,food) if transfer == "4": transferBalance(entertainment,clothing) if transfer == "5": transferBalance(clothing,food) if transfer == "6": transferBalance(clothing,entertainment) else: errorMsg() overwriteBudget() viewBalance() elif selection2 == "4": print("---BALANCE---") viewBalance() else: errorMsg() else: errorMsg()
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("./MNIST_data", one_hot=True) img_length = 784 classes = 10 learning_rate = 1e-3 epochs = 30 batch_size = 100 x = tf.placeholder(tf.float32,[None,img_length]) y = tf.placeholder(tf.float32,[None,classes]) w = tf.Variable(tf.random_normal([img_length,classes])) b = tf.Variable(tf.random_normal([classes])) hypothesis = tf.nn.softmax(tf.matmul(x,w) + b) cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(hypothesis),axis=1)) train = tf.train.AdamOptimizer(learning_rate).minimize(cost) prediction = tf.argmax(hypothesis,1) cor = tf.equal(prediction,tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(cor,tf.float32)) with tf.Session() as s: s.run(tf.global_variables_initializer()) batches = int(mnist.train.num_examples / batch_size) for epoch in xrange(epochs): for batch in xrange(batches): train_x, train_y = mnist.train.next_batch(batch_size) s.run(train,feed_dict={x:train_x,y:train_y}) print 'Epoch',epoch,'finished with cost:',s.run(cost,feed_dict={x:train_x,y:train_y}) print '-' * 50 acc = s.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}) print 'training finished with accuracy:',acc
import getpass """ 输入用户名密码 """ name = input("name :") passwd = int(input("passwd :")) info ="""++++++++++++++++info {_name}+++++++++++++++++ name={_name} passwd={_passwd} """.format(_name=name, _passwd=passwd) print(type(name)) print()
#!/usr/bin/env python3 #james liu """ 字典的使用 01-字典是一个无序的,唯一的key=value 的类型对象 """ #创建字典 dictionary1={'name':"james.liu",'age':'23'} #查看字典 print(dictionary1["name"]) print(dictionary1) print(dictionary1.items()) print(dictionary1.get('name')) """ 区别 dictionary1.get(key) #key 不存在的时候return None dictionary1[key] #key 不存在的时候报错 """ print(dictionary1.get('salay')) #print(dictionary1['salay']) #增加 dict1=dictionary1.copy() dict1["salay"]=15000 print(dict1.items()) #改 print(dictionary1) dictionary1['name']="james" print(dictionary1) #删除 dictionary2=dictionary1.copy() #dictionary2=dictionary1会给clear清除 dictionary3=dictionary1.copy() print(dictionary2.items()) dictionary2.clear() #清空dictionary2 print(dictionary2.items()) del dictionary1['name'] #删除 print(dictionary1) print(dictionary3.items()) # dictionary3.pop("age") #删除 print(dictionary3.items()) ### 查看字典 print(dictionary1) print(len(dictionary1)) ###判断 info={'name':"james","age":'23',"salay":"15000"} print(info) if "james" in info["name"]: print("YES") else: print("NO james") ## 字符串形式 print("this is test".center(50,"#")) print(str(dict1)) ######## #dict2=dict1.copy() #浅复制一个字典 ##dict2.copy() ##浅复制一个字典 #dict2.get("name",delattr("james ok")) # #dict2.fromkeys() #dict2.has_key(key) #dict2.items() #dict2.keys() #dict2.setdefault() #dict2.values() #dict2.pop() #dict2.items() #dict2.clear() #删除字典里的所有元素
# latihan projek python daftarBuah = {'apel' : 5000, 'jeruk' : 8500, 'mangga' : 7800, 'duku' : 6500} while True: # tampilkan menu print('-'*50) print('Menu: ') print('1. Tambah data buah') print('2. Hapus data buah') print('3. Beli buah') print('4. Keluar') print('='*50) pilihan = int(input('Pilihan anda: ')) if pilihan == 1: tambahBuah = input('Masukkan nama buah : ') hargaBuah = input('Masukkan harga satuan : ') if tambahBuah not in daftarBuah: daftarBuah[tambahBuah] = hargaBuah for buah in daftarBuah: print(buah, '(Harga Rp ', daftarBuah[buah],')') elif tambahBuah in daftarBuah: print('Maaf buah sudah dalam daftar') elif pilihan == 2: namaBuah = input('Buah yang akan dihapus: ') if namaBuah in daftarBuah: del daftarBuah[namaBuah] print(namaBuah, 'Sudah dihapus dalam daftar') elif namaBuah not in daftarBuah: print(namaBuah, 'tidak ada dalam daftar') elif pilihan == 3: # nilai awal total pembelian totalHarga = 0 while True: fruit = input('Nama buah yang dibeli : ') kg = int(input('Berapa Kg : ')) harga = daftarBuah[fruit] # harga dijumlahkan totalHarga += kg * harga jwb = input('Beli buah yang lain (y/n): ') if jwb == 'n': break print('-'*50) print('Total harga : ', totalHarga) elif pilihan == 4: break else: print('Pilihan salah')
# latihan projek python 3,4 # input kode = input('Masukkan kode karyawan: ') nama = str(input('Masukkan nama karyawan: ')) gol = str(input('Masukkan golongan : ')) nikah= int(input('Masukkan status (1: menikah; 2: blm): ')) if nikah == 1: anak = int(input('Masukkan jumlah anak : ')) stat = 'Menikah' if nikah == 2: stat = 'Belum menikah' elif nikah != 1 or nikah != 2: print('Maaf terdapat kesalahan input') print('======================================') print('STRUKTUR RINCIAN GAJI KARYAWAN') print('--------------------------------------') print("Nama Karyawan : ", nama, "(Kode: ", kode,")") print("Golongan : ", gol) print("Status menikah : ", stat) if nikah == 1: print("Jumlah anak : ", anak) print('--------------------------------------') # proses while True: if gol == 'A': gajiPokok = 10000000 potongan = '2.5%' pot = 0.025 if gol == 'B': gajiPokok = 8500000 potongan = '2.0%' pot = 0.02 if gol == 'C': gajiPokok = 7000000 potongan = '1.5%' pot = 0.015 if gol == 'D': gajiPokok = 5000000 potongan = '1.0%' pot = 0.01 else: print('masukkan golongan A/B/C/D dengan huruf kapital') break if nikah == 1: subPair = gajiPokok*0.01 if anak > 0: subChild = gajiPokok*0.05*anak else: subChild = 0 else: subPair = 0 subChild = 0 cut = gajiPokok*pot gajiKotor = gajiPokok + subPair + subChild gajiBersih = gajiKotor - cut # output print('Gaji pokok : Rp', gajiPokok) if nikah == 1: print('Tunjangan istri/suami : Rp', subPair) print('Tunjangan anak : Rp', subChild) print('--------------------------------------') print('Gaji kotor : Rp', gajiKotor) print('Potongan (',potongan,') : Rp', cut) print('--------------------------------------') print('Gaji bersih : Rp', gajiBersih)
# latihan projek python 6 # input C = float(input('Masukkan suhu (celcius): ')) # proses # Reamur Re = 4/5*C # Romer Ro = (C * 21/40) + 7.5 # Kelvin K = C + 273 # Fahrenheit F = (C * 9/5) + 32 # Rankin Ra = (C * 9/5) + 492 # Newton N = C * 33/100 # Delisle D = (672 - (C * 9/5) + 32) * 5/6 # output print('Reamur : ', Re) print('Romer : ', Ro) print('Kelvin : ', K) print('Fahrenheit : ', F) print('Rankin : ', Ra) print('Newton : ', N) print('Delisle : ', D)
# Created on Wed Apr 1 15:43:37 2020 def main(): x = 0 x = 3 x = ((x * x) + 1) return x if __name__ == "__main__": import sys ret=main() sys.exit(ret)
class Error(Exception): """Base class for exceptions in TicTacToeBoard""" pass class InvalidKey(Error): pass class InvalidMove(Error): pass class InvalidValue(Error): pass class NotYourTurn(Error): pass class TicTacToeBoard: def __init__(self): self.state = {"A1": " ", "A2": " ", "A3": " ", "B1": " ", "B2": " ", "B3": " ", "C1": " ", "C2": " ", "C3": " "} self.current = "b" self.status = "Game in progress." def __getitem__(self, key): try: if(key[0] != "A" and key[0] != "B" and key[0] != "C" or key[1] != "1" and key[1] != "2" and key[1] != "3"): raise InvalidKey except InvalidKey: print(InvalidKey) else: return self.state[key] def __setitem__(self, key, value): try: if(key[0] != "A" and key[0] != "B" and key[0] != "C" or key[1] != "1" and key[1] != "2" and key[1] != "3"): raise InvalidKey elif value != "X" and value != "O": raise InvalidValue elif self.state[key] != " ": raise InvalidMove elif self.current != value: if self.current != "b": raise NotYourTurn except InvalidKey: raise except InvalidValue: raise except InvalidMove: raise except NotYourTurn: raise else: self.state[key] = value if self.current == "b": if value == "O": self.current = "X" else: self.current = "O" elif self.current == "X": self.current = "O" else: self.current = "X" def game_status(self): if self.status == "Game in progress.": self.check_end_game() return self.status def check_draw(self): flag = True for key, value in self.state: if self.state[key + value] == " ": flag = False return flag def check_end_game(self): cases = [["A1", "A2", "A3"], ["B1", "B2", "B3"], ["C1", "C2", "C3"], ["A1", "B1", "C1"], ["A2", "B2", "C2"], ["A3", "B3", "C3"], ["A3", "B2", "C1"], ["A1", "B2", "C3"]] for case in cases: if (self.state[case[0]] == self.state[case[1]] and self.state[case[1]] == self.state[case[2]] and self.state[case[0]] != " " and self.state[case[1]] != " " and self.state[case[2]] != " "): self.status = "{0} wins!".format(self.state[case[0]]) return self.status if self.check_draw(): self.status = "Draw!" return self.status def __str__(self): return ("\n" +\ " -------------\n" +\ "3 | {0} | {1} | {2} |\n" +\ " -------------\n" +\ "2 | {3} | {4} | {5} |\n" +\ " -------------\n" +\ "1 | {6} | {7} | {8} |\n" +\ " -------------\n" +\ " A B C \n").format(self.state["A3"], self.state["B3"], self.state["C3"], self.state["A2"], self.state["B2"], self.state["C2"], self.state["A1"], self.state["B1"], self.state["C1"])
# Reading an excel file using Python import xlrd import time load_start_time = time.time() # Give the location of the file loc = ("CityTemp.xlsx") print("Started") # To open Workbook wb = xlrd.open_workbook(loc) print("Opened") sheet = wb.sheet_by_index(0) print("Loaded") load_end_time = time.time() print("The dataset took ",load_end_time - load_start_time,"s to load") # For row 0 and column 0 # print(sheet.cell_value(0, 0)) # Print the number of column and row print("Total Columns: ",sheet.ncols) print("Total Rows: ",sheet.nrows) # Iterate through the rows and Columns columns = sheet.ncols rows = sheet.nrows # dataset = [] # for i in range(rows): # row_data = [] # for j in range(columns): # row_data.append(sheet.cell_value(i, j)) # # print(sheet.cell(i, j)) # Prints the cells in the format 'type' : 'value' # # print(sheet.cell_value(i, j)) # Prints the value in the particular cells # dataset.append(row_data) # # print(dataset) # Prints the data row by row | The sheet.row_value(x) returns the sheet as a list # for i in range(sheet.nrows): # print(sheet.row_values(i)) # # print(type(sheet.row_values(i))) # Prints the data row by Columns | The sheet.col_values(x) returns the sheet columns as a list # for i in range(sheet.ncols): # print(sheet.col_values(i))
from random import choice from random import random from vpython import * class Random_Walk(): def __init__(self, n=10000): self.n = n self.x = [0] self.y = [0] self.z = [0] def fill_walk(self): while len(self.x)<self.n: direction_x,direction_y,direction_z = choice([1,-1]),choice([1,-1]),choice([1,-1]) distance_x,distance_y,distance_z = choice([0,1]),choice([0,1]),choice([0,1]) step_x,step_y,step_z = direction_x*distance_x,direction_y*distance_y,direction_z*distance_z next_x,next_y,next_z = self.x[-1]+step_x, self.y[-1]+step_y,self.z[-1]+step_z self.x.append(next_x) self.y.append(next_y) self.z.append(next_z) def colors(self): r = random() if (r < 1.0/8.0): return [vector(1,0,0),vector(0,0,0)] elif (r < 2.0/8.0): return [vector(0,1,0),vector(0,0,0)] elif (r < 3.0/8.0): return [vector(-1,0,0),vector(0,0,0)] elif (r < 4.0/8.0): return [vector(0,-1,0),vector(0,0,0)] elif (r < 5.0/8.0): return [vector(0,0,1),vector(0,0,0)] elif (r < 6.0/8.0): return [vector(0,0,-1),vector(0,0,0)] elif (r < 7.0/8.0): return [vector(0,0,0),vector(1,0,-1)] else: return [vector(0,0,0),vector(-1,0,1)]
''' Consider our representation of permutations of students in a line from Exercise 1. (The teacher only swaps the positions of two students that are next to each other in line.) Let's consider a line of three students, Alice, Bob, and Carol (denoted A, B, and C). Using the Graph class created in the lecture, we can create a graph with the design chosen in Exercise 1: vertices represent permutations of the students in line; edges connect two permutations if one can be made into the other by swapping two adjacent students. ''' # Define Class Node (Vertices who represent premutations of students) class Node(object): def __init__(self, name): """Assumes name is a string""" self.name = name def getName(self): return self.name def __str__(self): return self.name # Define Class Edge connect two permutations if one can be made into other # by swapping two adjacent students class Edge(object): def __init__(self, src, dest): """Assumes src and dest are nodes""" self.src = src self.dest = dest def getSource(self): return self.src def getDestination(self): return self.dest def __str__(self): return self.src.getName() + '->' + self.dest.getName() # Weighted graph # weighting edges higher for moves that are harder to make. # EG in the student permutations: # 1. A large student who is difficult to move around in line # 1. weight heavily all edges that involve moving that student # 2. A sticky spot on the floor which is difficult to move onto and off of # 2. weight heavily all edges that involve moving thorugh that point class WeightedEdge(Edge): def __init__(self, src, dest, weight): self.weight = weight def getWeight(self): return self.weight def __str__(self): return self.src.getName() + '->' + self.dest.getName() +\ '(' + self.weight + ')' # Define Diagraph with an adjacency list implementation. # Associate with each node a list of destination nodes class Digraph(object): """edges is a dict mapping each node to a list of its children""" def __init__(self): # Initialize edges as an empty dictionary self.edges = {} def addNode(self, node): if node in self.edges: raise ValueError('Duplicate node') else: # insert node as key in the dictionary with empty values self.edges[node] = [] # Add an edge of Class Edge with attribute source and destination # Taken from Node names # g.addEdge(Edge(g.getNode('ACB'), g.getNode('ABC'))) def addEdge(self, edge): src = edge.getSource() dest = edge.getDestination() if not (src in self.edges and dest in self.edges): raise ValueError('Node not in graph') # other wise use source name (equal Node Name) as key and append # Node name of destination self.edges[src].append(dest) # return list of destinations - values in the dictionary given the node key # e.g. children of ACB is ABC def childrenOf(self, node): return self.edges[node] # return True or False if node name is in the source edges def hasNode(self, node): return node in self.edges # getNode return object of Class Node base on the Node attribute name def getNode(self, name): for n in self.edges: # if node name if n.getName() == name: return n raise NameError(name) # print string with source and destination def __str__(self): result = '' # src equal dictionary keys for src in self.edges: # dest equal dictionary values for dest in self.edges[src]: result = result + src.getName() + '->'\ + dest.getName() + '\n' return result[:-1] # omit final newline # Graph object inherits all attributes and function from Class Digraph class Graph(Digraph): def addEdge(self, edge): Digraph.addEdge(self, edge) # plus it calculates its reverse rev = Edge(edge.getDestination(), edge.getSource()) Digraph.addEdge(self, rev) # buildPermutationGraph def buildPermutationGraph(graphType): # Instantiate g = graphType() # add nodes nodes = [] nodes.append(Node("ABC")) # nodes[0] nodes.append(Node("ACB")) # nodes[1] nodes.append(Node("BAC")) # nodes[2] nodes.append(Node("BCA")) # nodes[3] nodes.append(Node("CAB")) # nodes[4] nodes.append(Node("CBA")) # nodes[5] for n in nodes: g.addNode(n) # list all possible permutations (undirectional edges) g.addEdge(Edge(g.getNode('ACB'), g.getNode('ABC'))) g.addEdge(Edge(g.getNode('BAC'), g.getNode('ABC'))) g.addEdge(Edge(g.getNode('BCA'), g.getNode('BAC'))) g.addEdge(Edge(g.getNode('CAB'), g.getNode('ACB'))) g.addEdge(Edge(g.getNode('CBA'), g.getNode('BCA'))) g.addEdge(Edge(g.getNode('CAB'), g.getNode('CBA'))) return g # Build a Graph print(buildPermutationGraph(Graph)) g = buildPermutationGraph(Graph) # Instantiate g = Graph() # add nodes nodes = [] nodes.append(Node("ABC")) # nodes[0] nodes.append(Node("ACB")) # nodes[1] nodes.append(Node("BAC")) # nodes[2] nodes.append(Node("BCA")) # nodes[3] nodes.append(Node("CAB")) # nodes[4] nodes.append(Node("CBA")) # nodes[5] for n in nodes: g.addNode(n) # CODE FOR SUBMITION # list all possible permutations (bidirectional edges) g.addEdge(Edge(g.getNode('ACB'), g.getNode('ABC'))) g.addEdge(Edge(g.getNode('BAC'), g.getNode('ABC'))) g.addEdge(Edge(g.getNode('BCA'), g.getNode('BAC'))) g.addEdge(Edge(g.getNode('CAB'), g.getNode('ACB'))) g.addEdge(Edge(g.getNode('CBA'), g.getNode('BCA'))) g.addEdge(Edge(g.getNode('CAB'), g.getNode('CBA'))) # Check answers edges = g.childrenOf(nodes[0]) for n in edges: n.getName() # AUTOMATION for i in range(len(nodes)): n = nodes[i].getName() for j in range(i+1, len(nodes)): # if following node names are equal to one of its children if nodes[j].getName() == n[1]+n[0]+n[2] or \ nodes[j].getName() == n[0]+n[2]+n[1]: # addEdge g.addEdge(Edge(nodes[i], nodes[j])) # Check answers for z in range(len(nodes)): edges = g.childrenOf(nodes[z]) for n in edges: 'node[' + str(z) + ']: ' + n.getName()
import sqliteDB 제품입력 제품목록 제품검색 제품수정 제품삭제 종료 while True: print(''' 1. 테이블 생성 2. 데어터 입력 3. 데이터 수정 4. 데이터 삭제 5. 데이터 리스트 6. 종료 ''') menu=input() if menu=='1': sqliteDB.create_table() elif menu=='2': sqliteDB.insert_data() elif menu=='3': sqliteDB.update_data() elif menu=='4': sqliteDB.delete_data() elif menu=='5': break else: print("메뉴를 잘못 선택하셨습니다")
def AgeCalculate(): from speak import speak from datetime import datetime try: print("please enter your birthday") speak("Year") bd_y=int(input("Year:")) speak("Month") bd_m=int(input("Month(1-12):")) speak("Date") bd_d=int(input("Date:")) calculate = datetime.now() - datetime(bd_y, bd_m, bd_d) year=calculate.days/365 month=(year-int(year))*12 print(f"You are now {int(year)} year's and {int(month)} months old: ") speak(f"You are now {int(year)} year's and {int(month)} months old: ") speak("Thank you") except: print("!!Something Went Wrong!!") speak("Something Went Wrong")
from musica import Musica # opción 1 """ A partir del archivo de texto musica.csv (creado con el módulo separado que se indicó), generar un vector de registros, de tal manera que vaya quedando ordenado por título, con todos los temas musicales. Mostrar el vector a razón de una línea por tema mostrando el género y el idioma en lugar de sus códigos). """ def busqueda_binaria_indice_por_titulo(vector, titulo): """ Encuentra mediante búsqueda binaria la posición de inserción de una nueva música en un arreglo, de acuerdo a su título. """ min = 0 max = len(vector) - 1 while min <= max: mid = min + (max - min) // 2 if vector[mid].titulo > titulo: max = mid - 1 else: min = mid + 1 return min def insertar_cancion(vector, musica): indice = busqueda_binaria_indice_por_titulo(vector, musica.titulo) vector[indice:indice] = [musica] def cargar_vector(vector): filename = "musica.csv" file = open(filename, "rt", encoding="utf8") data = file.readlines() file.close() for line in data[1:]: titulo, genero, idioma = line.strip().split("; ") musica = Musica(titulo, genero, idioma) insertar_cancion(vector, musica) def mostrar_vector(vector): print("{:^50} ({:^11} - {:^9})".format("Título", "Género", "Idioma")) for musica in vector: print(musica) def generar_y_mostrar_vector(vector): if len(vector) == 0: cargar_vector(vector) mostrar_vector(vector)
from typing import Union from binary_tree import BinaryTree from tree import Empty, Tree class BinarySearchTree(BinaryTree): """A binary search tree is a binary tree whose left child of each node contain an item less in value than itself, and the right child an item higher in value than itself. An in-order traversal of the binary search tree results to items arranged in ascending order. Instantiate a binary search tree object >>> tree = BinarySearchTree() Insert an item to the tree >>> tree.insert(5, 500) >>> tree.insert(4, 400) >>> tree.insert(6, 600) >>> tree.insert(10, 1000) Check if a tree is empty >>> tree.is_empty() False >>> BinarySearchTree().is_empty() True Get root position >>> root = tree.get_root() Get item corresponding to a certain position >>> root.get_data() (5, 500) Check if a position is owned by some tree >>> root.is_owned_by(tree) True >>> root.is_owned_by(BinarySearchTree()) False Get children of some position >>> children = tree.get_children(root) >>> [i.get_data() for i in children] [(4, 400), (6, 600)] Get left child of some position >>> left_child = tree.get_left_child(root) >>> left_child.get_data() (4, 400) Get right child of some position >>> right_child = tree.get_right_child(root) >>> right_child.get_data() (6, 600) Delete an item from the tree >>> position_to_delete = tree.get_right_child(right_child) >>> tree.delete(position_to_delete) Check if a position contains the root >>> tree.is_root(root) True >>> tree.is_root(left_child) False Check if a position contains a leaf node >>> tree.is_leaf(left_child) True >>> tree.is_leaf(root) False Get parent of some position >>> tree.get_parent(left_child).get_data() (5, 500) >>> tree.get_parent(root) is None True Get siblings of some position >>> siblings = tree.get_siblings(left_child) >>> [i.get_data() for i in siblings] [(6, 600)] Get height of some position >>> tree.get_height_of_node(left_child) 0 >>> tree.get_height_of_node(root) 1 Get height of tree >>> tree.get_height_of_tree() 1 Get depth of some position >>> tree.get_depth_of_node(left_child) 1 >>> tree.get_depth_of_node(root) 0 Get depth of tree >>> tree.get_depth_of_tree() 1 Get level of some position >>> tree.get_level_of_node(left_child) 2 >>> tree.get_level_of_node(root) 1 Get length of tree >>> len(tree) 3 >>> len(BinarySearchTree()) 0 Get string reresentation of tree >>> tree 5(4, 6) >>> str(tree) '5(4, 6)' Get tree iterable >>> tree_iterable = iter(tree) >>> next(tree_iterable).get_data() (5, 500) Get next item of tree iterator >>> next(tree).get_data() (4, 400) """ def __init__(self): super().__init__() def insert(self, key, value): super().insert(key, value) node = Tree._Node(key, value, children=[None, None]) if self.is_empty(): self._root = node else: current_node = self._root previous_node = current_node.parent while current_node is not None: previous_node = current_node left_child = current_node.children[0] right_child = current_node.children[1] if key == current_node.key: raise ValueError("Key already exists in tree") elif key > current_node.key: current_node = right_child else: current_node = left_child node.parent = previous_node if key > previous_node.key: previous_node.children[1] = node else: previous_node.children[0] = node def search(self, key) -> Union[BinaryTree._Position, None]: """Return the position of a key within the tree, or None if the value doesn't exist in the tree. Time complexity: O(n). :param key: the key to search :returns: the position of the item if it exists in the tree, else None """ if self.is_empty(): raise Empty("Tree is empty") current_node = self._root while current_node is not None: left_child = current_node.children[0] right_child = current_node.children[1] if key == current_node.key: break elif key > current_node.key: current_node = right_child else: current_node = left_child if current_node is None: return None else: return Tree._Position(self, current_node)
from abc import ABC, abstractmethod from typing import Any, Union class Empty(Exception): pass class PriorityQueue(ABC): """A priority queue is a queue ADT that supports insertion (enqueueing) of elements at one end and removal (dequeueing) of elements from the opposite end, with the extra attribute of priority of each element it contains, meaning an element can move closer to the front of the queue if the elements in front of it are of less precedence than itself. """ def __init__(self, minimum_priority_queue: bool): self._minimum_priority_queue = minimum_priority_queue @abstractmethod def __len__(self) -> int: """Get the total number of elements stored in the queue :returns: count of elements in queue """ pass @abstractmethod def is_empty(self) -> bool: """Check if queue contains no elements :return: True if queue is empty, else False """ pass @abstractmethod def enqueue(self, x: Any, priority: Union[int, float]) -> None: """Insert an element to the end of the queue :param x: element to add to the queue :param priority: value that determines precedence of x in relation to the rest of the elements in the queue """ pass @abstractmethod def dequeue(self) -> Any: """Remove first element of the queue and return it :return: first element of queue """ pass @abstractmethod def get_first(self) -> Any: """Return first element of the queue without removing it :return: first element of queue """ pass
from singly_linked_list import SinglyLinkedList class CircularlySinglyLinkedList(SinglyLinkedList): """A circularly singly linked list is a cyclic collection of nodes whose head and tail nodes are connected. Each node contains a reference to the node succeeding it. Instantiate a circularly singly linked list object >>> a_list = CircularlySinglyLinkedList() Append an item to the list >>> a_list.append(0) The L.append(x) method is an alias of L.insert_last(x) >>> a_list.insert_last(1) Insert an item at the head of the list >>> a_list.insert_first(2) Insert an item at a specific index >>> a_list.insert(1, 3) Insert an item at an index that's out of range raises IndexError >>> a_list.insert(100, 3) Traceback (most recent call last): ... IndexError: Index out of range Get first item of the list >>> a_list.get_first() 2 Get first item of an empty list raises Empty >>> CircularlySinglyLinkedList().get_first() Traceback (most recent call last): ... linked_list.Empty: List is empty Get last item of the list >>> a_list.get_last() 1 Get last item of an empty list raises Empty >>> CircularlySinglyLinkedList().get_last() Traceback (most recent call last): ... linked_list.Empty: List is empty Get item at a specific index >>> a_list[1] 3 Get item at an index that's out of range raises IndexError >>> a_list[100] Traceback (most recent call last): ... IndexError: Index out of range Get items at slice range of the list >>> a_list[1:3] [3, 0] Get items at a slice that's out of range raises IndexError >>> a_list[1:100] Traceback (most recent call last): ... IndexError: Index out of range Get items at a slice with a slice step of less than one raises a ValueError >>> a_list[1:3:0] Traceback (most recent call last): ... ValueError: Step needs to be greater than zero Get an iterable object of the list >>> iterable_object = iter(a_list) Get next item of the iterable object >>> next(iterable_object) 2 Get next item of the list iterator >>> next(a_list) 3 Get length of the the list >>> len(a_list) 4 Get a string representation of the list >>> str(a_list) '[2, 3, 0, 1]' >>> a_list [2, 3, 0, 1] Delete first item of the list >>> a_list.remove_first() Delete first item of an empty list raises Empty >>> CircularlySinglyLinkedList().remove_first() Traceback (most recent call last): ... linked_list.Empty: List is empty Delete last item of the list >>> a_list.remove_last() Delete last item of an empty list raises Empty >>> CircularlySinglyLinkedList().remove_last() Traceback (most recent call last): ... linked_list.Empty: List is empty Delete item at a specific index >>> del a_list[0] Delete item of at an index that's out of range raises IndexError >>> del a_list[100] Traceback (most recent call last): ... IndexError: Index out of range Replace item at a specific index >>> a_list[0] = 100 Replace item of at an index that's out of range raises IndexError >>> a_list[100] = 100 Traceback (most recent call last): ... IndexError: Index out of range Delete all items from the list >>> a_list.remove_all() >>> a_list [] """ def __init__(self): super().__init__() self._tail.next_node = self._head
from abc import ABC, abstractmethod from typing import Any, Union class Empty(Exception): pass class PositionalLinkedList(ABC): """A positional linked list is a linked list whose nodes are identifiable by their position within the list. Using the position of a node, operations such as insertion, retrieval, and deletion of elements can be performed on neighbouring nodes without the need to traverse the list from its head or tail to that specific position. A positional linked list can be implemented based on any linked list data structure, such as singly linked list, doubly linked list, etc. The operations that can be performed on the neighbouring nodes of a certain position, for a running time of O(1), are limited to the directions of traversal offered by the data structure used to implement the positional linked list. When using a linked list data structure where each node has a reference to the node succeeding it but not the one preceding it, only operations referencing the next neighbours of a specific position are achievable at constant running time. If the linked data structure contains nodes where each node contains references to both its previous and next nodes, operations referencing both the previous and next neighbours of a specific position are achievable at constant running time. """ class _Position: """A representation of the position of a node within a positional linked list""" def __init__(self, belongs_to, node): self.__variables = {"belongs_to": belongs_to} self.__node = node def is_owned_by(self, owner): """Check whether position belongs to the list, owner. Time complexity: O(1). :param owner: object to check whether it's the owner of this position :returns: True of the position is owned by the object passed, else False """ return owner is self.__variables["belongs_to"] def manipulate_variables(self, owner, method: str, *params): """Manipulate member variables of this position. Methods of the owner list are the only ones that can call this method. Time complexity: O(1). :param owner: list object that owns this position :param method: method name of list object that will manipulate the member variables of this position :param params: extra optional parameters to pass to the method :returns: the return value of the list method whose name is passed """ if not self.is_owned_by(owner): raise ValueError("Position doesn't belong to the passed owner") return getattr(owner, method)(self.__variables, *params) def manipulate_node(self, owner, method: str, *params): """Manipulate the node held by this position. Methods of the owner list are the only ones that can call this method. Time complexity: O(1). :param owner: list object that owns this position :param method: method name of list object that will manipulate the node contained in this position :param params: extra optional parameters to pass to the method :returns: the return value of the list method whose name is passed """ if not self.is_owned_by(owner): raise ValueError("Position doesn't belong to the passed owner") return getattr(owner, method)(self.__node, *params) def get_data(self): """Return the data stored by the node held by this position. Time complexity: O(1). :returns: data stored in node contained in this position """ return self.__node.data @staticmethod def _invalidate_position(variables): """Helper function to set the belongs_to key of a dictionary to None. Time complexity: O(1). :returns: the passed dictionary with belongs_to set to None """ variables["belongs_to"] = None return variables @staticmethod @abstractmethod def _validate_node(node): """Helper function to check if a node is a sentinel. Returns None if the node is a sentinel, otherwise returns the node itself. :param node: node to validate :returns: None if the node passed is a sentinel node, else returns the node that was passed """ pass @abstractmethod def is_empty(self) -> bool: """Return True if list is empty, else False :return: True if list is empty, else False """ pass @abstractmethod def insert_before(self, position: _Position, data: Any) -> _Position: """Add item before the defined position within the list :param position: reference position :param data: item to insert :returns: the position of the added item """ if not position.is_owned_by(self): raise ValueError("Position doesn't belong to this list") @abstractmethod def insert_after(self, position: _Position, data: Any) -> _Position: """Add item after the defined position within the list :param position: reference position :param data: item to insert :returns: the position of the added item """ if not position.is_owned_by(self): raise ValueError("Position doesn't belong to this list") @abstractmethod def get_before(self, position: _Position) -> Union[_Position, None]: """Return the position just before the passed position, None if the referenced before position doesn't exist :param position: reference position :returns: the position just before the passed position """ if not position.is_owned_by(self): raise ValueError("Position doesn't belong to this list") @abstractmethod def get_after(self, position: _Position) -> Union[_Position, None]: """Return the position just after the passed position, None if the referenced after position doesn't exist :param position: reference position :returns: the position just after the passed position """ if not position.is_owned_by(self): raise ValueError("Position doesn't belong to this list") @abstractmethod def remove_before(self, position: _Position) -> Any: """Delete item just before the passed position :param position: reference position :returns: the deleted item """ if not position.is_owned_by(self): raise ValueError("Position doesn't belong to this list") @abstractmethod def remove_after(self, position: _Position) -> Any: """Delete item just after the passed position :param position: reference position :returns: the deleted item """ if not position.is_owned_by(self): raise ValueError("Position doesn't belong to this list") @abstractmethod def remove(self, position: _Position) -> Any: """Delete item at a specific position :param position: position containing item to be deleted :returns: the deleted item """ if not position.is_owned_by(self): raise ValueError("Position doesn't belong to this list") @abstractmethod def insert_first(self, data: Any) -> _Position: """Add item at the head of the list :param data: item to insert :returns: the position of the added item """ pass @abstractmethod def insert_last(self, data: Any) -> _Position: """Add item at the tail of the list :param data: item to insert :returns: the position of the added item """ pass def append(self, data: Any) -> _Position: """Alias of insert_last :param data: item to insert :returns: the position of the added item """ return self.insert_last(data) @abstractmethod def get_first(self) -> Union[_Position, None]: """Return the position of the item at the head of the list, None if the list is empty :returns: the position of the item at the head of the list """ pass @abstractmethod def get_last(self) -> Union[_Position, None]: """Return the position of the item at the tail of the list, None if the list is empty :returns: the position of the item at the tail of the list """ pass def remove_first(self) -> Any: """Delete item at the head of the list :returns: the deleted item """ pass @abstractmethod def remove_last(self) -> Any: """Delete item at the tail of the list :returns: the deleted item """ pass def replace(self, position: _Position, data: Any) -> Any: """Replace item at a specific position. Time complexity: O(1). :param position: reference position :param data: item to replace the existing item at the reference position :returns: the item replaced from the reference position """ if not position.is_owned_by(self): raise ValueError("Position doesn't belong to this list") node = position.manipulate_node(self, "_validate_node", *[]) current_data = node.data node.data = data return current_data
class Conversion: # Code created by Luke Reddick # Please use inputs of one character, so C, F, K, c, f ,k # for celsius, fahrenheit, and Kelvin respectively convertFrom = str((input("What temperature are you converting from? (C/F/K) : " + "\n"))) convertTo = str((input("What temperature would you like to convert to? (C/F/K) : " + "\n"))) try: valueTemp = float((input(("What is the value of your temperature you would like to convert? : " + "\n")))) except: print("Your input was invalid.") def convert(w, s, x): if s == "F" or s == "f": if w == "C" or w == "c": result = (x - 32) * (5/9) print(str(x) + " degrees Fahrenheit is \n" + str(round(result, 3)) + " degrees Celsius \n") elif w == "K" or w == "k": result = (x - 32) * (5/9) + 273.15 print(str(x) + " degrees Fahrenheit is \n" + str(round(result, 3)) + " degrees Kelvin \n") else: print("Your input did not make sense to the program, try again.") elif s == "C" or s == "c": if w == "F" or w == "f": result = (x * (9/5)) + 32 print(str(x) + " degrees Celsius is \n" + str(round(result, 3)) + " degrees Fahrenheit \n") elif w == "K" or w == "k": result = x + 273.15 print(str(x) + " degrees Celsius is \n" + str(round(result, 3)) + " degrees Kelvin \n") else: print("Your input did not make sense to the program, try again.") elif s == "K" or s == "k": if w == "F" or w == "f": result = (x - 273.15 - 32) * (5/9) print(str(x) + " degrees Kelvin is \n" + str(round(result, 3)) + " degrees Fahrenheit \n") elif w == "C" or w == "c": result = x - 273.15 print(str(x) + " degrees Kelvin is \n" + str(round(result, 3)) + " degrees Celsius \n") else: print("Your input did not make sense to the program, try again. \n") else: print("Your input did not make sense to the program, try again. \n") try: convert(convertTo, convertFrom, valueTemp) except: print("Since input was invalid... \n Use single characters for the first two inputs and digits for the third. \n") input(" \nPress enter to exit.")
try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk root = tk.Tk() # use width x height + x_offset + y_offset (no spaces!) root.geometry("240x180+130+180") root.title('listbox with scrollbar') # create the listbox (height/width in char) listbox = tk.Listbox(root, width=20, height=6) listbox.grid(row=0, column=0) # create a vertical scrollbar to the right of the listbox yscroll = tk.Scrollbar(command=listbox.yview, orient=tk.VERTICAL) yscroll.grid(row=0, column=1, sticky='ns') listbox.configure(yscrollcommand=yscroll.set) # now load the listbox with data friend_list = [ 'Stew', 'Tom', 'Jen', 'Adam', 'Ethel', 'Barb', 'Tiny', 'Tim', 'Pete', 'Sue', 'Egon', 'Swen', 'Albert'] for item in friend_list: # insert each new item to the end of the listbox listbox.insert('end', item) # optionally scroll to the bottom of the listbox lines = len(friend_list) listbox.yview_scroll(lines, 'units') root.mainloop()
# ============================================================================= # import decimal # from decimal import Decimal # decimal.getcontext().prec = 6 # d = Decimal('1.234567') # print(d) # d += Decimal('1') # print(d) # ============================================================================= from fractions import Fraction a = Fraction(2,3) print(a) a = Fraction(0.5) print(a) a = 2j print(type(a)) import datetime d = datetime.date.today() print("{date:%A} {date.day} {date:%B} {date.year}".format(date=d))
#!/usr/bin/python3 from collections import deque class Stack(list): """Clase que representa una pila. Dado que hereda a partir de una lista, sólo se implementan los métodos push para agregar al principio de la pila y peek para ver el tope de la misma. Ejemplo de uso: pila = Stack() pila.push(1) pila.push(2) pila.push(3) print(pila) # [1, 2, 3] pila.pop() print(pila) # [1, 2]""" def __init__(self): """Constructor. Inicializa el constructor de la clase padre.""" super(Stack, self).__init__() def push(self, val): """Inserta un elemento en el tope de la pila.""" self.append(val) def peek(self): """Devuelve el valor del elemento en el tope de la pila sin eliminarlo de la pila.""" return self[-1] class Queue(deque): """Clase que representa una cola. Dado que hereda a partir de collections.deque, sólo se implementan los métodos enqueue y dequeue para facilitar su operación al insertar y eliminar elementos. Ejemplo de uso: cola = Queue() cola.enqueue(1) cola.enqueue(2) cola.enqueue(4) print(cola) # deque([1, 2, 4]) cola.dequeue() print(cola) # deque([2, 4])""" def __init__(self): """Constructor, inicializa el constructor de la clase padre.""" super(Queue, self).__init__() def enqueue(self, value): """Inserta un elemento al final de la cola.""" self.append(value) def dequeue(self): """Saca un elemento al principio de la cola.""" self.popleft() cuadro = [[4, 5, 16, 9], [14, 11, 2, 7], [1, 8, 13, 12], [15, 10, 3, 6]] def valida_renglon(cuadro, renglon, constante): """ Dados el cuadrado mágico, el índice del renglón a validar y el valor de la constante mágica, se realiza la suma de los elementos y se verifica si dicha suma es igual a la de la constante dada.""" suma_parcial = sum(valor for valor in cuadro[renglon]) return suma_parcial == constante def valida_columna(cuadro, columna, constante): """ Dados el cuadrado mágico, el índice de la columna a validar y el valor de constante mágica, se realiza la suma de los elementos para dicha columan y se verifica si dicha suma es igual a la de la constante dada.""" suma_parcial = sum(renglon[columna] for renglon in cuadro) return suma_parcial == constante def constante_magica(n): """Calcula la constante mágica para un número n. La formula para calcular la constante mágica es n * (n ** 2 + 1) / 2.""" return n * (n ** 2 + 1) / 2 def verticales(cuadro, constante): """ Verifica que para un cuadro mágico, para cada columna, la suma de los elementos del cuadro sea igual al valor de la constante mágica para el cuadro. """ for columna in range(len(cuadro)): if not valida_columna(cuadro, columna, constante): return False return True def horizontales(cuadro, constante): """ Verifica que para un cuadro mágica, para cada renglón, la suma de los elementos del cuadro sea igual al valor de la constante mágica para el cuadro. Este valor es pasado como parámetro. """ for renglon in range(len(cuadro)): if not valida_renglon(cuadro, renglon, constante): return False return True def diagonales(cuadro, constante): """ Verifica que para un cuadro mágico, para cada diagonal, la suma de los elementos del cuadro sea igual al valor de la constante mágica para el cuadro. Este valor es pasado como parámetro. """ n = len(cuadro) sum_1 = sum(cuadro[i][i] for i in range(n)) sum_2 = sum(cuadro[i][(n - 1) - i] for i in range(n)) return sum_1 == constante == sum_2 def valida_cuadro(cuadro, constante): """ Valida que un cuadro mágico sea valido para la constante dada. Para esto, valida que la suma de todas sus columnas, renglones y diagonales sea igual al valor de la constante mágica dada como parámetro. """ return constante_magica(len(cuadro)) == constante \ and diagonales(cuadro, constante) \ and horizontales(cuadro, constante) \ and verticales(cuadro, constante) ################################################### # Vamos a escribir código hasta que algo funcione # ################################################### cuadro = [[0 for i in range(3)] for i in range(3)] totalSqs = 3*3 posible = [True for i in range(totalSqs)] constante = constante_magica(3) numSquares = 0 def testRenglon(c, const): for i in range(len(c)): test = 0 unfilled = False for j in range(len(c[i])): test += c[i][j] if c[i][j] == 0: unfilled = True if not unfilled and test != const: return False return True def testCols(c, const): for j in range(len(c[0])): test = 0 unfilled = False for i in range(len(c)): test += c[i][j] if c[i][j] == 0: unfilled = True if not unfilled and test != const: return False return True def testDiagonales(c, const): test = 0 unfilled = False for i in range(len(c)): test += c[i][i] if c[i][i] == 0: unfilled = True if not unfilled and test != const: return False test = 0 unfilled = False for i in range(len(c)): test += c[i][len(c) - 1 - i] if (c[i][len(c) - 1- i]) == 0: unfilled = True if not unfilled and test != const: return False return True def pretty_print(c): for row in c: print('\t'.join(str(e) for e in row)) def llena(c, row, col, const): if not testRenglon(c, const) or not testCols(c, const) or not testDiagonales(c, const): return if row == len(c): print("\n\n") pretty_print(c) print("\n\n") global numSquares numSquares += 1 return for i in range(totalSqs): if posible[i]: c[row][col] = i + 1 posible[i] = False newCol = col + 1 newRow = row if newCol == len(c): newRow += 1 newCol = 0 llena(c, newRow, newCol, const) c[row][col] = 0 posible[i] = True def main(n): cuadro = [[0 for i in range(n)] for i in range(n)] constante = constante_magica(n) llena(cuadro, 0, 0, constante) print("Hay {} soluciones".format(numSquares)) main(3) ######################################################################## # Probamos la salida, como por el momento sólo las imprimo en lugar de # # meterlas en alguna lista, tengo que probar a mano que todas las # # soluciones son correctas :c # ######################################################################## l = [[[2, 7, 6], [9, 5, 1], [4, 3, 8]], [[2, 9, 4], [7, 5, 3], [6, 1, 8]], [[4, 3, 8], [9, 5, 1], [2, 7, 6]], [[4, 9, 2], [3, 5, 7], [8, 1, 6]], [[6, 1, 8], [7, 5, 3], [2, 9, 4]], [[6, 7, 2], [1, 5, 9], [8, 3, 4]], [[8, 1, 6], [3, 5, 7], [4, 9, 2]], [[8, 3, 4], [1, 5, 9], [6, 7, 2]]] for x in l: print("Funcionó: {}".format(valida_cuadro(x, 15)))
print (6+12-3) print (2*3.0) print (-4) print (10/3) print (10.0/3.0) print ((2+3)*4) print (2+3*4) print (2**3+1) print (2.1**2.0) print (2.2*3.0) a = 3 print (a+2.0) a = a+1.0 print (a) # a = 3 # print (b) print (3 > 4) print (4.0 > 3.999) print (4 > 4) print (4 > +4) print (2+2 == 4) print (True or False) print (False or False) print (not False) print (3.0-1.0 != 5.0-3.0) print (3 > 4 or (2 < 3 and 9 > 10)) print (4 > 5 or 3 < 4 and 9 > 8) print (not(4 > 3 and 100 > 6)) a = 3 a == 5.0 print (a) b = 10 c = b > 9 print (c) print (3+5.0) print (5/2) print (5/2 == 5/2.0) print (5/2.0) print (round(2.6)) print (int(2.6)) print (2.0+5.0) print (5*2 == 5.0*2.0)
# NumberList = [] # Num1 = int(input("Enter the first number: ")) # NumberList.append(Num1) # while True: # Num2 = int(input("Enter the next number, or Zero to exit: ")) # if Num2 == 0: # break # NumberList.append(Num2) # NumberList.reverse() # print(NumberList) # MessageList = [] # i = 1 # while i <= 5: # Message = input("Please enter message " + str(i) + ": ") # MessageList.append(Message) # i = i + 1 # SeeMessage = int(input("Which message would you like to see?: ")) # print(MessageList[SeeMessage - 1]) # NumList = [] # FirstNum = int(input("Please enter the first number: ")) # NumList.append(FirstNum) # FinalTotal, i = 1, 0 # while i >= 0: # NextNum = int(input("Enter the next number, or 0 if finished: ")) # if NextNum == 0: # break # elif i == 0: # FinalTotal = FinalTotal * FirstNum # NumList.append(NextNum) # FinalTotal = FinalTotal * NextNum # print(NumList, "Multiplied together is: ", FinalTotal) # FriendList = [] # FirstFriend = input("Please enter the name of a friend: ") # FriendList.append(FirstFriend) # while True: # NextFriend = input("Please enter another name, or press enter if finished: ") # if not NextFriend: # break # FriendList.append(NextFriend) # for friend in FriendList: # print(friend) # def Courses(): # while True: # NextCourse = input("Please enter another name, or press enter if finished: ") # if not NextCourse: # break # CourseList.append(NextCourse) # def Grading(): # for course in CourseList: # CourseGrade = int(input("Enter your grade for " + course + ": ")) # GradeList.append(CourseGrade) # CourseList = [] # GradeList = [] # FirstCourse = input("Please enter the name of the first course: ") # CourseList.append(FirstCourse) # Courses() # Grading() # grades = 0 # for course in CourseList: # print(course, "Grade: ", GradeList[grades]) # grades = grades + 1 # FinalGrade = sum(GradeList)/len(GradeList) # print("Your final GPA is: ", round(FinalGrade, 1)) def InCommon(): ListC = (set(ListA).intersection(ListB)) if "" not in ListC: print("Common numbers are:", ListC) else: print("There are no items in common") ListA = [] ListB = [] while True: ItemA = int(input("Enter a number for list A: ")) if ItemA == 0: break else: ListA.append(ItemA) while True: ItemB = int(input("Enter a number for list B: ")) if ItemB == 0: break else: ListB.append(ItemB) InCommon()
import requests from bs4 import BeautifulSoup import pandas as pd from tabulate import tabulate number_of_articles = 5 # Number of articles that we want to retrieve headline_list = [] intro_list = [] full_list = [] # Empty list that is going to be used for future iteration of the project*** # Creating a loop in order to gain the 5 most popular # headlines on the BBC news business page for n in range(0, number_of_articles): url = "https://www.bbc.co.uk/news/business" # The URL of the website that the data is being retrieved from page = requests.get(url) # Get access to the BBC business news page soup = BeautifulSoup(page.content, 'html.parser') # Get the HTML content of the page headlines = soup.find_all('a', class_="gs-c-promo-heading") # Find all headline titles through HTML classes intro = soup.find_all('p', class_="gs-c-promo-summary") # Find all headline intros through HTML classes title = headlines[n].get_text() # Assigning the headline text to the 'title' variable headline_list.append(title) paragraph = intro[n].get_text() intro_list.append(paragraph) # Adding the text of the headline to the list df = pd.DataFrame( # Creating a dataframe in order to display the collected data from the site. {'Article Title': headline_list, # Creating two columns in the dataframe one displaying all the Article Titles 'Article Info': intro_list} # the other displaying all the intros to the article. ) pd.set_option('display.max_colwidth', None) # No max length to the columns, allowing for long intros if need be pd.set_option('display.colheader_justify', "left") # Set the column headers to the left of the dataframe # prints the titles and intros to the top 5 articles using the tabulate library, keeping it neat in a fancy grid print(tabulate(df, showindex=False, headers=df.columns, tablefmt='fancy_grid'))
''' Pavlo Semchyshyn ''' from collections import defaultdict def read_file(path): """ Reads file and returns a generator, which yields year, film and location as a tuple """ with open(path, "r", encoding="latin1") as file_to_read: line = file_to_read.readline() while not line.startswith("="): line = file_to_read.readline() while not line.startswith("\""): line = file_to_read.readline() for line in file_to_read: if "}" in line: continue line = line.strip() first_point = line.find("(") second_point = line.find(")") year = line[first_point + 1: second_point] if not year.isdigit(): continue film = line[: first_point].strip().strip("\"") if ")" in line[second_point + 1:]: third_point = line.find(")", second_point + 1) location = line[third_point + 1:].strip() else: location = line[second_point + 1:].strip() if len(location) < 2: continue yield year, film, location def films_by_year(lines): """ Returns a dictionary with year as a key, and list of the name of film and location as value """ dict_of_films = defaultdict(list) for year, film, location in lines: dict_of_films[year].append((film, location)) return dict_of_films def all_films_in_year(year, dict_of_films): """ Returns a dictionary of films, shot in one year, as name of film as key and location as value """ film_location = {} if str(year) in dict_of_films: for film, location in dict_of_films[str(year)]: film_location[film] = location return film_location CONTENTS = read_file("locations.list") DICT_OF_FILMS = films_by_year(CONTENTS) if __name__ == "__main__": FILM_IN_YEAR = all_films_in_year(2010, DICT_OF_FILMS)
# -*- coding: cp1252 -*- ## Importar librerias Tkinter y Pickle from Tkinter import* import pickle ##Funcion que recibe como argumento una ventana y la muestra def mostrar(ventana): ventana.deiconify() ##Funcion que recibe como argumento una ventana y la oculta def ocultar(ventana): ventana.withdraw() ##Funcion que recibe como argumento un StringVar y limpia lo que contenga def limpiar(entry): entry.set("") ##Variables Globales utilizadas en distintas secciones listaDoctores=[] listaPacientes=[] listaCitas=[] listaObjetosInfoDoctor=[] listaObjetosInfoPaciente=[] listaObjetosInfoCita=[] listaTemporal=[] listaObjetosInfoTratamientos=[] CitaTemporal="" DoctorTemporal="" indiceDoctorTemporal="" PacienteTemporal="" indicePacienteTemporal="" #Carga el archivo con la informacion de las citas mediante la libreria Pickle def cargarArchivoCitas(): global listaCitas archivo=file("listaCitas.txt") listaCitas=pickle.load(archivo) #Carga el archivo con la informacion de los doctores mediante la libreria Pickle def cargarArchivoDoctores(): global listaDoctores archivo=file("listaDoctores.txt") listaDoctores=pickle.load(archivo) #Carga el archivo con la informacion de los pacientes mediante la libreria Pickle def cargarArchivoPacientes(): global listaPacientes archivo=file("listaPacientes.txt") listaPacientes=pickle.load(archivo) ##Termina la aplicacion y guarda en archivos todos los cambios hechos a las listas def salir(): global listaDoctores global listaPacientes global listaCitas archivo=file("listaDoctores.txt",'w') archivo2=file("listaPacientes.txt",'w') archivo3=file("listaCitas.txt",'w') pickle.dump(listaCitas,archivo3) pickle.dump(listaPacientes,archivo2) pickle.dump(listaDoctores,archivo) v0.destroy() ##Se define la clase Doctor class Doctor(): def __init__(self,identificacion,nombre,fechaNacimiento,direccion,especialidad): self.identificacion=identificacion self.nombre=nombre self.listaTelefonos=[] self.listaCorreos=[] self.fechaNacimiento=fechaNacimiento self.direccion=direccion self.especialidad=especialidad def obtenerInfo(self): return self.identificacion,self.nombre,self.listaTelefonos,self.listaCorreos,self.fechaNacimiento,self.direccion,self.especialidad def obtenerNombre(self): return self.nombre ##Se define la clase tratamiento class Tratamiento(): def __init__(self,fecha,doctor,descripcion): self.fecha=fecha self.doctor=doctor self.descripcion=descripcion self.estado="Activo" def obtenerInfo(self): return self.fecha,self.doctor,self.descripcion,self.estado #Se define la clase Paciente class Paciente(): def __init__(self,identificacion,nombre,fechaNacimiento,direccion,ocupacion): self.identificacion=identificacion self.nombre=nombre self.listaTelefonos=[] self.listaCorreos=[] self.listaTratamientos=[] self.fechaNacimiento=fechaNacimiento self.direccion=direccion self.ocupacion=ocupacion def obtenerInfo(self): return self.identificacion,self.nombre,self.listaTelefonos,self.listaCorreos,self.fechaNacimiento,self.direccion,self.ocupacion,self.listaTratamientos #Se define la clase cita class Cita(): def __init__(self,fecha,hora,paciente,doctor): self.fecha=fecha self.hora=hora self.paciente=paciente self.doctor=doctor self.estado="Pendiente" def obtenerInfo(self): return self.fecha,self.hora,self.paciente,self.doctor,self.estado #Toma una lista con objetos y elimina todos sus objetos de la respectiva ventana def olvidarGrids(lista): for objeto in lista: objeto.pack_forget() lista=[] def olvidarObjetos(lista): for objeto in lista: objeto.grid_forget() lista=[] ##Limpia Entrys def limpiarEntry(entry): entry.set("") def limpiarEntryDoctores(): global vsNombreDoctor global vsIdentificacionDoctor global vsCorreoDoctor1 global vsCorreoDoctor2 global vsCorreoDoctor3 global vsTelefonoDoctor1 global vsTelefonoDoctor2 global vsTelefonoDoctor3 global vsfnacimientoDoctor global vsDireccionDoctor global vsEspecialidadDoctor vsNombreDoctor.set("") vsIdentificacionDoctor.set("") vsCorreoDoctor1.set("") vsCorreoDoctor2.set("") vsCorreoDoctor3.set("") vsTelefonoDoctor1.set("") vsTelefonoDoctor2.set("") vsTelefonoDoctor3.set("") vsfnacimientoDoctor.set("") vsDireccionDoctor.set("") vsEspecialidadDoctor.set("") def limpiarEntryPacientes(): global vsNombrePaciente global vsIdentificacionPaciente global vsCorreoPaciente1 global vsCorreoPaciente2 global vsCorreoPaciente3 global vsTelefonoPaciente1 global vsTelefonoPaciente2 global vsTelefonoPaciente3 global vsfnacimientoPaciente global vsDireccionPaciente global vsOcupacionPaciente vsNombrePaciente.set("") vsIdentificacionPaciente.set("") vsCorreoPaciente1.set("") vsCorreoPaciente2.set("") vsCorreoPaciente3.set("") vsTelefonoPaciente1.set("") vsTelefonoPaciente2.set("") vsTelefonoPaciente3.set("") vsfnacimientoPaciente.set("") vsDireccionPaciente.set("") vsOcupacionPaciente.set("") def limpiarEntryCitas(): global vsFechaCita global vsHoraCita vsFechaCita.set("") vsHoraCita.set("") ##Muestra todas las citas pendientes def mostrarCitasPendientes(): global listaCitas global listaObjetosInfoCita for cita in listaCitas: if cita.estado=="Pendiente": obj1=Label(vCitas,text="Doctor: "+cita.doctor.nombre,font=('Cambria',14),bg="lightblue") obj1.grid() obj2=Label(vCitas,text="Paciente: "+cita.paciente.nombre,font=('Cambria',14),bg="lightblue") obj2.grid() obj3=Label(vCitas,text="Fecha: "+cita.fecha,font=('Cambria',14),bg="lightblue") obj3.grid() obj4=Label(vCitas,text="Hora: "+cita.hora,font=('Cambria',14),bg="lightblue") obj4.grid() obj5=Label(vCitas,text="Estado: Pendiente",font=('Cambria',14),bg="lightblue") obj5.grid() obj6=Button(vCitas,text="Modificar Fecha u Hora",command=lambda:mostrarDatosCitaModificar(cita) or ocultar(vCitas) or seleccionarCita(cita)) obj6.grid() obj7=Button(vCitas,text="Eliminar Cita",command=lambda:seleccionarCita(cita) or eliminarCita(cita) or ocultar(vCitas)) obj7.grid() obj8=Button(vCitas,text="Cambiar Estado",command=lambda:seleccionarPaciente(cita.paciente.nombre,0) or seleccionarCita(cita) or mostrar(vConfirmarCambiarEstadoCita) or ocultar(vCitas)) obj8.grid() listaObjetosInfoCita.append(obj1) listaObjetosInfoCita.append(obj2) listaObjetosInfoCita.append(obj3) listaObjetosInfoCita.append(obj4) listaObjetosInfoCita.append(obj5) listaObjetosInfoCita.append(obj6) listaObjetosInfoCita.append(obj7) listaObjetosInfoCita.append(obj8) mostrar(vCitas) #Muestra todas las citas en las q el paciente ya ha asistido def mostrarCitasRealizadas(): global listaCitas global listaObjetosInfoCita for cita in listaCitas: if cita.estado=="Realizada": obj1=Label(vCitas,text="Doctor: "+cita.doctor.nombre,font=('Cambria',14),bg="lightblue") obj1.grid() obj2=Label(vCitas,text="Paciente: "+cita.paciente.nombre,font=('Cambria',14),bg="lightblue") obj2.grid() obj3=Label(vCitas,text="Fecha: "+cita.fecha,font=('Cambria',14),bg="lightblue") obj3.grid() obj4=Label(vCitas,text="Hora: "+cita.hora,font=('Cambria',14),bg="lightblue") obj4.grid() obj5=Label(vCitas,text="Estado: Realizada",font=('Cambria',14),bg="lightblue") obj5.grid() obj6=Button(vCitas,text="Eliminar Cita",command=lambda:seleccionarCita(cita) or eliminarCita(cita) or ocultar(vCitas)) obj6.grid() listaObjetosInfoCita.append(obj1) listaObjetosInfoCita.append(obj2) listaObjetosInfoCita.append(obj3) listaObjetosInfoCita.append(obj4) listaObjetosInfoCita.append(obj5) listaObjetosInfoCita.append(obj6) mostrar(vCitas) #Muestra todas las citas de un determinado dia def mostrarCitasPorDia(Dia): global listaCitas global listaObjetosInfoCita for cita in listaCitas: if cita.fecha==Dia: obj1=Label(vCitas,text="Doctor: "+cita.doctor.nombre,font=('Cambria',14),bg="lightblue") obj1.grid() obj2=Label(vCitas,text="Paciente: "+cita.paciente.nombre,font=('Cambria',14),bg="lightblue") obj2.grid() obj3=Label(vCitas,text="Fecha: "+cita.fecha,font=('Cambria',14),bg="lightblue") obj3.grid() obj4=Label(vCitas,text="Hora: "+cita.hora,font=('Cambria',14),bg="lightblue") obj4.grid() obj5=Label(vCitas,text="Estado: "+cita.estado,font=('Cambria',14),bg="lightblue") obj5.grid() obj6=Button(vCitas,text="Eliminar Cita",command=lambda:seleccionarCita(cita) or eliminarCita(cita) or ocultar(vCitas)) obj6.grid() if cita.estado=="Pendiente": obj7=Button(vCitas,text="Modificar Fecha u Hora",command=lambda:mostrarDatosCitaModificar(cita) or ocultar(vCitas) or seleccionarCita(cita)) obj7.grid() obj8=Button(vCitas,text="Cambiar Estado",command=lambda:seleccionarPaciente(cita.paciente.nombre,0) or seleccionarCita(cita) or mostrar(vConfirmarCambiarEstadoCita) or ocultar(vCitas)) obj8.grid() listaObjetosInfoCita.append(obj7) listaObjetosInfoCita.append(obj8) listaObjetosInfoCita.append(obj1) listaObjetosInfoCita.append(obj2) listaObjetosInfoCita.append(obj3) listaObjetosInfoCita.append(obj4) listaObjetosInfoCita.append(obj5) listaObjetosInfoCita.append(obj6) mostrar(vCitas) #Muestra Todas las citas de un determinado Doctor def mostrarCitasDoctor(Doctor): global listaCitas global listaObjetosInfoCita for cita in listaCitas: if cita.doctor.nombre==Doctor and cita.estado=="Pendiente": obj1=Label(vCitas,text="Doctor: "+cita.doctor.nombre,font=('Cambria',14),bg="lightblue") obj1.grid() obj2=Label(vCitas,text="Paciente: "+cita.paciente.nombre,font=('Cambria',14),bg="lightblue") obj2.grid() obj3=Label(vCitas,text="Fecha: "+cita.fecha,font=('Cambria',14),bg="lightblue") obj3.grid() obj4=Label(vCitas,text="Hora: "+cita.hora,font=('Cambria',14),bg="lightblue") obj4.grid() obj5=Label(vCitas,text="Estado: Pendiente",font=('Cambria',14),bg="lightblue") obj5.grid() obj6=Button(vCitas,text="Eliminar Cita",command=lambda:seleccionarCita(cita) or eliminarCita(cita) or ocultar(vCitas)) obj6.grid() obj7=Button(vCitas,text="Modificar Fecha u Hora",command=lambda:mostrarDatosCitaModificar(cita) or ocultar(vCitas) or seleccionarCita(cita)) obj7.grid() obj8=Button(vCitas,text="Cambiar Estado",command=lambda:seleccionarPaciente(cita.paciente.nombre,0) or seleccionarCita(cita) or mostrar(vConfirmarCambiarEstadoCita) or ocultar(vCitas)) obj8.grid() listaObjetosInfoCita.append(obj7) listaObjetosInfoCita.append(obj8) listaObjetosInfoCita.append(obj1) listaObjetosInfoCita.append(obj2) listaObjetosInfoCita.append(obj3) listaObjetosInfoCita.append(obj4) listaObjetosInfoCita.append(obj5) listaObjetosInfoCita.append(obj6) mostrar(vCitas) #Muestra Todas las citas de un determinado paciente def mostrarCitasPaciente(Paciente): global listaCitas global listaObjetosInfoCita for cita in listaCitas: if cita.paciente.nombre==Paciente and cita.estado=="Pendiente": obj1=Label(vCitas,text="Doctor: "+cita.doctor.nombre,font=('Cambria',14),bg="lightblue") obj1.grid() obj2=Label(vCitas,text="Paciente: "+cita.paciente.nombre,font=('Cambria',14),bg="lightblue") obj2.grid() obj3=Label(vCitas,text="Fecha: "+cita.fecha,font=('Cambria',14),bg="lightblue") obj3.grid() obj4=Label(vCitas,text="Hora: "+cita.hora,font=('Cambria',14),bg="lightblue") obj4.grid() obj5=Label(vCitas,text="Estado: Pendiente",font=('Cambria',14),bg="lightblue") obj5.grid() obj6=Button(vCitas,text="Eliminar Cita",command=lambda:seleccionarCita(cita) or eliminarCita(cita) or ocultar(vCitas)) obj6.grid() obj7=Button(vCitas,text="Modificar Fecha u Hora",command=lambda:mostrarDatosCitaModificar(cita) or ocultar(vCitas) or seleccionarCita(cita)) obj7.grid() obj8=Button(vCitas,text="Cambiar Estado",command=lambda:seleccionarPaciente(cita.paciente.nombre,0) or seleccionarCita(cita) or mostrar(vConfirmarCambiarEstadoCita) or ocultar(vCitas)) obj8.grid() listaObjetosInfoCita.append(obj7) listaObjetosInfoCita.append(obj8) listaObjetosInfoCita.append(obj1) listaObjetosInfoCita.append(obj2) listaObjetosInfoCita.append(obj3) listaObjetosInfoCita.append(obj4) listaObjetosInfoCita.append(obj5) listaObjetosInfoCita.append(obj6) mostrar(vCitas) #Cambia el estado de una cita a realizada def CambiarEstadoCita(): global CitaTemporal global listaCitas for cita in listaCitas: if cita.doctor.nombre==CitaTemporal.doctor.nombre and cita.fecha==CitaTemporal.fecha and cita.hora==CitaTemporal.hora: cita.estado="Realizada" mostrar(vDeseaAsignarTratamiento) #Asigna un tratamiento a un paciente def asignarTratamiento(descripcion): global CitaTemporal global PacienteTemporal global listaPacientes if descripcion=="": return mostrar(vFaltaInfoDescripcion) nuevoTratamiento=Tratamiento(CitaTemporal.fecha,f.doctor,descripcion) for paciente in listaPacientes: if paciente.nombre==PacienteTemporal: paciente.listaTratamientos.append(nuevoTratamiento) for trata in paciente.listaTratamientos: print trata.doctor print trata.fecha print trata.descripcion break mostrar(vTratamientoAsignado) #Declara como finalizado un tratamiento def cancelarTratamiento(Tratamiento): Tratamiento.estado="Finalizado" mostrar(vTratamientoCancelado) ##Selecciona una cita para trabajar con esta globalmente def seleccionarCita(cita): global CitaTemporal CitaTemporal=cita #Muestra un listbox con los doctores registrados def mostrarDoctores(): global ListBoxDoctores global ListBoxDoctores2 global listaDoctores for doctor in listaDoctores: ListBoxDoctores.insert(END,doctor.nombre) ListBoxDoctores2.insert(END,doctor.nombre) #Muestra un listbox con los pacientes registrados def mostrarPacientes(): global ListBoxPacientes global ListBoxPacientes2 global listaPacientes for paciente in listaPacientes: ListBoxPacientes.insert(END,paciente.nombre) ListBoxPacientes2.insert(END,paciente.nombre) ##Muestra un listbox con fechas def mostrarFechas(): global ListBoxFechas global listaCitas global listaTemporal for cita in listaCitas: if cita.fecha not in listaTemporal: listaTemporal.append(cita.fecha) for fecha in listaTemporal: ListBoxFechas.insert(END,fecha) ##Funcion para crear una nueva instancia de la clase doctor def agregarDoctor(nombre,identificacion,correo1,correo2,correo3,telefono1,telefono2,telefono3,fechaNacimiento,direccion,especialidad,lista): global ListBoxDoctores global listaDoctores if nombre=="" or identificacion=="" or correo1=="" or telefono1=="" or fechaNacimiento=="" or direccion=="" or especialidad=="": return mostrar(vFaltaInfoDoctor) for doctor in listaDoctores: if doctor.identificacion==identificacion: return mostrar(vDoctorRepetido) for doctor in listaDoctores: if doctor.nombre==nombre: return mostrar(vNombreDoctorRepetido) if correo1==correo2 or correo1==correo3: return mostrar(vInfoDoctorRepetida) if telefono1==telefono2 or telefono1==telefono3: return mostrar(vInfoDoctorRepetida) else: nuevoDoctor=Doctor(identificacion,nombre,fechaNacimiento,direccion,especialidad) nuevoDoctor.listaCorreos.append(correo1) nuevoDoctor.listaTelefonos.append(telefono1) if correo2!="": nuevoDoctor.listaCorreos.append(correo2) if correo3!="": nuevoDoctor.listaCorreos.append(correo3) if telefono2!="": nuevoDoctor.listaTelefonos.append(telefono2) if telefono3!="": nuevoDoctor.listaTelefonos.append(telefono3) lista.append(nuevoDoctor) ListBoxDoctores.insert(END,nuevoDoctor.nombre) return mostrar(vDoctorAgregado) #Funcion para agregar una nueva instancia de la clase paciente def agregarPaciente(nombre,identificacion,correo1,correo2,correo3,telefono1,telefono2,telefono3,fechaNacimiento,direccion,ocupacion,lista): global ListBoxPacientes global listaPacientes if nombre=="" or identificacion=="" or correo1=="" or telefono1=="" or fechaNacimiento=="" or direccion=="" or ocupacion=="": return mostrar(vFaltaInfoPaciente) for paciente in listaPacientes: if paciente.identificacion==identificacion: return mostrar(vPacienteRepetido) for paciente in listaPacientes: if paciente.nombre==nombre: return mostrar(vNombrePacienteRepetido) if correo1==correo2 or correo1==correo3: return mostrar(vInfoPacienteRepetida) if telefono1==telefono2 or telefono1==telefono3: return mostrar(vInfoPacienteRepetida) else: nuevoPaciente=Paciente(identificacion,nombre,fechaNacimiento,direccion,ocupacion) nuevoPaciente.listaCorreos.append(correo1) nuevoPaciente.listaTelefonos.append(telefono1) if correo2!="": nuevoPaciente.listaCorreos.append(correo2) if correo3!="": nuevoPaciente.listaCorreos.append(correo3) if telefono2!="": nuevoPaciente.listaTelefonos.append(telefono2) if telefono3!="": nuevoPaciente.listaTelefonos.append(telefono3) lista.append(nuevoPaciente) ListBoxPacientes.insert(END,nuevoPaciente.nombre) print nuevoPaciente.listaTelefonos return mostrar(vPacienteAgregado) #Funcion para agregar una nueva instancia de la clase Cita def agregarCita(fecha,hora,paciente,doctor,lista): global listaCitas global listaTemporal global listaDoctores global listaPacientes global ListBoxFechas listaCitasTemporal=[] if fecha=="" or hora=="": return mostrar(vFaltaInfoCita) for cita in listaCitas: if cita.doctor.nombre==doctor: listaCitasTemporal.append(cita) for cita in listaCitasTemporal: if cita.fecha==fecha and cita.hora==hora: limpiarEntryCitas() return mostrar(vDoctorOcupado) listaCitasTemporal=[] for cita in listaCitas: if cita.paciente.nombre==paciente: listaCitasTemporal.append(cita) for cita in listaCitasTemporal: if cita.fecha==fecha and cita.hora==hora: limpiarEntryCitas() return mostrar(vPacienteOcupado) listaCitasTemporal=[] for PACIENTE in listaPacientes: if PACIENTE.nombre==paciente: paciente=PACIENTE break for DOCTOR in listaDoctores: if DOCTOR.nombre==doctor: doctor=DOCTOR break nuevaCita=Cita(fecha,hora,paciente,doctor) lista.append(nuevaCita) limpiarEntryCitas() if fecha not in listaTemporal: ListBoxFechas.insert(END,fecha) return mostrar(vCitaAgregada) #Funcion para buscar un doctor mediante su identificacion def buscar_doctor(identificacion): global DoctorTemporal global listaDoctores for doctor in listaDoctores: if doctor.identificacion==identificacion: DoctorTemporal=doctor.nombre return mostrar(vDoctorEncontrado) return mostrar(vDoctorNoEncontrado) #Funcion para buscar un paciente mediante su identificacion def buscar_paciente(identificacion): global PacienteTemporal global listaPacientes for Paciente in listaPacientes: if Paciente.identificacion==identificacion: PacienteTemporal=Paciente.nombre return mostrar(vPacienteEncontrado) return mostrar(vPacienteNoEncontrado) #Funcion que reescribe la info de una instancia de tipo doctor def modificarInfoDoctor(nombre,identificacion,correo1,correo2,correo3,telefono1,telefono2,telefono3,fechaNacimiento,direccion,especialidad): global DoctorTemporal global listaDoctores if nombre=="" or identificacion=="" or correo1=="" or telefono1=="" or fechaNacimiento=="" or direccion=="" or especialidad=="": return mostrar(vFaltaInfoDoctor2) if nombre!=DoctorTemporal: for doctor in listaDoctores: if doctor.nombre==nombre: return mostrar(vNombreDoctorRepetido2) if correo1==correo2 or correo1==correo3: return mostrar(vInfoDoctorRepetida2) if telefono1==telefono2 or telefono1==telefono3: return mostrar(vInfoDoctorRepetida2) for doctor in listaDoctores: if doctor.nombre==DoctorTemporal: doctor.nombre=nombre if identificacion!=doctor.identificacion: for DOCTOR in listaDoctores: if DOCTOR.identificacion==identificacion: return mostrar(vDoctorRepetido2) doctor.identificacion=identificacion doctor.fechaNacimiento=fechaNacimiento doctor.direccion=direccion doctor.especialidad=especialidad doctor.listaCorreos=[] doctor.listaCorreos.append(correo1) doctor.listaCorreos.append(correo2) doctor.listaCorreos.append(correo3) doctor.listaTelefonos=[] doctor.listaTelefonos.append(telefono1) doctor.listaTelefonos.append(telefono2) doctor.listaTelefonos.append(telefono3) DoctorTemporal=doctor.nombre break mostrar(vDoctorModificado) #Funcion que reescribe la info de una instancia de tipo paciente def modificarInfoPaciente(nombre,identificacion,correo1,correo2,correo3,telefono1,telefono2,telefono3,fechaNacimiento,direccion,ocupacion): global PacienteTemporal global listaPacientes if nombre=="" or identificacion=="" or correo1=="" or telefono1=="" or fechaNacimiento=="" or direccion=="" or ocupacion=="": return mostrar(vFaltaInfoPaciente2) if nombre!=PacienteTemporal: for Paciente in listaPacientes: if Paciente.nombre==nombre: return mostrar(vNombrePacienteRepetido2) if correo1==correo2 or correo1==correo3: return mostrar(vInfoPacienteRepetida2) if telefono1==telefono2 or telefono1==telefono3: return mostrar(vInfoPacienteRepetida2) for Paciente in listaPacientes: if Paciente.nombre==PacienteTemporal: Paciente.nombre=nombre if identificacion!=Paciente.identificacion: for PACIENTE in listaPacientes: if PACIENTE.identificacion==identificacion: return mostrar(vPacienteRepetido2) Paciente.identificacion=identificacion Paciente.fechaNacimiento=fechaNacimiento Paciente.direccion=direccion Paciente.ocupacion=ocupacion Paciente.listaCorreos=[] Paciente.listaCorreos.append(correo1) Paciente.listaCorreos.append(correo2) Paciente.listaCorreos.append(correo3) Paciente.listaTelefonos=[] Paciente.listaTelefonos.append(telefono1) Paciente.listaTelefonos.append(telefono2) Paciente.listaTelefonos.append(telefono3) PacienteTemporal=Paciente.nombre break mostrar(vPacienteModificado) #Funcion que muestra todos los tratamientos de un paciente def mostrarTratamientos(): global PacienteTemporal global listaPacientes global listaObjetosInfoTratamientos for paciente in listaPacientes: if paciente.nombre==PacienteTemporal: for tratamiento in paciente.listaTratamientos: obj1=Label(vVerTratamientos,font=('Cambria',14),bg="lightblue",text=tratamiento.doctor.nombre) obj1.grid() obj2=Label(vVerTratamientos,font=('Cambria',14),bg="lightblue",text=tratamiento.fecha) obj2.grid() obj5=Label(vVerTratamientos,font=('Cambria',14),bg="lightblue",text=tratamiento.descripcion) obj5.grid() obj3=Label(vVerTratamientos,font=('Cambria',14),bg="lightblue",text=tratamiento.estado) obj3.grid() if tratamiento.estado=="Activo": obj4=Button(vVerTratamientos,text="Cancelar este Tratamiento",command=lambda:cancelarTratamiento(tratamiento) or ocultar(vVerTratamientos) or olvidarObjetos(listaObjetosInfoTratamientos)) obj4.grid() listaObjetosInfoTratamientos.append(obj4) listaObjetosInfoTratamientos.append(obj1) listaObjetosInfoTratamientos.append(obj2) listaObjetosInfoTratamientos.append(obj3) listaObjetosInfoTratamientos.append(obj5) mostrar(vVerTratamientos) #Muestra los datos actuales de un doctor para q se modifiquen def mostrarDatosDoctorModificar(): global vsNombreDoctor2 global vsIdentificacionDoctor2 global vsCorreoDoctor1_2 global vsCorreoDoctor2_2 global vsCorreoDoctor3_2 global vsTelefonoDoctor1_2 global vsTelefonoDoctor2_2 global vsTelefonoDoctor3_2 global vsfnacimientoDoctor2 global vsDireccionDoctor2 global vsEspecialidadDoctor2 global DoctorTemporal global listaDoctores DoctorActual="" for Doctor in listaDoctores: if Doctor.nombre==DoctorTemporal: DoctorActual=Doctor break vsNombreDoctor2.set(DoctorActual.nombre) vsIdentificacionDoctor2.set(DoctorActual.identificacion) vsCorreoDoctor1_2.set(DoctorActual.listaCorreos[0]) if len(DoctorActual.listaCorreos)>=2: vsCorreoDoctor2_2.set(DoctorActual.listaCorreos[1]) if len(DoctorActual.listaCorreos)>=3: vsCorreoDoctor3_2.set(DoctorActual.listaCorreos[2]) vsTelefonoDoctor1_2.set(DoctorActual.listaTelefonos[0]) if len(DoctorActual.listaTelefonos)>=2: vsTelefonoDoctor2_2.set(DoctorActual.listaTelefonos[1]) if len(DoctorActual.listaTelefonos)>=3: vsTelefonoDoctor3_2.set(DoctorActual.listaTelefonos[2]) vsfnacimientoDoctor2.set(DoctorActual.fechaNacimiento) vsDireccionDoctor2.set(DoctorActual.direccion) vsEspecialidadDoctor2.set(DoctorActual.especialidad) mostrar(vModificarDoctor) #Muestra los datos actuales de un paciente para q se modifiquen def mostrarDatosPacienteModificar(): global vsNombrePaciente2 global vsIdentificacionPaciente2 global vsCorreoPaciente1_2 global vsCorreoPaciente2_2 global vsCorreoPaciente3_2 global vsTelefonoPaciente1_2 global vsTelefonoPaciente2_2 global vsTelefonoPaciente3_2 global vsfnacimientoPaciente2 global vsDireccionPaciente2 global vsOcupacionPaciente2 global PacienteTemporal global listaPacientes PacienteActual="" for Paciente in listaPacientes: if Paciente.nombre==PacienteTemporal: PacienteActual=Paciente break vsNombrePaciente2.set(PacienteActual.nombre) vsIdentificacionPaciente2.set(PacienteActual.identificacion) vsCorreoPaciente1_2.set(PacienteActual.listaCorreos[0]) if len(PacienteActual.listaCorreos)>=2: vsCorreoPaciente2_2.set(PacienteActual.listaCorreos[1]) if len(PacienteActual.listaCorreos)>=3: vsCorreoPaciente3_2.set(PacienteActual.listaCorreos[2]) vsTelefonoPaciente1_2.set(PacienteActual.listaTelefonos[0]) if len(PacienteActual.listaTelefonos)>=2: vsTelefonoPaciente2_2.set(PacienteActual.listaTelefonos[1]) if len(PacienteActual.listaTelefonos)>=3: vsTelefonoPaciente3_2.set(PacienteActual.listaTelefonos[2]) vsfnacimientoPaciente2.set(PacienteActual.fechaNacimiento) vsDireccionPaciente2.set(PacienteActual.direccion) vsOcupacionPaciente2.set(PacienteActual.ocupacion) mostrar(vModificarPaciente) #Muestra los datos actuales de una cita para q se modifiquen def mostrarDatosCitaModificar(cita): global vsFechaCita2 global vsHoraCita2 vsFechaCita2.set(cita.fecha) vsHoraCita2.set(cita.hora) mostrar(vModificarCita) ##Reescribe los datos de una instancia de tipo cita def modificarCita(fechaModificada,horaModificada): global CitaTemporal global listaCitas listaCitasTemporal=[] for cita in listaCitas: if cita.doctor.nombre==CitaTemporal.doctor.nombre and cita.fecha==CitaTemporal.fecha and cita.hora==CitaTemporal.hora: if cita.fecha!=fechaModificada or cita.hora!=horaModificada: for CITA in listaCitas: if CITA.doctor.nombre==cita.doctor: listaCitasTemporal.append(cita) for citaSameDoctor in listaCitasTemporal: if citaSameDoctor.fecha==fecha and citaSameDoctor.hora==hora: return mostrar(vDoctorOcupado2) listaCitasTemporal=[] for CITA in listaCitas: if CITA.paciente.nombre==cita.paciente: listaCitasTemporal.append(cita) for citaSamePaciente in listaCitasTemporal: if citaSamePaciente.fecha==fecha and citaSamePaciente.hora==hora: return mostrar(vPacienteOcupado2) cita.fecha=fechaModificada cita.hora=horaModificada break mostrar(vCitaModificada) #Selecciona un doctor para trabajar con el globalmente def seleccionarDoctor(nombre,indice): global DoctorTemporal global indiceDoctorTemporal DoctorTemporal=nombre indiceDoctorTemporal=indice #Selecciona un paciente para trabajar con el globalmente def seleccionarPaciente(nombre,indice): global PacienteTemporal global indicePacienteTemporal PacienteTemporal=nombre indicePacienteTemporal=indice #Elimina una cita def eliminarCita(CITA): global listaCitas global listaObjetosInfoCita i=0 for cita in listaCitas: if cita.fecha==CITA.fecha and cita.hora==CITA.hora and cita.doctor.nombre==CITA.doctor.nombre: del listaCitas[i] break i+=1 for objeto in listaObjetosInfoCita: objeto.grid_forget() return mostrar(vCitaEliminada) #Elimina un doctor def eliminarDoctor(): global listaDoctores global DoctorTemporal global ListBoxDoctores global ListBoxDoctores2 global indiceDoctorTemporal i=0 for doctor in listaDoctores: if doctor.nombre==DoctorTemporal: del listaDoctores[i] break i+=1 ListBoxDoctores.delete(indiceDoctorTemporal) ListBoxDoctores2.delete(indiceDoctorTemporal) return mostrar(vDoctorEliminado) #Elimina un paciente def eliminarPaciente(): global listaPacientes global PacienteTemporal global ListBoxPacientes global ListBoxPacientes2 global indicePacienteTemporal i=0 for Paciente in listaPacientes: if Paciente.nombre==PacienteTemporal: del listaPacientes[i] break i+=1 ListBoxPacientes.delete(indicePacienteTemporal) ListBoxPacientes2.delete(indicePacienteTemporal) return mostrar(vPacienteEliminado) #Actualiza el listbox de doctores cuando se modifique la info de estos def actualizarListboxDoctores(): global DoctorTemporal global ListBoxDoctores global ListBoxDoctores2 global indiceDoctorTemporal ListBoxDoctores.delete(indiceDoctorTemporal) ListBoxDoctores.insert(END,DoctorTemporal) ListBoxDoctores2.delete(indiceDoctorTemporal) ListBoxDoctores2.insert(END,DoctorTemporal) return mostrar(vDoctores) #Actualiza el listbox de pacientes cuando se modifique la info de estos def actualizarListboxPacientes(): global PacienteTemporal global ListBoxPacientes global ListBoxPacientes2 global indicePacienteTemporal ListBoxPacientes.delete(indicePacienteTemporal) ListBoxPacientes.insert(END,PacienteTemporal) ListBoxPacientes2.delete(indicePacienteTemporal) ListBoxPacientes2.insert(END,PacienteTemporal) return mostrar(vPacientes) #MUestra la info detallada un determinado doctor def mostrarInfoDoctor(Doctor): global listaDoctores global listaObjetosInfoDoctor global DoctorTemporal DoctorActual='' for doctor in listaDoctores: if doctor.nombre==Doctor: DoctorActual=doctor Nombre="Nombre: "+DoctorActual.nombre lVerInfoDoctorNombre=Label(vVerInfoDoctor,font=('Cambria',14),bg="lightblue",text=Nombre) lVerInfoDoctorNombre.pack() listaObjetosInfoDoctor.append(lVerInfoDoctorNombre) Identificacion="Identificacion: "+DoctorActual.identificacion lVerInfoDoctorId=Label(vVerInfoDoctor,font=('Cambria',14),bg="lightblue",text=Identificacion) lVerInfoDoctorId.pack() listaObjetosInfoDoctor.append(lVerInfoDoctorId) Telefonos="Telefonos: " for telefono in DoctorActual.listaTelefonos: if telefono==DoctorActual.listaTelefonos[-1]: Telefonos=Telefonos+telefono else: Telefonos=Telefonos+telefono+ ", " lVerInfoDoctorTelefono=Label(vVerInfoDoctor,font=('Cambria',14),bg="lightblue",text=Telefonos) lVerInfoDoctorTelefono.pack() listaObjetosInfoDoctor.append(lVerInfoDoctorTelefono) Correos="Correos: " for correo in DoctorActual.listaCorreos: if correo==DoctorActual.listaCorreos[-1]: Correos=Correos+correo else: Correos=Correos+correo+", " lVerInfoDoctorCorreo=Label(vVerInfoDoctor,font=('Cambria',14),bg="lightblue",text=Correos) lVerInfoDoctorCorreo.pack() listaObjetosInfoDoctor.append(lVerInfoDoctorCorreo) FechaNacimiento="Fecha de Nacimiento: "+DoctorActual.fechaNacimiento lVerInfoDoctorNacimiento=Label(vVerInfoDoctor,font=('Cambria',14),bg="lightblue",text=FechaNacimiento) lVerInfoDoctorNacimiento.pack() listaObjetosInfoDoctor.append(lVerInfoDoctorNacimiento) Direccion="Direccion: "+DoctorActual.direccion lVerInfoDoctorDireccion=Label(vVerInfoDoctor,font=('Cambria',14),bg="lightblue",text=Direccion) lVerInfoDoctorDireccion.pack() listaObjetosInfoDoctor.append(lVerInfoDoctorDireccion) Especialidad="Especialidad: "+DoctorActual.especialidad lVerInfoDoctorEspecialidad=Label(vVerInfoDoctor,font=('Cambria',14),bg="lightblue",text=Especialidad) lVerInfoDoctorEspecialidad.pack() listaObjetosInfoDoctor.append(lVerInfoDoctorEspecialidad) mostrar(vVerInfoDoctor) #MUestra la info detallada un determinado paciente def mostrarInfoPaciente(Paciente): global listaPacientes global listaObjetosInfoPaciente global PacienteTemporal PacienteActual="" for paciente in listaPacientes: if paciente.nombre==Paciente: PacienteActual=paciente Nombre="Nombre: " +PacienteActual.nombre lVerInfoPacienteNombre=Label(vVerInfoPaciente,font=('Cambria',14),bg="lightblue",text=Nombre) lVerInfoPacienteNombre.pack() listaObjetosInfoPaciente.append(lVerInfoPacienteNombre) Identificacion="Identificacion: "+PacienteActual.identificacion lVerInfoPacienteId=Label(vVerInfoPaciente,font=('Cambria',14),bg="lightblue",text=Identificacion) lVerInfoPacienteId.pack() listaObjetosInfoPaciente.append(lVerInfoPacienteId) Telefonos="Telefonos: " for telefono in PacienteActual.listaTelefonos: if telefono==PacienteActual.listaTelefonos[-1]: Telefonos=Telefonos+telefono else: Telefonos=Telefonos+telefono+", " lVerInfoPacienteTelefono=Label(vVerInfoPaciente,font=('Cambria',14),bg="lightblue",text=Telefonos) lVerInfoPacienteTelefono.pack() listaObjetosInfoPaciente.append(lVerInfoPacienteTelefono) Correos="Correos: " for correo in PacienteActual.listaCorreos: if correo==PacienteActual.listaCorreos[-1]: Correos=Correos+correo else: Correos=Correos+correo+", " lVerInfoPacienteCorreo=Label(vVerInfoPaciente,font=('Cambria',14),bg="lightblue",text=Correos) lVerInfoPacienteCorreo.pack() listaObjetosInfoPaciente.append(lVerInfoPacienteCorreo) FechaNacimiento="Fecha de Nacimiento: "+PacienteActual.fechaNacimiento lVerInfoPacienteNacimiento=Label(vVerInfoPaciente,font=('Cambria',14),bg="lightblue",text=FechaNacimiento) lVerInfoPacienteNacimiento.pack() listaObjetosInfoPaciente.append(lVerInfoPacienteNacimiento) Direccion="Direccion: "+PacienteActual.direccion lVerInfoPacienteDireccion=Label(vVerInfoPaciente,font=('Cambria',14),bg="lightblue",text=Direccion) lVerInfoPacienteDireccion.pack() listaObjetosInfoPaciente.append(lVerInfoPacienteDireccion) Ocupacion="Ocupacion: "+PacienteActual.ocupacion lVerInfoPacienteOcupacion=Label(vVerInfoPaciente,font=('Cambria',14),bg="lightblue",text=Ocupacion) lVerInfoPacienteOcupacion.pack() listaObjetosInfoPaciente.append(lVerInfoPacienteOcupacion) mostrar(vVerInfoPaciente) v0=Tk() v0.title("Agenda Medica") v0.geometry("500x500") v0.config(bg="lightblue") labWelcome=Label(v0,font=('Cambria',14),bg="lightblue",text="Que Desea Hacer") labWelcome.pack() bVerDoctores=Button(v0,text="Ver Info Doctores",command=lambda:mostrar(vDoctores) or ocultar(v0)) bVerDoctores.pack() bVerPacientes=Button(v0,text="Ver Info Pacientes",command=lambda:mostrar(vPacientes) or ocultar(v0)) bVerPacientes.pack() bVerCitas=Button(v0,text="Administrar Citas",command=lambda:mostrar(vOpcionCitas) or ocultar(v0)) bVerCitas.pack() bSalir=Button(v0,text="Salir",command=lambda:salir()) bSalir.pack() vDoctores=Toplevel(v0) vDoctores.config(bg="lightblue") vDoctores.title("Doctores") vDoctores.geometry("500x500") vDoctores.withdraw() ListBoxDoctores=Listbox(vDoctores) ListBoxDoctores.pack() bAgregarDoctor=Button(vDoctores,text="Agregar Nuevo Doctor",command=lambda:mostrar(vAgregarDoctor) or ocultar(vDoctores)) bAgregarDoctor.pack() bEliminarDoctor=Button(vDoctores,text="Eliminar Doctor",command=lambda:seleccionarDoctor(ListBoxDoctores.get(ListBoxDoctores.curselection()),ListBoxDoctores.curselection()) or mostrar(vConfirmarEliminarDoctor) or ocultar(vDoctores)) bEliminarDoctor.pack() bVerInfoDoctores=Button(vDoctores,text="Ver Informacion",command=lambda:mostrarInfoDoctor(ListBoxDoctores.get(ListBoxDoctores.curselection())) or ocultar(vDoctores) or seleccionarDoctor(ListBoxDoctores.get(ListBoxDoctores.curselection()),ListBoxDoctores.curselection())) bVerInfoDoctores.pack() bBuscarDoctor=Button(vDoctores,text="Buscar Doctor",command=lambda:mostrar(vBuscarDoctor) or ocultar(vDoctores)) bBuscarDoctor.pack() bInicioDoctores=Button(vDoctores,text="Volver al Inicio",command=lambda:mostrar(v0) or ocultar(vDoctores)) bInicioDoctores.pack() vAgregarDoctor=Toplevel(v0) vAgregarDoctor.config(bg="lightblue") vAgregarDoctor.title("Agregar nuevo doctor") vAgregarDoctor.geometry("500x700") vAgregarDoctor.withdraw() lNombreDoctor=Label(vAgregarDoctor,font=('Cambria',14),bg="lightblue",text="Digite el nombre del Doctor") lNombreDoctor.pack() vsNombreDoctor=StringVar() eNombreDoctor=Entry(vAgregarDoctor,textvariable=vsNombreDoctor,width=20) eNombreDoctor.pack() lIdentificacionDoctor=Label(vAgregarDoctor,font=('Cambria',14),bg="lightblue",text="Digite el numero de Identificacion del Doctor") lIdentificacionDoctor.pack() vsIdentificacionDoctor=StringVar() eIdentificacionDoctor=Entry(vAgregarDoctor,textvariable=vsIdentificacionDoctor,width=20) eIdentificacionDoctor.pack() lCorreosDoctor=Label(vAgregarDoctor,font=('Cambria',14),bg="lightblue",text="Digite uno o mas correos del Doctor") lCorreosDoctor.pack() vsCorreoDoctor1=StringVar() eCorreoDoctor1=Entry(vAgregarDoctor,textvariable=vsCorreoDoctor1,width=20) eCorreoDoctor1.pack() vsCorreoDoctor2=StringVar() eCorreoDoctor2=Entry(vAgregarDoctor,textvariable=vsCorreoDoctor2,width=20) eCorreoDoctor2.pack() vsCorreoDoctor3=StringVar() eCorreoDoctor3=Entry(vAgregarDoctor,textvariable=vsCorreoDoctor3,width=20) eCorreoDoctor3.pack() lTelefonosDoctor=Label(vAgregarDoctor,font=('Cambria',14),bg="lightblue",text="Digite uno o mas telefonos del Doctor") lTelefonosDoctor.pack() vsTelefonoDoctor1=StringVar() eTelefonoDoctor1=Entry(vAgregarDoctor,textvariable=vsTelefonoDoctor1,width=20) eTelefonoDoctor1.pack() vsTelefonoDoctor2=StringVar() eTelefonoDoctor2=Entry(vAgregarDoctor,textvariable=vsTelefonoDoctor2,width=20) eTelefonoDoctor2.pack() vsTelefonoDoctor3=StringVar() eTelefonoDoctor3=Entry(vAgregarDoctor,textvariable=vsTelefonoDoctor3,width=20) eTelefonoDoctor3.pack() lfnacimientoDoctor=Label(vAgregarDoctor,font=('Cambria',14),bg="lightblue",text="Digite la fecha de nacimiento del Doctor") lfnacimientoDoctor.pack() vsfnacimientoDoctor=StringVar() efnacimientoDoctor=Entry(vAgregarDoctor,textvariable=vsfnacimientoDoctor,width=20) efnacimientoDoctor.pack() lDireccionDoctor=Label(vAgregarDoctor,font=('Cambria',14),bg="lightblue",text="Digite la direccion del Doctor") lDireccionDoctor.pack() vsDireccionDoctor=StringVar() eDireccionDoctor=Entry(vAgregarDoctor,textvariable=vsDireccionDoctor,width=20) eDireccionDoctor.pack() lEspecialidadDoctor=Label(vAgregarDoctor,font=('Cambria',14),bg="lightblue",text="Digite la especialidad del Doctor") lEspecialidadDoctor.pack() vsEspecialidadDoctor=StringVar() eEspecialidadDoctor=Entry(vAgregarDoctor,textvariable=vsEspecialidadDoctor,width=20) eEspecialidadDoctor.pack() bAgregarDoctor=Button(vAgregarDoctor,text="Agregar",command=lambda:agregarDoctor(vsNombreDoctor.get(),vsIdentificacionDoctor.get(),vsCorreoDoctor1.get(),vsCorreoDoctor2.get(),vsCorreoDoctor3.get(),vsTelefonoDoctor1.get(),vsTelefonoDoctor2.get(),vsTelefonoDoctor3.get(),vsfnacimientoDoctor.get(),vsDireccionDoctor.get(),vsEspecialidadDoctor.get(),listaDoctores) or ocultar(vAgregarDoctor)) bAgregarDoctor.pack() bVolverDoctores=Button(vAgregarDoctor,text="Volver a Informacion de Doctores",command=lambda:mostrar(vDoctores) or ocultar(vAgregarDoctor)) bVolverDoctores.pack() vModificarDoctor=Toplevel(v0) vModificarDoctor.config(bg="lightblue") vModificarDoctor.title("Modificar Doctor") vModificarDoctor.geometry("500x700") vModificarDoctor.withdraw() lNombreDoctor2=Label(vModificarDoctor,font=('Cambria',14),bg="lightblue",text="Digite el nombre del Doctor") lNombreDoctor2.pack() vsNombreDoctor2=StringVar() eNombreDoctor2=Entry(vModificarDoctor,textvariable=vsNombreDoctor2,width=20) eNombreDoctor2.pack() lIdentificacionDoctor2=Label(vModificarDoctor,font=('Cambria',14),bg="lightblue",text="Digite el numero de Identificacion del Doctor") lIdentificacionDoctor2.pack() vsIdentificacionDoctor2=StringVar() eIdentificacionDoctor2=Entry(vModificarDoctor,textvariable=vsIdentificacionDoctor2,width=20) eIdentificacionDoctor2.pack() lCorreosDoctor2=Label(vModificarDoctor,font=('Cambria',14),bg="lightblue",text="Digite uno o mas correos del Doctor") lCorreosDoctor2.pack() vsCorreoDoctor1_2=StringVar() eCorreoDoctor1_2=Entry(vModificarDoctor,textvariable=vsCorreoDoctor1_2,width=20) eCorreoDoctor1_2.pack() vsCorreoDoctor2_2=StringVar() eCorreoDoctor2_2=Entry(vModificarDoctor,textvariable=vsCorreoDoctor2_2,width=20) eCorreoDoctor2_2.pack() vsCorreoDoctor3_2=StringVar() eCorreoDoctor3_2=Entry(vModificarDoctor,textvariable=vsCorreoDoctor3_2,width=20) eCorreoDoctor3_2.pack() lTelefonosDoctor_2=Label(vModificarDoctor,font=('Cambria',14),bg="lightblue",text="Digite uno o mas telefonos del Doctor") lTelefonosDoctor_2.pack() vsTelefonoDoctor1_2=StringVar() eTelefonoDoctor1_2=Entry(vModificarDoctor,textvariable=vsTelefonoDoctor1_2,width=20) eTelefonoDoctor1_2.pack() vsTelefonoDoctor2_2=StringVar() eTelefonoDoctor2_2=Entry(vModificarDoctor,textvariable=vsTelefonoDoctor2_2,width=20) eTelefonoDoctor2_2.pack() vsTelefonoDoctor3_2=StringVar() eTelefonoDoctor3_2=Entry(vModificarDoctor,textvariable=vsTelefonoDoctor3_2,width=20) eTelefonoDoctor3_2.pack() lfnacimientoDoctor2=Label(vModificarDoctor,font=('Cambria',14),bg="lightblue",text="Digite la fecha de nacimiento del Doctor") lfnacimientoDoctor2.pack() vsfnacimientoDoctor2=StringVar() efnacimientoDoctor2=Entry(vModificarDoctor,textvariable=vsfnacimientoDoctor2,width=20) efnacimientoDoctor2.pack() lDireccionDoctor2=Label(vModificarDoctor,font=('Cambria',14),bg="lightblue",text="Digite la direccion del Doctor") lDireccionDoctor2.pack() vsDireccionDoctor2=StringVar() eDireccionDoctor2=Entry(vModificarDoctor,textvariable=vsDireccionDoctor2,width=20) eDireccionDoctor2.pack() lEspecialidadDoctor2=Label(vModificarDoctor,font=('Cambria',14),bg="lightblue",text="Digite la especialidad del Doctor") lEspecialidadDoctor2.pack() vsEspecialidadDoctor2=StringVar() eEspecialidadDoctor2=Entry(vModificarDoctor,textvariable=vsEspecialidadDoctor2,width=20) eEspecialidadDoctor2.pack() bGuardarCambiosDoctor=Button(vModificarDoctor,text="Guardar Cambios",command=lambda:modificarInfoDoctor(vsNombreDoctor2.get(),vsIdentificacionDoctor2.get(),vsCorreoDoctor1_2.get(),vsCorreoDoctor2_2.get(),vsCorreoDoctor3_2.get(),vsTelefonoDoctor1_2.get(),vsTelefonoDoctor2_2.get(),vsTelefonoDoctor3_2.get(),vsfnacimientoDoctor2.get(),vsDireccionDoctor2.get(),vsEspecialidadDoctor2.get()) or ocultar(vModificarDoctor)) bGuardarCambiosDoctor.pack() bVolverDoctores2=Button(vModificarDoctor,text="Volver a Informacion de Doctores",command=lambda:olvidarGrids(listaObjetosInfoDoctor) or mostrar(vDoctores) or ocultar(vModificarDoctor)) bVolverDoctores2.pack() vDoctorModificado=Toplevel(v0) vDoctorModificado.config(bg="lightblue") vDoctorModificado.title("Doctor Modificado") vDoctorModificado.geometry("500x500") vDoctorModificado.withdraw() lDoctorModificado=Label(vDoctorModificado,font=('Cambria',14),bg="lightblue",text="La informacion ha sido modificada") lDoctorModificado.pack() bDoctorModificado=Button(vDoctorModificado,text="Aceptar",command=lambda:olvidarGrids(listaObjetosInfoDoctor) or actualizarListboxDoctores() or ocultar(vDoctorModificado)) bDoctorModificado.pack() vFaltaInfoDoctor=Toplevel(v0) vFaltaInfoDoctor.config(bg="lightblue") vFaltaInfoDoctor.title("Falta Informacion") vFaltaInfoDoctor.geometry("500x500") vFaltaInfoDoctor.withdraw() lFaltaInfoDoctor=Label(vFaltaInfoDoctor,font=('Cambria',14),bg="lightblue",text="Complete todos los espacios") lFaltaInfoDoctor.pack() bAceptarFaltaInfoDoctor=Button(vFaltaInfoDoctor,text="Aceptar",command=lambda:mostrar(vAgregarDoctor) or ocultar(vFaltaInfoDoctor)) bAceptarFaltaInfoDoctor.pack() vFaltaInfoDoctor2=Toplevel(v0) vFaltaInfoDoctor2.config(bg="lightblue") vFaltaInfoDoctor2.title("Falta Informacion") vFaltaInfoDoctor2.geometry("500x150") vFaltaInfoDoctor2.withdraw() lFaltaInfoDoctor2=Label(vFaltaInfoDoctor2,font=('Cambria',14),bg="lightblue",text="Complete todos los espacios") lFaltaInfoDoctor2.pack() bAceptarFaltaInfoDoctor2=Button(vFaltaInfoDoctor,text="Aceptar",command=lambda:mostrar(vModificarDoctor) or ocultar(vFaltaInfoDoctor2)) bAceptarFaltaInfoDoctor2.pack() vDoctorRepetido=Toplevel(v0) vDoctorRepetido.config(bg="lightblue") vDoctorRepetido.title("Doctor existente") vDoctorRepetido.geometry("500x150") vDoctorRepetido.withdraw() lDoctorRepetido=Label(vDoctorRepetido,font=('Cambria',14),bg="lightblue",text="Ya existe un Doctor con esta identificacion") lDoctorRepetido.pack() bDoctorRepetido=Button(vDoctorRepetido,text="Aceptar",command=lambda:mostrar(vAgregarDoctor) or ocultar(vDoctorRepetido)) bDoctorRepetido.pack() vNombreDoctorRepetido=Toplevel(v0) vNombreDoctorRepetido.config(bg="lightblue") vNombreDoctorRepetido.title("Doctor existente") vNombreDoctorRepetido.geometry("500x150") vNombreDoctorRepetido.withdraw() lNombreDoctorRepetido=Label(vNombreDoctorRepetido,font=('Cambria',14),bg="lightblue",text="Ya existe un Doctor con este nombre") lNombreDoctorRepetido.pack() bNombreDoctorRepetido=Button(vNombreDoctorRepetido,text="Aceptar",command=lambda:mostrar(vAgregarDoctor) or ocultar(vNombreDoctorRepetido)) bNombreDoctorRepetido.pack() vNombreDoctorRepetido2=Toplevel(v0) vNombreDoctorRepetido2.config(bg="lightblue") vNombreDoctorRepetido2.title("Doctor existente") vNombreDoctorRepetido2.geometry("500x150") vNombreDoctorRepetido2.withdraw() lNombreDoctorRepetido2=Label(vNombreDoctorRepetido2,font=('Cambria',14),bg="lightblue",text="Ya existe un Doctor con este nombre") lNombreDoctorRepetido2.pack() bNombreDoctorRepetido2=Button(vNombreDoctorRepetido2,text="Aceptar",command=lambda:mostrar(vModificarDoctor) or ocultar(vNombreDoctorRepetido2)) bNombreDoctorRepetido2.pack() vDoctorRepetido2=Toplevel(v0) vDoctorRepetido2.config(bg="lightblue") vDoctorRepetido2.title("Doctor existente") vDoctorRepetido2.geometry("500x150") vDoctorRepetido2.withdraw() lDoctorRepetido2=Label(vDoctorRepetido2,font=('Cambria',14),bg="lightblue",text="Ya existe un Doctor con esta identificacion") lDoctorRepetido2.pack() bDoctorRepetido2=Button(vDoctorRepetido2,text="Aceptar",command=lambda:mostrar(vModificarDoctor) or ocultar(vDoctorRepetido2)) bDoctorRepetido2.pack() vInfoDoctorRepetida=Toplevel(v0) vInfoDoctorRepetida.config(bg="lightblue") vInfoDoctorRepetida.title("Informacion Repetida") vInfoDoctorRepetida.geometry("500x150") vInfoDoctorRepetida.withdraw() lInfoDoctorRepetida=Label(vInfoDoctorRepetida,font=('Cambria',14),bg="lightblue",text="Ha digitado informacion repetida") lInfoDoctorRepetida.pack() bInfoDoctorRepetida=Button(vInfoDoctorRepetida,text="Aceptar",command=lambda:mostrar(vAgregarDoctor) or ocultar(vInfoDoctorRepetida)) bInfoDoctorRepetida.pack() vInfoDoctorRepetida2=Toplevel(v0) vInfoDoctorRepetida2.config(bg="lightblue") vInfoDoctorRepetida2.title("Informacion Repetida") vInfoDoctorRepetida2.geometry("500x150") vInfoDoctorRepetida2.withdraw() lInfoDoctorRepetida2=Label(vInfoDoctorRepetida2,font=('Cambria',14),bg="lightblue",text="Ha digitado informacion repetida") lInfoDoctorRepetida2.pack() bInfoDoctorRepetida2=Button(vInfoDoctorRepetida2,text="Aceptar",command=lambda:mostrar(vModificarDoctor) or ocultar(vInfoDoctorRepetida2)) bInfoDoctorRepetida2.pack() vDoctorAgregado=Toplevel(v0) vDoctorAgregado.config(bg="lightblue") vDoctorAgregado.title("Doctor Agregado") vDoctorAgregado.geometry("500x150") vDoctorAgregado.withdraw() lDoctorAgregado=Label(vDoctorAgregado,font=('Cambria',14),bg="lightblue",text="Doctor Agregado Exitosamente!") lDoctorAgregado.pack() bAceptarDoctorAgregado=Button(vDoctorAgregado,text="Aceptar",command=lambda:limpiarEntryDoctores() or mostrar(vDoctores) or ocultar(vDoctorAgregado)) bAceptarDoctorAgregado.pack() vConfirmarEliminarDoctor=Toplevel(v0) vConfirmarEliminarDoctor.config(bg="lightblue") vConfirmarEliminarDoctor.title("Confirmar") vConfirmarEliminarDoctor.geometry("500x150") vConfirmarEliminarDoctor.withdraw() lConfirmarEliminarDoctor=Label(vConfirmarEliminarDoctor,font=('Cambria',14),bg="lightblue",text="Estas seguro que deseas eliminar toda la informacion de este Doctor?") lConfirmarEliminarDoctor.pack() bAceptarEliminarDoctor=Button(vConfirmarEliminarDoctor,text="Aceptar",command=lambda:eliminarDoctor() or ocultar(vConfirmarEliminarDoctor)) bAceptarEliminarDoctor.pack() bCancelarEliminarDoctor=Button(vConfirmarEliminarDoctor,text="Cancelar",command=lambda:mostrar(vDoctores) or ocultar(vConfirmarEliminarDoctor)) bCancelarEliminarDoctor.pack() vDoctorEliminado=Toplevel(v0) vDoctorEliminado.config(bg="lightblue") vDoctorEliminado.title("Doctor Eliminado") vDoctorEliminado.geometry("500x150") vDoctorEliminado.withdraw() lDoctorEliminado=Label(vDoctorEliminado,font=('Cambria',14),bg="lightblue",text="Doctor Eliminado Correctamente") lDoctorEliminado.pack() bAceptarDoctorEliminado=Button(vDoctorEliminado,text="Aceptar",command=lambda:mostrar(vDoctores) or ocultar(vDoctorEliminado)) bAceptarDoctorEliminado.pack() vDoctorEncontrado=Toplevel(v0) vDoctorEncontrado.config(bg="lightblue") vDoctorEncontrado.title("Doctor Encontrado") vDoctorEncontrado.geometry("500x150") vDoctorEncontrado.withdraw() lDoctorEncontrado=Label(vDoctorEncontrado,font=('Cambria',14),bg="lightblue",text="Doctor Encontrado") lDoctorEncontrado.pack() bDoctorEncontrado=Button(vDoctorEncontrado,text="Aceptar",command=lambda:mostrarInfoDoctor(DoctorTemporal) or limpiar(vsIdentificacionBuscarDoctor) or ocultar(vDoctorEncontrado)) bDoctorEncontrado.pack() vDoctorNoEncontrado=Toplevel(v0) vDoctorNoEncontrado.config(bg="lightblue") vDoctorNoEncontrado.title("No existe ningun Doctor con esa Identificacion") vDoctorNoEncontrado.geometry("500x150") vDoctorNoEncontrado.withdraw() lDoctorNoEncontrado=Label(vDoctorNoEncontrado,font=('Cambria',14),bg="lightblue",text="No existe ningun Doctor con esa Identificacion") lDoctorNoEncontrado.pack() bDoctorNoEncontrado=Button(vDoctorNoEncontrado,text="Aceptar",command=lambda:mostrar(vDoctores) or limpiar(vsIdentificacionBuscarDoctor) or ocultar(vDoctorNoEncontrado)) bDoctorNoEncontrado.pack() vVerInfoDoctor=Toplevel(v0) vVerInfoDoctor.config(bg="lightblue") vVerInfoDoctor.title("Informacion del Doctor") vVerInfoDoctor.geometry("500x500") vVerInfoDoctor.withdraw() bRegresarVerInfoDoctor=Button(vVerInfoDoctor,text="Regresar",command=lambda:olvidarGrids(listaObjetosInfoDoctor) or mostrar(vDoctores) or ocultar(vVerInfoDoctor)) bRegresarVerInfoDoctor.pack() bModificarInfoDoctor2=Button(vVerInfoDoctor,text="Modificar la Informacion",command=lambda:mostrarDatosDoctorModificar() or ocultar(vVerInfoDoctor)) bModificarInfoDoctor2.pack() bVerCitasDoctor=Button(vVerInfoDoctor,text="Ver Citas",command=lambda:mostrarCitasDoctor(DoctorTemporal) or ocultar(vVerInfoDoctor)) bVerCitasDoctor.pack() lVerInfoDoctor=Label(vVerInfoDoctor,font=('Cambria',14),bg="lightblue",text="Informacion del Doctor") lVerInfoDoctor.pack() vBuscarDoctor=Toplevel(v0) vBuscarDoctor.config(bg="lightblue") vBuscarDoctor.title("Buscar Doctor") vBuscarDoctor.geometry("500x500") vBuscarDoctor.withdraw() lBuscarDoctor=Label(vBuscarDoctor,font=('Cambria',14),bg="lightblue",text="Digite la identificacion del Doctor a buscar") lBuscarDoctor.pack() vsIdentificacionBuscarDoctor=StringVar() eBuscarDoctor=Entry(vBuscarDoctor,textvariable=vsIdentificacionBuscarDoctor,width=20) eBuscarDoctor.pack() bAceptarBuscarDoctor=Button(vBuscarDoctor,text="Aceptar",command=lambda:buscar_doctor(vsIdentificacionBuscarDoctor.get()) or ocultar(vBuscarDoctor)) bAceptarBuscarDoctor.pack() bRegresarBuscarDoctor=Button(vBuscarDoctor,text="Regresar",command=lambda:mostrar(vDoctores) or ocultar(vBuscarDoctor)) bRegresarBuscarDoctor.pack() vPacientes=Toplevel(v0) vPacientes.config(bg="lightblue") vPacientes.title("Pacientes") vPacientes.geometry("500x500") vPacientes.withdraw() ListBoxPacientes=Listbox(vPacientes) ListBoxPacientes.pack() bAgregarPaciente=Button(vPacientes,text="Agregar Nuevo Paciente",command=lambda:mostrar(vAgregarPaciente) or ocultar(vPacientes)) bAgregarPaciente.pack() bEliminarPaciente=Button(vPacientes,text="Eliminar Paciente",command=lambda:seleccionarPaciente(ListBoxPacientes.get(ListBoxPacientes.curselection()),ListBoxPacientes.curselection()) or mostrar(vConfirmarEliminarPaciente) or ocultar(vPacientes)) bEliminarPaciente.pack() bVerInfoPacientes=Button(vPacientes,text="Ver Informacion",command=lambda:mostrarInfoPaciente(ListBoxPacientes.get(ListBoxPacientes.curselection())) or ocultar(vPacientes) or seleccionarPaciente(ListBoxPacientes.get(ListBoxPacientes.curselection()),ListBoxPacientes.curselection())) bVerInfoPacientes.pack() bBuscarPaciente=Button(vPacientes,text="Buscar Paciente",command=lambda:mostrar(vBuscarPaciente) or ocultar(vPacientes)) bBuscarPaciente.pack() bInicioPacientes=Button(vPacientes,text="Volver al Inicio",command=lambda:mostrar(v0) or ocultar(vPacientes)) bInicioPacientes.pack() vAgregarPaciente=Toplevel(v0) vAgregarPaciente.config(bg="lightblue") vAgregarPaciente.title("Agregar nuevo Paciente") vAgregarPaciente.geometry("500x700") vAgregarPaciente.withdraw() lNombrePaciente=Label(vAgregarPaciente,font=('Cambria',14),bg="lightblue",text="Digite el nombre del Paciente") lNombrePaciente.pack() vsNombrePaciente=StringVar() eNombrePaciente=Entry(vAgregarPaciente,textvariable=vsNombrePaciente,width=20) eNombrePaciente.pack() lIdentificacionPaciente=Label(vAgregarPaciente,font=('Cambria',14),bg="lightblue",text="Digite el numero de Identificacion del Paciente") lIdentificacionPaciente.pack() vsIdentificacionPaciente=StringVar() eIdentificacionPaciente=Entry(vAgregarPaciente,textvariable=vsIdentificacionPaciente,width=20) eIdentificacionPaciente.pack() lCorreosPaciente=Label(vAgregarPaciente,font=('Cambria',14),bg="lightblue",text="Digite uno o mas correos del Paciente") lCorreosPaciente.pack() vsCorreoPaciente1=StringVar() eCorreoPaciente1=Entry(vAgregarPaciente,textvariable=vsCorreoPaciente1,width=20) eCorreoPaciente1.pack() vsCorreoPaciente2=StringVar() eCorreoPaciente2=Entry(vAgregarPaciente,textvariable=vsCorreoPaciente2,width=20) eCorreoPaciente2.pack() vsCorreoPaciente3=StringVar() eCorreoPaciente3=Entry(vAgregarPaciente,textvariable=vsCorreoPaciente3,width=20) eCorreoPaciente3.pack() lTelefonosPaciente=Label(vAgregarPaciente,font=('Cambria',14),bg="lightblue",text="Digite uno o mas telefonos del Paciente") lTelefonosPaciente.pack() vsTelefonoPaciente1=StringVar() eTelefonoPaciente1=Entry(vAgregarPaciente,textvariable=vsTelefonoPaciente1,width=20) eTelefonoPaciente1.pack() vsTelefonoPaciente2=StringVar() eTelefonoPaciente2=Entry(vAgregarPaciente,textvariable=vsTelefonoPaciente2,width=20) eTelefonoPaciente2.pack() vsTelefonoPaciente3=StringVar() eTelefonoPaciente3=Entry(vAgregarPaciente,textvariable=vsTelefonoPaciente3,width=20) eTelefonoPaciente3.pack() lfnacimientoPaciente=Label(vAgregarPaciente,font=('Cambria',14),bg="lightblue",text="Digite la fecha de nacimiento del Paciente") lfnacimientoPaciente.pack() vsfnacimientoPaciente=StringVar() efnacimientoPaciente=Entry(vAgregarPaciente,textvariable=vsfnacimientoPaciente,width=20) efnacimientoPaciente.pack() lDireccionPaciente=Label(vAgregarPaciente,font=('Cambria',14),bg="lightblue",text="Digite la direccion del Paciente") lDireccionPaciente.pack() vsDireccionPaciente=StringVar() eDireccionPaciente=Entry(vAgregarPaciente,textvariable=vsDireccionPaciente,width=20) eDireccionPaciente.pack() lOcupacionPaciente=Label(vAgregarPaciente,font=('Cambria',14),bg="lightblue",text="Digite la ocupacion del Paciente") lOcupacionPaciente.pack() vsOcupacionPaciente=StringVar() eOcupacionPaciente=Entry(vAgregarPaciente,textvariable=vsOcupacionPaciente,width=20) eOcupacionPaciente.pack() bAgregarPaciente=Button(vAgregarPaciente,text="Agregar",command=lambda:agregarPaciente(vsNombrePaciente.get(),vsIdentificacionPaciente.get(),vsCorreoPaciente1.get(),vsCorreoPaciente2.get(),vsCorreoPaciente3.get(),vsTelefonoPaciente1.get(),vsTelefonoPaciente2.get(),vsTelefonoPaciente3.get(),vsfnacimientoPaciente.get(),vsDireccionPaciente.get(),vsOcupacionPaciente.get(),listaPacientes) or ocultar(vAgregarPaciente)) bAgregarPaciente.pack() bVolverPacientes=Button(vAgregarPaciente,text="Volver a Informacion de Pacientes",command=lambda:mostrar(vPacientes) or ocultar(vAgregarPaciente)) bVolverPacientes.pack() vModificarPaciente=Toplevel(v0) vModificarPaciente.config(bg="lightblue") vModificarPaciente.title("Modificar Paciente") vModificarPaciente.geometry("500x700") vModificarPaciente.withdraw() lNombrePaciente2=Label(vModificarPaciente,font=('Cambria',14),bg="lightblue",text="Digite el nombre del Paciente") lNombrePaciente2.pack() vsNombrePaciente2=StringVar() eNombrePaciente2=Entry(vModificarPaciente,textvariable=vsNombrePaciente2,width=20) eNombrePaciente2.pack() lIdentificacionPaciente2=Label(vModificarPaciente,font=('Cambria',14),bg="lightblue",text="Digite el numero de Identificacion del Paciente") lIdentificacionPaciente2.pack() vsIdentificacionPaciente2=StringVar() eIdentificacionPaciente2=Entry(vModificarPaciente,textvariable=vsIdentificacionPaciente2,width=20) eIdentificacionPaciente2.pack() lCorreosPaciente2=Label(vModificarPaciente,font=('Cambria',14),bg="lightblue",text="Digite uno o mas correos del Paciente") lCorreosPaciente2.pack() vsCorreoPaciente1_2=StringVar() eCorreoPaciente1_2=Entry(vModificarPaciente,textvariable=vsCorreoPaciente1_2,width=20) eCorreoPaciente1_2.pack() vsCorreoPaciente2_2=StringVar() eCorreoPaciente2_2=Entry(vModificarPaciente,textvariable=vsCorreoPaciente2_2,width=20) eCorreoPaciente2_2.pack() vsCorreoPaciente3_2=StringVar() eCorreoPaciente3_2=Entry(vModificarPaciente,textvariable=vsCorreoPaciente3_2,width=20) eCorreoPaciente3_2.pack() lTelefonosPaciente_2=Label(vModificarPaciente,font=('Cambria',14),bg="lightblue",text="Digite uno o mas telefonos del Paciente") lTelefonosPaciente_2.pack() vsTelefonoPaciente1_2=StringVar() eTelefonoPaciente1_2=Entry(vModificarPaciente,textvariable=vsTelefonoPaciente1_2,width=20) eTelefonoPaciente1_2.pack() vsTelefonoPaciente2_2=StringVar() eTelefonoPaciente2_2=Entry(vModificarPaciente,textvariable=vsTelefonoPaciente2_2,width=20) eTelefonoPaciente2_2.pack() vsTelefonoPaciente3_2=StringVar() eTelefonoPaciente3_2=Entry(vModificarPaciente,textvariable=vsTelefonoPaciente3_2,width=20) eTelefonoPaciente3_2.pack() lfnacimientoPaciente2=Label(vModificarPaciente,font=('Cambria',14),bg="lightblue",text="Digite la fecha de nacimiento del Paciente") lfnacimientoPaciente2.pack() vsfnacimientoPaciente2=StringVar() efnacimientoPaciente2=Entry(vModificarPaciente,textvariable=vsfnacimientoPaciente2,width=20) efnacimientoPaciente2.pack() lDireccionPaciente2=Label(vModificarPaciente,font=('Cambria',14),bg="lightblue",text="Digite la direccion del Paciente") lDireccionPaciente2.pack() vsDireccionPaciente2=StringVar() eDireccionPaciente2=Entry(vModificarPaciente,textvariable=vsDireccionPaciente2,width=20) eDireccionPaciente2.pack() lOcupacionPaciente2=Label(vModificarPaciente,font=('Cambria',14),bg="lightblue",text="Digite la ocupacion del Paciente") lOcupacionPaciente2.pack() vsOcupacionPaciente2=StringVar() eOcupacionPaciente2=Entry(vModificarPaciente,textvariable=vsOcupacionPaciente2,width=20) eOcupacionPaciente2.pack() bGuardarCambiosPaciente=Button(vModificarPaciente,text="Guardar Cambios",command=lambda:modificarInfoPaciente(vsNombrePaciente2.get(),vsIdentificacionPaciente2.get(),vsCorreoPaciente1_2.get(),vsCorreoPaciente2_2.get(),vsCorreoPaciente3_2.get(),vsTelefonoPaciente1_2.get(),vsTelefonoPaciente2_2.get(),vsTelefonoPaciente3_2.get(),vsfnacimientoPaciente2.get(),vsDireccionPaciente2.get(),vsOcupacionPaciente2.get()) or ocultar(vModificarPaciente)) bGuardarCambiosPaciente.pack() bVolverPacientes2=Button(vModificarPaciente,text="Volver a Informacion de Pacientes",command=lambda:olvidarGrids(listaObjetosInfoPaciente) or mostrar(vPacientes) or ocultar(vModificarPaciente)) bVolverPacientes2.pack() vPacienteModificado=Toplevel(v0) vPacienteModificado.config(bg="lightblue") vPacienteModificado.title("Paciente Modificado") vPacienteModificado.geometry("500x150") vPacienteModificado.withdraw() lPacienteModificado=Label(vPacienteModificado,font=('Cambria',14),bg="lightblue",text="La informacion ha sido modificada") lPacienteModificado.pack() bPacienteModificado=Button(vPacienteModificado,text="Aceptar",command=lambda:olvidarGrids(listaObjetosInfoPaciente) or actualizarListboxPacientes() or ocultar(vPacienteModificado)) bPacienteModificado.pack() vFaltaInfoPaciente=Toplevel(v0) vFaltaInfoPaciente.config(bg="lightblue") vFaltaInfoPaciente.title("Falta Informacion") vFaltaInfoPaciente.geometry("500x150") vFaltaInfoPaciente.withdraw() lFaltaInfoPaciente=Label(vFaltaInfoPaciente,font=('Cambria',14),bg="lightblue",text="Complete todos los espacios") lFaltaInfoPaciente.pack() bAceptarFaltaInfoPaciente=Button(vFaltaInfoPaciente,text="Aceptar",command=lambda:mostrar(vAgregarPaciente) or ocultar(vFaltaInfoPaciente)) bAceptarFaltaInfoPaciente.pack() vFaltaInfoPaciente2=Toplevel(v0) vFaltaInfoPaciente2.config(bg="lightblue") vFaltaInfoPaciente2.title("Falta Informacion") vFaltaInfoPaciente2.geometry("500x150") vFaltaInfoPaciente2.withdraw() lFaltaInfoPaciente2=Label(vFaltaInfoPaciente2,font=('Cambria',14),bg="lightblue",text="Complete todos los espacios") lFaltaInfoPaciente2.pack() bAceptarFaltaInfoPaciente2=Button(vFaltaInfoPaciente,text="Aceptar",command=lambda:mostrar(vModificarPaciente) or ocultar(vFaltaInfoPaciente2)) bAceptarFaltaInfoPaciente2.pack() vPacienteRepetido=Toplevel(v0) vPacienteRepetido.config(bg="lightblue") vPacienteRepetido.title("Paciente existente") vPacienteRepetido.geometry("500x150") vPacienteRepetido.withdraw() lPacienteRepetido=Label(vPacienteRepetido,font=('Cambria',14),bg="lightblue",text="Ya existe un Paciente con esta identificacion") lPacienteRepetido.pack() bPacienteRepetido=Button(vPacienteRepetido,text="Aceptar",command=lambda:mostrar(vAgregarPaciente) or ocultar(vPacienteRepetido)) bPacienteRepetido.pack() vNombrePacienteRepetido=Toplevel(v0) vNombrePacienteRepetido.config(bg="lightblue") vNombrePacienteRepetido.title("Paciente existente") vNombrePacienteRepetido.geometry("500x150") vNombrePacienteRepetido.withdraw() lNombrePacienteRepetido=Label(vNombrePacienteRepetido,font=('Cambria',14),bg="lightblue",text="Ya existe un Paciente con este nombre") lNombrePacienteRepetido.pack() bNombrePacienteRepetido=Button(vNombrePacienteRepetido,text="Aceptar",command=lambda:mostrar(vAgregarPaciente) or ocultar(vNombrePacienteRepetido)) bNombrePacienteRepetido.pack() vNombrePacienteRepetido2=Toplevel(v0) vNombrePacienteRepetido2.config(bg="lightblue") vNombrePacienteRepetido2.title("Paciente existente") vNombrePacienteRepetido2.geometry("500x150") vNombrePacienteRepetido2.withdraw() lNombrePacienteRepetido2=Label(vNombrePacienteRepetido2,font=('Cambria',14),bg="lightblue",text="Ya existe un Paciente con este nombre") lNombrePacienteRepetido2.pack() bNombrePacienteRepetido2=Button(vNombrePacienteRepetido2,text="Aceptar",command=lambda:mostrar(vModificarPaciente) or ocultar(vNombrePacienteRepetido2)) bNombrePacienteRepetido2.pack() vPacienteRepetido2=Toplevel(v0) vPacienteRepetido2.config(bg="lightblue") vPacienteRepetido2.title("Paciente existente") vPacienteRepetido2.geometry("500x150") vPacienteRepetido2.withdraw() lPacienteRepetido2=Label(vPacienteRepetido2,font=('Cambria',14),bg="lightblue",text="Ya existe un Paciente con esta identificacion") lPacienteRepetido2.pack() bPacienteRepetido2=Button(vPacienteRepetido2,text="Aceptar",command=lambda:mostrar(vModificarPaciente) or ocultar(vPacienteRepetido2)) bPacienteRepetido2.pack() vInfoPacienteRepetida=Toplevel(v0) vInfoPacienteRepetida.config(bg="lightblue") vInfoPacienteRepetida.title("Informacion Repetida") vInfoPacienteRepetida.geometry("500x150") vInfoPacienteRepetida.withdraw() lInfoPacienteRepetida=Label(vInfoPacienteRepetida,font=('Cambria',14),bg="lightblue",text="Ha digitado informacion repetida") lInfoPacienteRepetida.pack() bInfoPacienteRepetida=Button(vInfoPacienteRepetida,text="Aceptar",command=lambda:mostrar(vAgregarPaciente) or ocultar(vInfoPacienteRepetida)) bInfoPacienteRepetida.pack() vInfoPacienteRepetida2=Toplevel(v0) vInfoPacienteRepetida2.config(bg="lightblue") vInfoPacienteRepetida2.title("Informacion Repetida") vInfoPacienteRepetida2.geometry("500x150") vInfoPacienteRepetida2.withdraw() lInfoPacienteRepetida2=Label(vInfoPacienteRepetida2,font=('Cambria',14),bg="lightblue",text="Ha digitado informacion repetida") lInfoPacienteRepetida2.pack() bInfoPacienteRepetida2=Button(vInfoPacienteRepetida2,text="Aceptar",command=lambda:mostrar(vModificarPaciente) or ocultar(vInfoPacienteRepetida2)) bInfoPacienteRepetida2.pack() vPacienteAgregado=Toplevel(v0) vPacienteAgregado.config(bg="lightblue") vPacienteAgregado.title("Paciente Agregado") vPacienteAgregado.geometry("500x150") vPacienteAgregado.withdraw() lPacienteAgregado=Label(vPacienteAgregado,font=('Cambria',14),bg="lightblue",text="Paciente Agregado Exitosamente!") lPacienteAgregado.pack() bAceptarPacienteAgregado=Button(vPacienteAgregado,text="Aceptar",command=lambda:limpiarEntryPacientes() or mostrar(vPacientes) or ocultar(vPacienteAgregado)) bAceptarPacienteAgregado.pack() vConfirmarEliminarPaciente=Toplevel(v0) vConfirmarEliminarPaciente.config(bg="lightblue") vConfirmarEliminarPaciente.title("Confirmar") vConfirmarEliminarPaciente.geometry("500x150") vConfirmarEliminarPaciente.withdraw() lConfirmarEliminarPaciente=Label(vConfirmarEliminarPaciente,font=('Cambria',14),bg="lightblue",text="Estas seguro que deseas eliminar toda la informacion de este Paciente?") lConfirmarEliminarPaciente.pack() bAceptarEliminarPaciente=Button(vConfirmarEliminarPaciente,text="Aceptar",command=lambda:eliminarPaciente() or ocultar(vConfirmarEliminarPaciente)) bAceptarEliminarPaciente.pack() bCancelarEliminarPaciente=Button(vConfirmarEliminarPaciente,text="Cancelar",command=lambda:mostrar(vPacientes) or ocultar(vConfirmarEliminarPaciente)) bCancelarEliminarPaciente.pack() vPacienteEliminado=Toplevel(v0) vPacienteEliminado.config(bg="lightblue") vPacienteEliminado.title("Paciente Eliminado") vPacienteEliminado.geometry("500x150") vPacienteEliminado.withdraw() lPacienteEliminado=Label(vPacienteEliminado,font=('Cambria',14),bg="lightblue",text="Paciente Eliminado Correctamente") lPacienteEliminado.pack() bAceptarPacienteEliminado=Button(vPacienteEliminado,text="Aceptar",command=lambda:mostrar(vPacientes) or ocultar(vPacienteEliminado)) bAceptarPacienteEliminado.pack() vPacienteEncontrado=Toplevel(v0) vPacienteEncontrado.config(bg="lightblue") vPacienteEncontrado.title("Paciente Encontrado") vPacienteEncontrado.geometry("500x150") vPacienteEncontrado.withdraw() lPacienteEncontrado=Label(vPacienteEncontrado,font=('Cambria',14),bg="lightblue",text="Paciente Encontrado") lPacienteEncontrado.pack() bPacienteEncontrado=Button(vPacienteEncontrado,text="Aceptar",command=lambda:mostrarInfoPaciente(PacienteTemporal) or limpiar(vsIdentificacionBuscarPaciente) or ocultar(vPacienteEncontrado)) bPacienteEncontrado.pack() vPacienteNoEncontrado=Toplevel(v0) vPacienteNoEncontrado.config(bg="lightblue") vPacienteNoEncontrado.title("No existe ningun Paciente con esa Identificacion") vPacienteNoEncontrado.geometry("500x150") vPacienteNoEncontrado.withdraw() lPacienteNoEncontrado=Label(vPacienteNoEncontrado,font=('Cambria',14),bg="lightblue",text="No existe ningun Paciente con esa Identificacion") lPacienteNoEncontrado.pack() bPacienteNoEncontrado=Button(vPacienteNoEncontrado,text="Aceptar",command=lambda:mostrar(vPacientes) or limpiar(vsIdentificacionBuscarPaciente) or ocultar(vPacienteNoEncontrado)) bPacienteNoEncontrado.pack() vVerInfoPaciente=Toplevel(v0) vVerInfoPaciente.config(bg="lightblue") vVerInfoPaciente.title("Informacion del Paciente") vVerInfoPaciente.geometry("500x500") vVerInfoPaciente.withdraw() bRegresarVerInfoPaciente=Button(vVerInfoPaciente,text="Regresar",command=lambda:olvidarGrids(listaObjetosInfoPaciente) or mostrar(vPacientes) or ocultar(vVerInfoPaciente)) bRegresarVerInfoPaciente.pack() bModificarInfoPaciente2=Button(vVerInfoPaciente,text="Modificar la Informacion",command=lambda:mostrarDatosPacienteModificar() or ocultar(vVerInfoPaciente)) bModificarInfoPaciente2.pack() bVerListaTratamientos=Button(vVerInfoPaciente,text="Ver tratamientos",command=lambda:mostrarTratamientos() or ocultar(vVerInfoPaciente)) bVerListaTratamientos.pack() bVerCitas=Button(vVerInfoPaciente,text="Ver Citas",command=lambda:mostrarCitasPaciente(PacienteTemporal) or ocultar(vVerInfoPaciente)) bVerCitas.pack() lVerInfoPaciente=Label(vVerInfoPaciente,font=('Cambria',14),bg="lightblue",text="Informacion del Paciente") lVerInfoPaciente.pack() vBuscarPaciente=Toplevel(v0) vBuscarPaciente.config(bg="lightblue") vBuscarPaciente.title("Buscar Paciente") vBuscarPaciente.geometry("500x500") vBuscarPaciente.withdraw() lBuscarPaciente=Label(vBuscarPaciente,font=('Cambria',14),bg="lightblue",text="Digite la identificacion del Paciente a buscar") lBuscarPaciente.pack() vsIdentificacionBuscarPaciente=StringVar() eBuscarPaciente=Entry(vBuscarPaciente,textvariable=vsIdentificacionBuscarPaciente,width=20) eBuscarPaciente.pack() bAceptarBuscarPaciente=Button(vBuscarPaciente,text="Aceptar",command=lambda:buscar_paciente(vsIdentificacionBuscarPaciente.get()) or ocultar(vBuscarPaciente)) bAceptarBuscarPaciente.pack() bRegresarBuscarPaciente=Button(vBuscarPaciente,text="Regresar",command=lambda:mostrar(vPacientes) or ocultar(vBuscarPaciente)) bRegresarBuscarPaciente.pack() vOpcionCitas=Toplevel(v0) vOpcionCitas.config(bg="lightblue") vOpcionCitas.title("Citas") vOpcionCitas.geometry("500x500") vOpcionCitas.withdraw() bAgregarCita=Button(vOpcionCitas,text="Agregar Una Nueva Cita",command=lambda:mostrar(vAgregarCita) or ocultar(vOpcionCitas)) bAgregarCita.pack() bCitasPorDia=Button(vOpcionCitas,text="Mostrar Citas por Dia",command=lambda:mostrar(vCitasPorDia) or ocultar(vOpcionCitas)) bCitasPorDia.pack() bCitasPendientes=Button(vOpcionCitas,text="Mostrar Todas las citas pendientes",command=lambda:mostrarCitasPendientes() or ocultar(vOpcionCitas)) bCitasPendientes.pack() bCitasRealizadas=Button(vOpcionCitas,text="Mostrar Todas las citas realizadas",command=lambda:mostrarCitasRealizadas() or ocultar(vOpcionCitas)) bCitasRealizadas.pack() bVolverInicioCitas=Button(vOpcionCitas,text="Volver al Inicio",command=lambda:mostrar(v0) or ocultar(vOpcionCitas)) bVolverInicioCitas.pack() vAgregarCita=Toplevel(v0) vAgregarCita.config(bg="lightblue") vAgregarCita.title("Agregar Cita") vAgregarCita.geometry("500x500") vAgregarCita.withdraw() lSeleccioneDoctor=Label(vAgregarCita,text="Seleccion un Doctor",font=('Cambria',14),bg="lightblue") lSeleccioneDoctor.pack() ListBoxDoctores2=Listbox(vAgregarCita) ListBoxDoctores2.pack() bSeleccionarDoctorCita=Button(vAgregarCita,text="Seleccionar",command=lambda:seleccionarDoctor(ListBoxDoctores2.get(ListBoxDoctores2.curselection()),ListBoxDoctores2.curselection()) or mostrar(vAgregarCita2) or ocultar(vAgregarCita)) bSeleccionarDoctorCita.pack() bVolverInfoCitas1=Button(vAgregarCita,text="Volver a Citas",command=lambda:mostrar(vOpcionCitas) or ocultar(vAgregarCita)) bVolverInfoCitas1.pack() vAgregarCita2=Toplevel(v0) vAgregarCita2.config(bg="lightblue") vAgregarCita2.title("Agregar Cita") vAgregarCita2.geometry("500x500") vAgregarCita2.withdraw() lSeleccionePaciente=Label(vAgregarCita2,text="Seleccion un Paciente",font=('Cambria',14),bg="lightblue") lSeleccionePaciente.pack() ListBoxPacientes2=Listbox(vAgregarCita2) ListBoxPacientes2.pack() bSeleccionarPacienteCita=Button(vAgregarCita2,text="Seleccionar",command=lambda:seleccionarPaciente(ListBoxPacientes2.get(ListBoxPacientes2.curselection()),ListBoxPacientes2.curselection()) or mostrar(vAgregarCita3) or ocultar(vAgregarCita2)) bSeleccionarPacienteCita.pack() bVolverInfoCitas2=Button(vAgregarCita2,text="Volver a Citas",command=lambda:mostrar(vOpcionCitas) or ocultar(vAgregarCita2)) bVolverInfoCitas2.pack() vAgregarCita3=Toplevel(v0) vAgregarCita3.config(bg="lightblue") vAgregarCita3.title("Agregar Cita") vAgregarCita3.geometry("500x500") vAgregarCita3.withdraw() lDigiteFecha=Label(vAgregarCita3,text="Digite la fecha (dd/mm/aaaa)",font=('Cambria',14),bg="lightblue") lDigiteFecha.pack() vsFechaCita=StringVar() eFechaCita=Entry(vAgregarCita3,textvariable=vsFechaCita,width=20) eFechaCita.pack() lDigiteHora=Label(vAgregarCita3,text="Digite la Hora",font=('Cambria',14),bg="lightblue") lDigiteHora.pack() vsHoraCita=StringVar() eHoraCita=Entry(vAgregarCita3,textvariable=vsHoraCita,width=20) eHoraCita.pack() bAgregarCita=Button(vAgregarCita3,text="Agregar Cita",command=lambda:agregarCita(vsFechaCita.get(),vsHoraCita.get(),PacienteTemporal,DoctorTemporal,listaCitas) or ocultar(vAgregarCita3)) bAgregarCita.pack() bVolverInfoCitas3=Button(vAgregarCita3,text="Volver a Citas",command=lambda:mostrar(vOpcionCitas) or ocultar(vAgregarCita3) or limpiarEntryCitas()) bVolverInfoCitas3.pack() vFaltaInfoCita=Toplevel(v0) vFaltaInfoCita.config(bg="lightblue") vFaltaInfoCita.title("Complete Todos los Espacios") vFaltaInfoCita.geometry("500x300") vFaltaInfoCita.withdraw() lFaltaInfoCita=Label(vFaltaInfoCita,text="Complete Todos los Espacios!",font=('Cambria',14),bg="lightblue") lFaltaInfoCita.pack() bAceptarFaltaInfoCita=Button(vFaltaInfoCita,text="Aceptar",command=lambda:mostrar(vAgregarCita3) or ocultar(vFaltaInfoCita)) bAceptarFaltaInfoCita.pack() vDoctorOcupado=Toplevel(v0) vDoctorOcupado.config(bg="lightblue") vDoctorOcupado.title("Doctor Ocupado") vDoctorOcupado.geometry("500x300") vDoctorOcupado.withdraw() lDoctorOcupado=Label(vDoctorOcupado,text="El Doctor Seleccionado ya tiene una cita en esa Fecha y Hora",font=('Cambria',14),bg="lightblue") lDoctorOcupado.pack() bAceptarDoctorOcupado=Button(vDoctorOcupado,text="Aceptar",command=lambda:mostrar(vOpcionCitas) or ocultar(vDoctorOcupado)) bAceptarDoctorOcupado.pack() vPacienteOcupado=Toplevel(v0) vPacienteOcupado.config(bg="lightblue") vPacienteOcupado.title("Paciente Ocupado") vPacienteOcupado.geometry("500x300") vPacienteOcupado.withdraw() lPacienteOcupado=Label(vPacienteOcupado,text="El Paciente Seleccionado ya tiene una cita en esa Fecha y Hora",font=('Cambria',14),bg="lightblue") lPacienteOcupado.pack() bAceptarPacienteOcupado=Button(vPacienteOcupado,text="Aceptar",command=lambda:mostrar(vOpcionCitas) or ocultar(vPacienteOcupado)) bAceptarPacienteOcupado.pack() vCitaAgregada=Toplevel(v0) vCitaAgregada.config(bg="lightblue") vCitaAgregada.title("Cita Agregada") vCitaAgregada.geometry("500x300") vCitaAgregada.withdraw() lCitaAgregada=Label(vCitaAgregada,text="La cita ha sido agregada!",font=('Cambria',14),bg="lightblue") lCitaAgregada.pack() bAceptarCitaAgregada=Button(vCitaAgregada,text="Aceptar",command=lambda:mostrar(vOpcionCitas) or ocultar(vCitaAgregada)) bAceptarCitaAgregada.pack() vCitasPorDia=Toplevel(v0) vCitasPorDia.config(bg="lightblue") vCitasPorDia.title("Seleccione Fecha") vCitasPorDia.geometry("500x500") vCitasPorDia.withdraw() lSeleccioneFecha=Label(vCitasPorDia,text="Seleccione una fecha",font=('Cambria',14),bg="lightblue") lSeleccioneFecha.pack() ListBoxFechas=Listbox(vCitasPorDia) ListBoxFechas.pack() bSeleccionarFechaCita=Button(vCitasPorDia,text="Seleccionar",command=lambda:mostrarCitasPorDia(ListBoxFechas.get(ListBoxFechas.curselection()))or ocultar(vCitasPorDia)) bSeleccionarFechaCita.pack() bVolverInfoCitas4=Button(vCitasPorDia,text="Volver a Citas",command=lambda:mostrar(vOpcionCitas) or ocultar(vCitasPorDia)) bVolverInfoCitas4.pack() vCitas=Toplevel(v0) vCitas.config(bg="lightblue") vCitas.title("Citas") vCitas.geometry("500x500") vCitas.withdraw() bVolverInfoCitas5=Button(vCitas,text="Volver Informacion de Citas",command=lambda:mostrar(vOpcionCitas) or ocultar(vCitas) or olvidarObjetos(listaObjetosInfoCita) or olvidarGrids(listaObjetosInfoPaciente) or olvidarGrids(listaObjetosInfoDoctor)) bVolverInfoCitas5.grid() vConfirmarCambiarEstadoCita=Toplevel(v0) vConfirmarCambiarEstadoCita.config(bg="lightblue") vConfirmarCambiarEstadoCita.title("Cambiar Estado") vConfirmarCambiarEstadoCita.geometry("450x300") vConfirmarCambiarEstadoCita.withdraw() lConfirmarCambiarEstadoCita=Label(vConfirmarCambiarEstadoCita,text="Desea cambiar del estado de la cita a realizada?",font=('Cambria',14),bg="lightblue") lConfirmarCambiarEstadoCita.pack() bConfirmarCambiarEstadoCita=Button(vConfirmarCambiarEstadoCita,text="Si",command=lambda:CambiarEstadoCita() or ocultar(vConfirmarCambiarEstadoCita) or olvidarObjetos(listaObjetosInfoCita)) bConfirmarCambiarEstadoCita.pack() bConfirmarCambiarEstadoCita2=Button(vConfirmarCambiarEstadoCita,text="No",command=lambda:mostrar(vCitas) or ocultar(vConfirmarCambiarEstadoCita)) bConfirmarCambiarEstadoCita2.pack() vDeseaAsignarTratamiento=Toplevel(v0) vDeseaAsignarTratamiento.config(bg="lightblue") vDeseaAsignarTratamiento.title("Ingresar Tratamiento") vDeseaAsignarTratamiento.geometry("450x300") vDeseaAsignarTratamiento.withdraw() lDeseaIngresarTratamiento=Label(vDeseaAsignarTratamiento,text="Desea Ingresarle un tratamiento al paciente?",font=('Cambria',14),bg="lightblue") lDeseaIngresarTratamiento.pack() bDeseaIngresarTratamiento=Button(vDeseaAsignarTratamiento,text="Si",command=lambda:mostrar(vAsignarTratamiento) or ocultar(vDeseaAsignarTratamiento)) bDeseaIngresarTratamiento.pack() bDeseaIngresarTratamiento2=Button(vDeseaAsignarTratamiento,text="No",command=lambda:mostrar(vOpcionCitas) or ocultar(vDeseaAsignarTratamiento)) bDeseaIngresarTratamiento2.pack() vAsignarTratamiento=Toplevel(v0) vAsignarTratamiento.config(bg="lightblue") vAsignarTratamiento.title("Asignar Tratamiento") vAsignarTratamiento.geometry("500x500") vAsignarTratamiento.withdraw() lAsignarDescripcionTratamiento=Label(vAsignarTratamiento,text="Digite la descripcion del tratamiento",font=('Cambria',14),bg="lightblue") lAsignarDescripcionTratamiento.pack() vsDescripcionTratamiento=StringVar() eDescripcionTratamiento=Entry(vAsignarTratamiento,textvariable=vsDescripcionTratamiento,width=20) eDescripcionTratamiento.pack() bAceptarAsignarTratamiento=Button(vAsignarTratamiento,text="Aceptar",command=lambda:asignarTratamiento(vsDescripcionTratamiento.get()) or ocultar(vAsignarTratamiento) or limpiarEntry(vsDescripcionTratamiento)) bAceptarAsignarTratamiento.pack() vTratamientoAsignado=Toplevel(v0) vTratamientoAsignado.config(bg="lightblue") vTratamientoAsignado.title("Ingresar Tratamiento") vTratamientoAsignado.geometry("500x300") vTratamientoAsignado.withdraw() lTratamientoAsignado=Label(vTratamientoAsignado,text="El Tratamiento ha sido Asignado",font=('Cambria',14),bg="lightblue") lTratamientoAsignado.pack() bTratamientoAsignado=Button(vTratamientoAsignado,text="Aceptar",command=lambda:mostrar(vOpcionCitas) or ocultar(vTratamientoAsignado)) bTratamientoAsignado.pack() vFaltaInfoDescripcion=Toplevel(v0) vFaltaInfoDescripcion.config(bg="lightblue") vFaltaInfoDescripcion.title("Falta Info") vFaltaInfoDescripcion.geometry("500x300") vFaltaInfoDescripcion.withdraw() lFaltaInfoDescripcion=Label(vFaltaInfoDescripcion,text="Falta Informacion",font=('Cambria',14),bg="lightblue") lFaltaInfoDescripcion.pack() bFaltaInfoDescripcion=Button(vFaltaInfoDescripcion,text="Aceptar",command=lambda:mostrar(vAsignarTratamiento) or ocultar(vFaltaInfoDescripcion)) bFaltaInfoDescripcion.pack() vModificarCita=Toplevel(v0) vModificarCita.config(bg="lightblue") vModificarCita.title("Modificar Cita") vModificarCita.geometry("500x500") vModificarCita.withdraw() lModificarFechaCita=Label(vModificarCita,text="Digite la fecha (dd/mm/aaaa)",font=('Cambria',14),bg="lightblue") lModificarFechaCita.pack() vsFechaCita2=StringVar() eFechaCita2=Entry(vModificarCita,textvariable=vsFechaCita2) eFechaCita2.pack() lModificarHoraCita=Label(vModificarCita,text="Digite la Hora",font=('Cambria',14),bg="lightblue") lModificarHoraCita.pack() vsHoraCita2=StringVar() eHoraCita2=Entry(vModificarCita,textvariable=vsHoraCita2) eHoraCita2.pack() bGuardarCambiosCita=Button(vModificarCita,text="Guardar Cambios",command=lambda:modificarCita(vsFechaCita2.get(),vsHoraCita2.get()) or ocultar(vModificarCita)) bGuardarCambiosCita.pack() vDoctorOcupado2=Toplevel(v0) vDoctorOcupado2.config(bg="lightblue") vDoctorOcupado2.title("Doctor Ocupado") vDoctorOcupado2.geometry("500x300") vDoctorOcupado2.withdraw() lDoctorOcupado2=Label(vDoctorOcupado2,text="El Doctor Seleccionado ya tiene una cita en esa Fecha y Hora",font=('Cambria',14),bg="lightblue") lDoctorOcupado2.pack() bAceptarDoctorOcupado2=Button(vDoctorOcupado2,text="Aceptar",command=lambda:mostrar(vModificarCita) or ocultar(vDoctorOcupado2)) bAceptarDoctorOcupado2.pack() vPacienteOcupado2=Toplevel(v0) vPacienteOcupado2.config(bg="lightblue") vPacienteOcupado2.title("Paciente Ocupado") vPacienteOcupado2.geometry("500x300") vPacienteOcupado2.withdraw() lPacienteOcupado2=Label(vPacienteOcupado2,text="El Paciente Seleccionado ya tiene una cita en esa Fecha y Hora",font=('Cambria',14),bg="lightblue") lPacienteOcupado2.pack() bAceptarPacienteOcupado2=Button(vPacienteOcupado2,text="Aceptar",command=lambda:mostrar(vModificarCita) or ocultar(vPacienteOcupado2)) bAceptarPacienteOcupado2.pack() vFaltaInfoCita2=Toplevel(v0) vFaltaInfoCita2.config(bg="lightblue") vFaltaInfoCita2.title("Complete Todos los Espacios") vFaltaInfoCita2.geometry("500x300") vFaltaInfoCita2.withdraw() lFaltaInfoCita2=Label(vFaltaInfoCita2,text="Complete Todos los Espacios!",font=('Cambria',14),bg="lightblue") lFaltaInfoCita2.pack() bAceptarFaltaInfoCita2=Button(vFaltaInfoCita2,text="Aceptar",command=lambda:mostrar(vModificarCita) or ocultar(vFaltaInfoCita2)) bAceptarFaltaInfoCita2.pack() vCitaModificada=Toplevel(v0) vCitaModificada.config(bg="lightblue") vCitaModificada.title("Cita Modificada") vCitaModificada.geometry("500x300") vCitaModificada.withdraw() lCitaModificada=Label(vCitaModificada,text="La Cita ha sido Modificada",font=('Cambria',14),bg="lightblue") lCitaModificada.pack() bCitaModificada=Button(vCitaModificada,text="Aceptar",command=lambda:mostrar(vOpcionCitas) or ocultar(vCitaModificada) or olvidarObjetos(listaObjetosInfoCita)) bCitaModificada.pack() vCitaEliminada=Toplevel(v0) vCitaEliminada.config(bg="lightblue") vCitaEliminada.title("Cita Eliminada") vCitaEliminada.geometry("500x300") vCitaEliminada.withdraw() lCitaEliminada=Label(vCitaEliminada,text="La Cita ha sido Eliminada",font=('Cambria',14),bg="lightblue") lCitaEliminada.pack() bCitaEliminada=Button(vCitaEliminada,text="Aceptar",command=lambda:mostrar(v0) or ocultar(vCitaEliminada) or olvidarObjetos(listaObjetosInfoCita)) bCitaEliminada.pack() vVerTratamientos=Toplevel(v0) vVerTratamientos.config(bg="lightblue") vVerTratamientos.title("Ver Tratamientos") vVerTratamientos.geometry("500x500") vVerTratamientos.withdraw() bVerTratamientos=Button(vVerTratamientos,text="Volver",command=lambda:mostrar(vPacientes) or ocultar(vVerTratamientos)) bVerTratamientos.grid() vTratamientoCancelado=Toplevel(v0) vTratamientoCancelado.config(bg="lightblue") vTratamientoCancelado.title("Tratamiento Cancelado") vTratamientoCancelado.geometry("500x300") vTratamientoCancelado.withdraw() lLabel=Label(vTratamientoCancelado,text="El tratamiento ha sido cancelado",font=('Cambria',14),bg="lightblue") lLabel.pack() bTratamientoCancelado=Button(vTratamientoCancelado,text="Aceptar",command=lambda:mostrar(vPacientes) or ocultar(vTratamientoCancelado) or olvidarObjetos(listaObjetosInfoTratamientos) or olvidarGrids(listaObjetosInfoPaciente)) bTratamientoCancelado.pack() cargarArchivoDoctores() mostrarDoctores() cargarArchivoPacientes() mostrarPacientes() cargarArchivoCitas() mostrarFechas() v0.mainloop()
#Jumlah Rata-Rata Orang Bertemu Pasien Covid-19 R = int(input('Masukan Jumlah Rata-Rata Orang Bertemu Pasien Covid-19 : ')) #Peluang Tertular P = float(input('Masukan Peluang Tertular (ex 0.1, 0.01, 0.5 dst) : ')) #Jumlah Kasus Perhari Nh = int(input('Masukan Jumlah Kasus Perhari : ')) #Hari ke x x = int(input('Hari ke : ')) #rumus menggunakan persamaan eksponen pangkat = (1 + R * P)**x Nx = int(pangkat*Nh) print('') print('Hari ke -',x) print('Jumlah Kasus Perhari :',Nh) print('Peluang Tertular : ',P) print('Jumlah Rata-Rata Orang Bertemu Pasien Covid-19 : ',R) print('--------------------------------------------------------') print('HASIL -> Jumlah Pasien Di Hari Ke - ',x,' : ',Nx, 'orang') print('--------------------------------------------------------')
# ! /usr/bin/env python from thor.tree import TreeNode class Solution(object): ''' 1. 都为空指针返回True 2. 只有一个为空返回False 3. 递归过程 a. 判断两个指针是否相等 b. 判断A左子树和B右子树是否对称 c. 判断A右子树和B左子树是否对称 ''' def is_symmetric(self, root: TreeNode): if not root: return True else: self.func(root.left, root.right) def func(self, p: TreeNode, q: TreeNode): if not p and not q: return True elif p and q and p.val == q.val: return self.func(p.left, q.right) and self.func(p.right, q.left) else: return False
#! /usr/bin/env python ''' 1. 变化前和变化的位数是一样的 1.1 加完后,值不小于10,需要做进位 1.1.1 进位后,首位数字不小于10,位数将增加1 1.1.2 进位后,首位数字小于10 1.2 加完后,值小于10 ''' class Solution(object): def plusOne(self, digits: [int]) -> [int]: ''' 字符串和数值之间的转化 :param digits: :return: ''' if not digits: return digits else: return [int(x) for x in str(int(''.join(str(i) for i in digits)) + 1)] def plusOneExtend(self, digits: [int]) -> [int]: ''' 进位计算 :param digits: :return: ''' i = len(digits) - 1 while i >= 0: digits[i] = digits[i] + 1 digits[i] = digits[i] % 10 if digits[i] != 0: return digits i = i - 1 return [1] + digits if __name__ == '__main__': s = Solution() print(s.plusOne([1, 2, 3])) print(s.plusOne([9])) print(s.plusOneExtend([1, 2, 3])) print(s.plusOneExtend([9]))
# coding:utf-8 from thor.linklist.ListNode import ListNode class Solution(object): """双指针+哑结点""" def rotateRight1(self, head: ListNode, k: int) -> ListNode: if head is None or head.next is None or k == 0: return head else: dummy = ListNode(-1) dummy.next = head first = dummy second = dummy length = 0 """移动至尾部结点""" while first.next: first = first.next length += 1 """转化为单圈""" k %= length for i in range(length - k): second = second.next """执行旋转操作""" first.next = dummy.next dummy.next = second.next second.next = None return dummy.next """单指针""" def rotateRight(self, head: ListNode, k: int) -> ListNode: if not head or not head.next or k == 0: return head else: p = head length = 1 while p.next: p = p.next length += 1 k %= length """成环""" p.next = head for i in range(length - k): p = p.next head = p.next p.next = None return head def main(): s = Solution() l1 = ListNode(1).append(2).append(3).append(4).append(5) s.rotateRight(l1, 2).travel() l2 = ListNode(0).append(1).append(2) s.rotateRight(l2, 4).travel() if __name__ == '__main__': main()
#! /usr/bin/env python ''' 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。 ''' class Solution(object): def twoSum(self, numbers: [int], target: int) -> [int]: ''' 使用双指针,一个指针指向值较小的元素,一个指针指向值较大的元素。指向较小元素的指针从头向尾遍历,指向较大元素的指针从尾向头遍历。 1. 如果两个指针指向元素的和 sum == targetsum==target,那么得到要求的结果; 2. 如果 sum > targetsum>target,移动较大的元素,使 sumsum 变小一些; 3. 如果 sum < targetsum<target,移动较小的元素,使 sumsum 变大一些。 数组中的元素最多遍历一次,时间复杂度为 O(N)O(N)。只使用了两个额外变量,空间复杂度为 O(1)O(1)。 :param numbers: :param target: :return: ''' result = [] if not numbers: return result slow, fast = 0, len(numbers) - 1 while slow < fast: if numbers[slow] == target - numbers[fast]: return [slow + 1, fast + 1] elif numbers[slow] < target - numbers[fast]: slow = slow + 1 else: fast = fast - 1 return result if __name__ == '__main__': s = Solution() print(s.twoSum([2, 7, 11, 25], 9)) print(s.twoSum([2, 6, 7], 9)) print(s.twoSum([2, 3, 4], 6)) print(s.twoSum([-1, 0], -1))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """二叉树的类实现,以及遍历等各种方法""" # 结点类 class BinTreeNode(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left # 左子树 self.right = right # 右子树 # 统计树中结点的个数 def count_bintree_nodes(node: BinTreeNode): # 递归实现 if node is None: return 0 return 1+count_bintree_nodes(node.left)+count_bintree_nodes(node.right) # 计算树中结点的数据和 def sum_tree_nodes(node: BinTreeNode): # 递归实现 if node is None: return 0 else: return node.val + sum_tree_nodes(node.left) + sum_tree_nodes(node.right) # 遍历算法 # 递归实现——前序遍历 def preorder_dfs_rec(root:BinTreeNode, proc=print): if root is None: return cur_node = root proc(cur_node.val) if root.left is not None: preorder_dfs_rec(cur_node.left) if root.right is not None: preorder_dfs_rec(cur_node.right) # 非递归实现——前序遍历 def preorder_dfs(root: BinTreeNode, proc=print): cur_node = root stack = list() # 用栈来实现 while cur_node is not None or stack: # 栈不为空 # 先处理左子树,直到左结点处理结束 while cur_node is not None: proc(cur_node.val) # 先处理父结点 stack.append(cur_node) cur_node = cur_node.left if stack: # 此时栈顶结点是处理过的父结点 cur_node = stack.pop() cur_node = cur_node.right # 当前结点设置为右子结点 # 递归实现——中序遍历 def midorder_dfs_rec(root:BinTreeNode, proc=print): if root is None: return # 先处理左子树 if root.left: midorder_dfs_rec(root.left) # 处理根结点 proc(root.val) # 再处理右子树 if root.right: midorder_dfs_rec(root.right) # 非递归实现——中序遍历 def midorder_dfs(root:BinTreeNode, proc=print): stack = list() cur_node = root while cur_node is not None or stack: # 当cur_node为None且栈为空时,退出循环 while cur_node is not None: stack.append(cur_node) cur_node = cur_node.left # 左孩子为空了,stack不为空 if stack: cur_node = stack.pop() proc(cur_node.val) cur_node = cur_node.right # 递归实现,后序遍历 def lastorder_dfs_rec(root:BinTreeNode, proc=print): if root is None: return # 左子树 lastorder_dfs_rec(root.left) # 右子树 lastorder_dfs_rec(root.right) # 根结点 proc(root.val) # 非递归实现,后序遍历 def lastorder_dfs(root:BinTreeNode, proc=print): stack = list() cur_node = root while cur_node is not None or stack: while cur_node is not None: # 下行循环,直到栈顶的两子树为空 stack.append(cur_node) if cur_node.left is not None: # 能左就左,否则向右一步 cur_node = cur_node.left else: cur_node = cur_node.right # 入栈操作结束,两子树为空,cur_node=None cur_node = stack.pop() # 栈顶是应该访问的结点 proc(cur_node.val) if stack and stack[-1].left == cur_node: # 栈不为空,且当前结点是栈顶的左子结点 cur_node = stack[-1].right # 当前结点向右一步 else: cur_node = None # 没有右子树或者右子树遍历完毕,则强迫退栈 if __name__ == '__main__': bin_tree = BinTreeNode(2, BinTreeNode(3, BinTreeNode(4), BinTreeNode(6)), BinTreeNode(5, BinTreeNode(10), BinTreeNode(12))) print("树中的总结点数量:%s" % count_bintree_nodes(bin_tree)) print("树中结点数据总和:%s" % sum_tree_nodes(bin_tree)) print("递归实现,前序遍历序列:") preorder_dfs_rec(bin_tree) print("非递归实现,前序遍历序列:") preorder_dfs(bin_tree) print("递归实现,中序遍历序列:") midorder_dfs_rec(bin_tree) print("非递归实现,中序遍历序列:") midorder_dfs(bin_tree) print("递归实现,后序遍历序列:") lastorder_dfs_rec(bin_tree) print("非递归实现,后序遍历序列:") lastorder_dfs(bin_tree)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 基于链表技术实现栈,用LNode做节点 此时栈顶为链表首端元素 """ # 定义自己的异常 class StackUnderFlow(ValueError): # 继承ValueError类 pass # 定义节点类 class LNode(object): def __init__(self, elem, next_=None): self.elem = elem # 数据域 self.next = next_ # 指向下一个节点 class LinkedStack(object): def __init__(self): self._top = None def is_empty(self): return self._top is None def top(self): """取出栈顶元素""" # 先检查是否为空 if self._top is None: raise StackUnderFlow("in LinkedSatck.top()") # 非空,返回栈顶元素 return self._top.elem def push(self, elem): """入栈""" self._top = LNode(elem, self._top) def pop(self): """出栈""" # 是否为空 if self._top is None: raise StackUnderFlow("in LinkedList.pop()") # 非空,重置self._top,并返回出栈元素 elem = self._top.elem self._top = self._top.next return elem if __name__ == '__main__': stack_test = LinkedStack() for i in range(10): stack_test.push(i) print(stack_test.top()) print(stack_test.pop()) print(stack_test.top())