text
stringlengths
5
121k
from datetime import datetime from datetime import timedelta '''the formatting on the lab is off GetNextDate(day, month, year, num_days_forward) would not return 9/17/2016 if GetNextDate(2, 28, 2004) is passed because 28 is not a month. ''' def GetNextDate(day, month, year, num_days_forward): num_days_forward = int...
minutes = float(input("Minutes: ")) num_hours = minutes//60 num_minutes = minutes%60 num_seconds = 60*(num_minutes%1) print(int(num_hours), "hours", int(num_minutes), "minutes", int(num_seconds), "seconds")
first_name = input("What is your first name?") last_name = input("What is your last name?") weight = int(input("What is your weight?")) moon_gravity= 0.17 moon_weight = weight*moon_gravity print("My name is", first_name, last_name+".", "And I weigh", moon_weight, "on the moon")
from math import * x = [15, 12, 8, 8, 7, 7, 7, 6, 5, 3] y = [10, 25, 17, 11, 13, 17, 20, 13, 9, 15] x_mean = sum(x)/len(x) y_mean = sum(y)/len(y) diff_x_mean = [(i - x_mean) for i in x] diff_y_mean = [(i - y_mean) for i in y] xx = sum([(i - x_mean)**2 for i in x]) yy = sum([(i - y_mean)**2 for i in y]) sum_diff =...
class Move: """A single move in a game Attributes: player -- Player making the move piece -- Piece being moved space -- Space to which piece is being moved """ def __init__(self, player, piece, space): self.player = player self.piece = piece self.space =...
""" ================================= Author: keen Created on: 2020/8/7 E-mail:keen2020@outlook.com ================================= """ b = [1, 2, 3, 4] print(b[0]) print(b[1]) print(b[-1])
""" ================================= Author: keen Created on: 2020/7/27 E-mail:keen2020@outlook.com ================================= """ import time import threading def demo1(): for i in range(2): print("正在加载中...") print("当前活跃的线程有:{}".format(threading.current_thread())) ...
import turtle t=turtle.Turtle() s=turtle.Screen() ''' t=Turtle() s=Screen() ''' def my_rect(): t.begin_fill() for i in range(4): t.forward(100) t.left(90) t.end_fill() my_rect() s.mainloop()
n = int(input('n: ')) sum = 0 while (n > 0): sum += n n -= 1 for i in range(0, n+1): sum += i
def fibonacci(r, a, b): if r == 0: return else: print("{0} {1}".format(a, b), end = ' ') r -= 1 fibonacci(r, a+b, a+ 2*b) return if __name__ == "__main__": num = int(input("Enter the number of fibonacci series you want: ")) if num =...
import os import csv total_votes = 0 candidates = {} csvpath = os.path.join('Resources', '02-Homework_03-Python_Instructions_PyPoll_Resources_election_data.csv') with open (csvpath) as csvfile: csv_reader = csv.reader(csvfile, delimiter=",") csv_header = next(csvfile) ...
game_running = True while game_running == True: new_round = True player = {'name': 'Rekku', 'attack': 10, 'heal': 16, 'health': 100} monster = {'name': 'Max', 'attack': 12, 'health': 100} print('---' * 5) print('Enter Player name') player['name'] = input() print('---' *...
def course_info(tup_list): course_dict={} course_dict["students"]=[] average=0 for tup in tup_list: course_dict["students"].append(tup[0]) average=average+tup[1] average=average/len(tup_list) course_dict["avg_age"]=average return course_dict
import heapq import itertools class PriorityQueue: def __init__(self): self.heap = [] self.counter = itertools.count() self.entry_finder = {} self._size = 0 def size(self): return self._size def push(self, priority, x): count = next(self.counter) e...
''' Notice carefully that 1. All the elements of the array are always non-negative 2. If array length = n, then elements would start from 0 to (n-2), i.e. Natural numbers 0,1,2,3,4,5...(n-2) 3. There is only SINGLE element which is present twice. Therefore let's find the sum of all elements (current_sum) of the origi...
from random import choice class RandomWalk: """Generates random walks.""" def __init__(self, num_points=5000): """Initializes walk attributes.""" self.num_points = num_points self.x_values = [0] self.y_values = [0] def fill_walk(self): """Calculate all the points in a walk.""" while len(self.x...
import json def get_fav_num(): """Asks a user for their favorite number and stores the value in a .json file.""" fav_num = input("What is your favorite number? ") filename = 'fav_num.json' with open(filename, 'w') as f: json.dump(fav_num, f) def print_fav_num(): """Retrieves user's favoite number and prints ...
users = ['admin', 'Nick', 'Nicole', 'Al', 'Pete', 'Michaela'] for user in users: if user == 'admin': print("Hello admin, would you like to see a status report?") else: print(f"Hello {user}, thanks for logging in.")
prompt = "Why do you like programming? (enter 'q' to exit)\n\t" keep_going = True while keep_going: reason = input(prompt) if reason != 'q': with open('programming_poll.txt', 'a') as file_object: file_object.write(f"{reason}\n") else: keep_going = False
animals = ['parrot', 'raven', 'bald eagle'] for animal in animals: print(f"A {animal} is a pretty cool bird.") print("And all of them can fly!")
def make_album(artist, album, no_of_songs=None): album_info = {'artist': artist, 'album': album} if no_of_songs: album_info['no_of_songs'] = no_of_songs return album_info while True: artist_name = input("Enter the artist's name: ") album_title = input("Enter the album title: ") no_of_songs = input("Enter the n...
guests = ['Bertrand Russell', 'Elon Musk', 'Claude Shannon'] print(f"Dear Mr. {guests[0]}, are you available to attend a dinner at my home this weekend?") print(f"Dear Mr. {guests[1]}, are you available to attend a dinner at my home this weekend?") print(f"Dear Mr. {guests[2]}, are you available to attend a dinner at ...
destinations = ['Oslo', 'Edinburgh', 'Copenhagen', 'London', 'Stockholm'] print(destinations) print(sorted(destinations)) print(destinations) print(sorted(destinations, reverse=True)) print(destinations) destinations.reverse() print(destinations) destinations.reverse() print(destinations) destinations.sort() print(dest...
name = "Nick" message = f"Hello {name},would you like to learn some python today?" print(message)
def read_file(filename): try: with open(filename) as f: content = f.read() print(content.strip()) except FileNotFoundError: print(f"We couldn't find {filename}") read_file('cats.txt') read_file('dogs.txt')
import sys def write_t_file(out_file, a): with open(out_file, 'w') as h: if type(a) is list: for i in range(len(a)): if type(a[i]) is list: if len(a[i])>1: for j in range(len(a[i])-1): h.wri...
x = 74 num_of_guesses = 1 print("Welcome to guess the number") print("Number of guesses is limited to only 6 times: ") while (num_of_guesses <= 6): guess_number = int(input("Guess the number :\n")) if guess_number < 74: print("Please Increase the number") elif guess_number > 74: print("Pleas...
class student: def __init__(self,name,roll,age): self.name = name self.roll = roll self.age = age self.attendance = 0 self.marks = [] def print_details(self): print("Name:{}\nRoll:{}\nAge:{}\nAttendance:{}\nMarks:{}"...
import os os.rename("files/a.txt" , "files/aaa.txt") os.remove("files/b.txt")
from tkinter import * my_gui = Tk() my_gui.title("Hello") my_gui.geometry("500x500+300+100") my_gui.mainloop()
num = int(input("Enter any number:\n")) if(num < 0): print("It's a negative number.") else: fact = 1 while(num > 0): fact = fact * num num = num - 1 print("Answer:\t",fact) input("Press any key to quit...")
print("Assuming that both number and power will be +ve\n") num = int(input("Enter a number:\n")) power = int(input("Enter power:\n")) result = num for i in range(1,power): result = result * num print(result) input("Press any key to quit...")
num = int(input("Enter a number:\n")) for i in range (1, (num+1)): print("Multiplication Table of",i) for j in range(1,11): print(i,"x",j,"=",i*j)
""" Task: The goal in this problem is to find the minimum number of coins needed to change the input value (integer) into coins with denominations of 1, 5, 10. Input format: single integer m. (1<=m<=10^3) Output: minimum number of coins with denominations 1, 5, 10 that changes m. """ def greedy_strategy(m, print_dist...
""" Maximizing Revenue in Online ad placement. You have n ads to place on a popular internet page. For each ad, you know how much is the advertiser willing to pay for one click on this ad. You have set up n slots on your page and estimated the expected number of clicks per day for each slot. Now your goal is to distri...
"""How close a data is to being sorted An inversion of sequence a0, a1, .. an-1 is a pair of indices 0<= i < j< n such that ai < aj. The number of inversion of a sequence in some sense measures how close the sequence is to being sorted. For example, a sorted (in non-decreasing order) sequence contains no inversions a...
from functools import cmp_to_key import random def compare_two_numbers(x, y): if x == y: return x - y str_x = str(x) str_y = str(y) if str_x[0] != str_y[0]: return int(str_x[0]) - int(str_y[0]) same = True max_x = len(str_x) - 1 index_x = min(1, max_x) max_...
def main(): count = 1 while count < 11: print(count) count = count + 1 if count == 11: print('Counting complete.') if __name__ == "__main__": main()
class Parameter: name = [] datatype = [] value = [] datatypes = {"BYTE": 33, "SHORT": 34, "INT": 35, "LONG": 36, "FLOAT": 15, "DOUBLE": 16, "CHAR": 1, "STRING": 46, "...
import sys class BinaryTree(): def __init__(self,rootid): self.left = None self.right = None self.rootid = rootid def getLeftChild(self): return self.left def getRightChild(self): return self.right def setNodeValue(self,value): self.rootid = value def ...
def read(): f=open("input",'r') line=f.readline() split=line.split() print(split) a=float(split[2]) line=f.readline() split=line.split() print(split) b=float(split[2]) line=f.readline() split=line.split() print(split) c=float(split[2]) f.close() return(a,b,c)
""" Determines whether a given integer is a perfect square, without using sqrt() or multiplication. This works because the square of a natural number, n, is the sum of the first n consecutive odd natural numbers. Various itertools functions are used to generate a lazy iterable of odd numbers and a running sum of them,...
""" http://en.wikipedia.org/wiki/Tree_of_primitive_Pythagorean_triples """ pairMN=(2, 1) def nextLevel(pairMN): (m, n)=pairMN return ((2*m-n, m), (2*m+n, m), (m+2*n, n)) def MN2ABC(pairMN): (m, n)=pairMN return (m**2-n**2, 2*m*n, m**2+n**2) def traverse(pairMN, condition): if (condition(pairMN...
class SequenceNumber: def __init__(self): self.__n=0 def advance(self): self.__n+=1 def n(self): return self.__n class TriangleNumber(SequenceNumber): def generate(self): n=self.n() return n*(n+1)/2 class SquareNumber(SequenceNumber): def generate(self): ...
""" see: http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Pell.27s_equation """ """ Let A be number of blue discs, B - number of all discs Than, (A/B)*((A-1)*(B-1) == 1/2 -> 2*A**2-2*A == B**2 - B Than, B**2 - 2*A**2 == B - 2*A Than, (2*B-1)**2 - 2*(2*A-1)**2 = -1 It's like a Pell's equation, only w...
import os import pathlib def renameFile(dir_path = None, out_path = None): file_paths = os.listdir(dir_path) file_lens = len(file_paths) print("file_len:",file_lens) if out_path == None: out_path = str(dir_path) + '/outdir' print("out_path",out_path) os.mkdir(out...
n=int(input("Enter the binary value")) count=-1 sum=0 while(n!=0): r=n%10 n=int(n/10) count=count+1 sum=sum+(2**count)*r print("Decimal value is "+ str(sum))
from gensim.utils import lemmatize from nltk.corpus import stopwords def get_stopwords(): return set(stopwords.words('english')) def get_bigram(train_texts): import gensim bigram = gensim.models.Phrases(train_texts) return bigram def build_texts_from_file(fname): import gensim """ Fun...
""" This module return text for widget for main window. Text depends about choice language. """ def main_text(language='eng'): if language == 'eng': text = {'title': 'Coach Book', 'database': 'Database', 'training': 'Training'} if language == 'rus': text = {'title': 'Книга трене...
info = { "1212121212":"mohammed" } Input = input('Your Name Or Phone Number: ').lower() print("Sorry, The number is not found" if Input not in info.keys() and Input not in info.values() else "This is invalid number" if len([i for i in Input if i in "0123456789"])!=len(Input) else [i for i in info.keys() if info[i]==...
import box, sys, time, random if len(sys.argv) != 3: print("Three command line arguments required.") else: start = time.time() name = sys.argv[1] time_limit = float(sys.argv[2]) remaining = list(range(1, 10)) def lose(): print("Game Over!\n") print("Score for player ", name, ": ", sum(remaining), " points") p...
max_days = 4 target = 16 dollars = 1 days_when_amount_acquired = 0 for num in range(1,max_days+1): dollars *= 2 if dollars >= target: days_when_amount_acquired = num break print('Days needed:',days_when_amount_acquired)
import math n_str = input("Input n: ") n_int = int(n_str) first_three = n_int//100 last_two =n_int % 100 print("first_three:", first_three) print("last_two:", last_two)
""" Spyder Editor This is a temporary script file. @author: Josh M, Zhicong Z """ import numpy as np import matplotlib.pyplot as plt def mean(n): return float(sum(n))/max(len(n),1) mu, sigma = -10, 5 s = np.random.normal(mu, sigma, 1000) mu2, sigma2 = 10, 5 s2 = np.random.normal(mu2, sigma2, 1000) s3 = s + ...
from DateStructureAndAlgorithm.bintree import BinTree, BinTNode, PrioQueue __author__ = 'barnett' class HTNode(BinTNode): def __lt__(self, othernode): return self.data < othernode.data class HuffmanPrioQ(PrioQueue): def number(self): return len(self._elems) def huffman_tree(weights): ...
""" Item Class : Where you can resize the ability of Mac Gyver to get Swiss Army Knives """ import os import pygame from config import ASSETS_DIR from random import randint class Item(pygame.sprite.Sprite): """ This class is handling properties and methods for all kind of item :returns any player without...
stack = [] def pushit(): ch = 'y' while (ch == 'y'): inp = input("Enter some character") stack.append(inp) ch = input("Do you want to enter more values? Enter y/n") def popit(): if len(stack) == 0: print('Cannot pop from an empty stack!') else: print('R...
import math def gaussian(dist, sigma=10.0): exp = math.e ** (-dist ** 2 / (2 * sigma ** 2)) return (1 / (sigma * (2 * math.pi) ** .5)) * exp
from itertools import count def prime_generator(): g = count(2) while True: prime = next(g) yield prime g = filter(lambda x, prime=prime: x % prime, g) for pr in prime_generator(): print(pr)
import sys class List(list): def head(self): return self[0] def tail(self): return self[1:] def init(self): return self[0:-1] def last(self): return self[-1] def shift(self): try: return self.pop(0) except IndexError: retur...
import matplotlib.pyplot as plt import numpy as np import math def poisson(lambd): def f(x): return float(lambd ** x) * np.exp(-lambd) / math.factorial(x) return f N = 8 L = [] score_mean = 0.8 f = poisson(score_mean) L.append([f(k) for k in range(N + 1)]) for prob in L: plt.plot(range(N + 1),...
from pprint import pformat import random def randomize(items): randomized = [] while 0 < len(items): idx = random.randint(0, len(items) - 1) popped = items[idx] del items[idx] randomized.append(popped) return randomized if __name__ == '__main__': x = [1, 2, 3, 4, 5]...
import plotly.graph_objects as go import plotly.express as px from plotly.offline import plot import os import pandas as pd data = pd.read_csv(r"data/csv/aggregated_scores.csv") fig = go.Figure([go.Bar(x = data['bank'], y = data['cx_quantitative_score'], marker_color = 'green')]) fig.update_layout(tit...
import random max=1 min=6 print("Heres your roll!",end=" ") print(random.randint(max,min)) yesno = input("Reroll? Y/N: ") while yesno == 'Y' or yesno== 'y': pass print("Heres your roll!",end=" ") print(random.randint(max,min)) yesno = input("Reroll? Y/N: ") print("Heres your roll!",end=" ") whil...
import sys sys.setrecursionlimit(10000) def fib(n): if n <= 1: return 1 else: return fib(n-1) + fib(n-2) def coincount(l): if l[2] == 0: return 1 if l[2] < 0: return 0 if (l[1]<=0 and l[2]>=1): return 0 return coincount([l[0], l[1]-1, l[2]]) + coincount(...
import math import random def knn(novo_exemplo, entradas, respostas, k): melhores = sorted( [ [ math.sqrt( sum( [(n - e)**2 for n, e in zip(novo_exempl...
def Divide(No1,No2): if No2 == 0 : return -1 return No1/No2; No1 = float(input("Enter First Number :")) No2 = float(input("Enter Second Number :")) iAns = Divide(No1,No2) print("Division is :",iAns);
def mayusculas(cadena): letras = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" coincidencias = '' for x in cadena: for y in letras: if x == y: coincidencias = coincidencias + x return coincidencias cadena = input("Introduce una cadena de texto") print("Se han encontrado {} mayusculas y estas fueron las letras {}.".format...
from datetime import datetime datearr=[] wage_per_hour = 5 client_name = input("Name of client: ") task_name = input("What is the name of this task?: ") started = input("When did "+task_name+" start? (YYYY-MM-DD HH:MM): ") datearr.append(started) now = datetime.now() datearr.append(now) print("Amazing, let us pro...
n = 123 f = 456.789 s1 = 'Hello,world' s2 = 'Helo,\'Adam\'' s3 = r'''Hello, Lisa!''' s4 = 'Hello,"Bart"' print(n) print(f) print(s1) print(s2) print(s3) print(s4) print ('True is:',True) print ('False is:',False) print('3>2 is:',3>2) print('3>5 is:',3>5) print('True and True is:',True and True) r'''只有所有都为True,and结果才...
def advancedGuessing(list_of_people, name): confidence = {prof : 0 for prof in list_of_people} for prof in list_of_people: name_iterator = iter(name) last_position = 0 on_a_roll = False while 1: try: on_a_roll = False ...
def matmult (A, B): rows_A = len(A) cols_A = len(A[0]) rows_B = len(B) cols_B = len(B[0]) if cols_A != rows_B: return C = [[0 for row in range(cols_B)] for col in range(rows_A)] for i in range(rows_A): for j in range(cols_B): for...
import re def find_delimiter(numbers): if len(numbers) > 0: if re.match("//(?P<delimiter>.)\n\d+(?:(?P=delimiter)\d+)*", numbers): return numbers[2], numbers[4:] elif re.match("//(?P<delimiter>\[.*\])\n\d+(?:(?P=delimiter)\d+)*", numbers): first_newline = numbers.find("\n") ...
''' while: 负责不固定次数的循环 while 条件: xxxx ''' import random target = random.randint(0, 1000) count = 0 while True: count += 1 num = input('请猜测一个数字(0-1000):') num = int(num) if num == target: print('恭喜您, 猜对了, 共猜了%s次' % count) break if num < target: print('猜小了') if num...
""" Stack to queue converter. """ import copy from arraystack import ArrayStack from arrayqueue import ArrayQueue def stack_to_queue(stack): """ This function returns queue from stack. """ stack_copy = copy.deepcopy(stack) queue = ArrayQueue() stack_lenth = len(stack_copy) for _ in ...
""" This is module which contains two classes for cashing data from the webpage. """ import doctest from datetime import datetime from urllib.request import urlopen from time import time clean = open("date_note.txt", 'a') clean_1 = open("cash_note.txt", 'a') with open("date_note.txt") as file: if file.readlines()...
def topological_sort(unsorted_graph): ''' idea from http://blog.jupo.org/2012/04/06/topological-sorting-acyclic-directed-graphs/ deal with a node only if all it's children are sorted, in other words, start from the latest appeared nodes, build from there. A cycle is defined when in any iteration, none o...
def isPrime(n): if n <= 1: return False for i in range(2, n): if n % i == 0: return False return True def allPrimes(n): for i in range(2, n): if isPrime(i): yield i def isPerfect(n): sum = 0 for i in range(1, n): if n % i == 0: ...
""" Created on Sun Jul 17 21:50:33 2016 @author: Schultze first crack at computing the nth prime number optimized for simplest code, not fastest run time """ import math n = 2 primeSum = math.log(2) i = 1 while i < 1000: n = n + 1 test = 1 rem = 1 while rem != 0: ...
""" 07/26/16 @Schultze Script to calculate chicken nuggets combinations If nuggets are sold in packs of 6, 9, and 20, what combinations are required to get exactly n nuggets. AKA, all solutions to the diopnantene equation: 6A + 9B + 20C = n for a given n This is an update to diahpantene_rev1.py in which it cal...
""" Given an integer X and a list L, find the first pair in L whose sum is X """ def find_pair_with_sum(X, l): """ Returns a tuple with indexes of both elements or None if there is no pair """ return (0, 1) l = [3, 34, 4, 12, 5, 2] X = 5 print ("In the list {} items {} sum {}".format(l, find_pair_wi...
import unittest import tuw_geometry as tuw class TestPoint2D(unittest.TestCase): def runTest(self): p = tuw.Point2D(3,2) self.assertEqual(p.x, 3, 'incorrect x') self.assertEqual(p.y, 2, 'incorrect y') self.assertEqual(p.h, 1, 'incorrect h') p = tuw.Point2D(3,2,3) s...
def encode(message, key): msg_len = len(message) alfa = 'abcdefghijklmnopqrstuvwxyz' out_message = '' for letter in message: if letter.lower() not in alfa: print('invalid letter') break if letter == letter.lower(): letter_pos = alfa.index(lette...
fo = open("Akash.txt", "rw+") line = fo.readline() print ("Read Line: %s" % (line)) fo.seek(0, 0) line = fo.readline() print ("Read Line: %s" % (line)) fo.close()
import time text1 = "Toets hier" text2 = "Nog so bietjie" N = 100000 iterations = 100 avg = 0 avg_lst = [0,0,0,0] for k in range(iterations): avg = 0 t1 = time.time() for i in range(N): text = "Toets hier" + str(i*0.1) + "Nog so bietjie" t2 = time.time() avg += t2 - t1 ...
''' Create a program that: Chooses a number between 1 to 100 Takes a users guess and tells them if they are correct or not Bonus: Tell the user if their guess was lower or higher than the computer's number ''' print('Number Guessing Challenge') guess=int(input('This is a number guessing Challenge. Please enter your ...
class Product: def __init__(self, id, name, unit, quantity, category, measurement_unit): self.id = id self.name = name self.unit = unit self.quantity = quantity self.category = category self.measurement_unit = measurement_unit '''method to return a JSON format'...
password = 'a123456' i = 3 while i > 0: pwd = input('Please enter the password: ') if pwd == password: print('Log in success!') break else: i = i - 1 print('Password is incorrect! Remaining', i,'times')
def p(func): def inner(s): return '<p>' + func(s) + '</p>' return inner def tag(*args, name='p', **kwargs): def _tag(func): def inner(*args, **kwargs): return '<%s>%s</%s>' % (name, func(*args, **kwargs), name) return inner return _tag @tag(name='html') @tag(name...
import csv file = 'examples/csv/monty_python.csv' with open(file) as fh: rd = csv.DictReader(fh, delimiter=',') for row in rd: print(row)
import random y = 0 x = 0; while 1 : x = random.randint(1,9) print(x) if(x % 2 == 0): break;
edad = input("Ingresa tu edad: ") print(edad) print(type(edad)) edadEntero = int(edad) print(type(edadEntero))
""" """ from typing import List from collections import Counter def valid_passphrase(phrase: str) -> bool: counter = Counter(phrase.split()) for val in counter.values(): if val > 1: return False return True assert valid_passphrase("aa bb cc dd ee") assert not valid_passphrase("aa b...
""" http://adventofcode.com/2017/day/24 """ from typing import List def parse_input(input: List[str]) -> List[List[int]]: return [list(map(int, line.split('/'))) for line in input] def build_bridges(parts, pin, bridge): available_parts = [part for part in parts if pin in part] if not available_part...
from contacts import Contacts add_delete_search_contact_ = True phone_book = Contacts() while add_delete_search_contact_: check = input('Add/Delete/Search/Quit a contact? a/d/s/q ') if check == 'a': contact = phone_book.add_contact() add_delete_search_contact_ = True elif check == 'd': ...
adjLists = [ [1,2], [2,3], [4], [4,5], [5], [] ] print("Neighbors of vertex 0: ", adjLists[0]) print("Neighbors of vertex 3: ", adjLists[3]) print("\nPrint all adjacency lists with corresponding vertex") n = len(adjLists) for v in range(0,n): print(v, ":", adjLists[v])
bob = ('Bob', 30, 'male') print( 'Representation:', bob) jane = ('Jane', 29, 'female') print( '\nField by index:', jane[0]) print( '\nFields by index:') for p in [ bob, jane ]: print( '%s is a %d year old %s' % p)
import collections Person = collections.namedtuple ('Person', 'name age gender') print( 'Type of Person:', type(Person)) bob = Person(name='Bob', age=30, gender='male') print( '\nRepresentation:', bob) jane = Person(name='Jane', age=29, gender='female') print( '\nField by name:', jane.name) print( '\nFields by in...
import time import IP import DNA def lcs(X , Y): m = len(X) n = len(Y) L = [[0 for x in range(n+1)] for x in range(m+1)] """Following steps build L[m+1][n+1] in bottom up fashion Note: L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]""" for i in range(m+...
g = 0 def func(): i = 30 print("From Inside Func() - i = ", i) print("From Inside Func() - g = ", g) print('---- Global Variables ---') func() print("From Outside Func() - g = ", g) print() g = 0 def func1(): g = 10 print("From Inside Func1() - g = ", g) print('---- Modify Global Variables...