text
stringlengths
37
1.41M
from PIL import Image, ImageFilter class Canvas(object): """ The primary class which holds all of the different elements that are going into building the diagram """ def __init__(self, width=400, height=400, backgroundcolor=(0,0,0,0)): """ Initializes a blank canvas, with a specified width and he...
#Global Variable Definitions prec = 10**-12 def cmplxConj(num): return complex(num.real,-1*num.imag) def printRoot(root): print("Roots are as follows") for i in range (len(root)): print("x - [" + str(root[i]) + "]") print("Done") def roundComplex (val): if abs(round(val.imag) - val.imag) ...
""" Solution to Even Fibonacci numbers Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million...
""" Solution to Champernowne's constant Problem 40 An irrational decimal fraction is created by concatenating the positive integers: 0.123456789101112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the fol...
""" Solution to Sum square difference Problem 6 The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and...
""" Solution to Circular primes Problem 35 The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? """ ...
""" Solution to 10001st prime Problem 7 By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ def sieve(limit): primes = [True for x in range(limit)] primes[0] = primes[1] = False res = [] for i in range(2, limit): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat May 4 15:29:26 2019 @author: paul """ class Tree: def __init__(self, tree_list): node_list = [] for i in range(len(tree_list)): if tree_list[i]: node = TreeNode(tree_list[i]) node_list.ap...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 22 14:46:19 2019 @author: paul """ class Solution: def searchMatrix(self, matrix, target): if not matrix: return False if not matrix[0]: return False low = 0 high = len(m...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 22 15:14:15 2019 @author: paul """ class Solution: def findMin(self, nums): if len(nums)==1: return nums[0] low = 0 high = len(nums)-1 while True: mid = int((low+high)/2) ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 30 13:34:28 2019 @author: paul """ class Solution: def findMinHeightTrees(self, n, edges): ###Try BFS from the leaves adj = {} for i in range(n): adj[i] = {} for i,j in edges: adj[i][j] =...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 14 18:53:30 2019 @author: paul """ class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ self.count = 0 self.dfs(s, p) return self.count>0...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 20 16:55:32 2019 @author: paul """ import heapq class Heap: def __init__(self, k): self.k = k self.list = [] def add(self, t): if len(self.list)<self.k: heapq.heappush(self.list, t) elif...
def frab(n): if n<1: return None lastNum=2 secondLastNum=1 for x in range(n-2): tmpResult=lastNum+secondLastNum secondLastNum=lastNum lastNum=tmpResult return lastNum print(frab(1)) [] sum
""" ********************************Space Platfrom Game*********************************** Main game program ================= Done ===== screen created = Salvador 2/27/2021 Game loop created = Salvador 2/27/2021 Game exit event = Salvador 2/27/2021 still needs work ================ 1 """ import p...
import math import random from objective import * from utils import * def simulated_annealing(photos, SA_temp, SA_min_temp, SA_cool_rate, SA_it_per_temp): import time start_time = time.process_time() s = generate_slides(photos) #generate slides, sorted by horizontal and then vertical solution = organ...
# 垃圾回收机制 class ClassA(): def __init__(self): print('object born,id:%s'%str(hex(id(self)))) def __del__(self): print('object del,id:%s'%str(hex(id(self)))) # # # def f2(): # while True: # c1=ClassA() # c2=ClassA() # c1.t=c2 # c2.t=c1 # del c1 # ...
#-----------Clase Premio------------ class Premio: #Se define el tipo de premio y el valor acumulado def __init__(self, tipo): self.tipo = tipo self.acumulado = 0 def acumular(self, valor): self.acumulado += valor
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: lifangcheng <shiwanyin199@gmail.com> list1 = [1, 3, 2, 6, 7, 3, 4] list2 = [9, 4, 5, 7, 3, 6, 1] list1 = set(list1) list2 = set(list2) print(list1, list2) print(list1 & list2) # 并集 print(list1 | list2) # 交集 print(list1 - list2) # 差集(项在 list1中,但不在 list2中) pri...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: lifangcheng # 错误尝试达到3次后,询问是否继续,只要输入的不是 N 或者 n 就可以继续。 age_of_lfc = 26 count = 0 while count < 3: guess_age = int(input("guess a age:")) if guess_age == age_of_lfc: print("right.") break elif guess_age > age_of_lfc: print("old....
class Point(object): def __init__(self,x,y): self.x = x self.y = y def distance(self, other_point): dis = (self.x – other.x)**2 + (self.y – other.y) ** 2 return genhao(dis) a = Point(3,4) b = Point(4,5) dis = a.distance(b)
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: lifangcheng <shiwanyin199@gmail.com> ''' str 字符串的常用操作 ''' name = "my name is lifangcheng" print(name.capitalize()) # 首字母大写 print(name.count('n')) # 统计一个字符串内有多少个字母或者其他信息 print(name.center(50, '-')) # 打印50个'-', 把变量 name 的信息放在横杠的中间 print(name.endswith('eng')) #...
from graphics import * ''' # create a window with width = 700 and height = 500 win = GraphWin('Program Name', 700, 500) tri = Polygon(Point(0,500),Point(350,0), Point(700,500)) tri.setFill('yellow') tri.draw(win) win.mainloop() ''' def Sierpinski(level,point_b,point_a,point_c): colors=['yellow','green','blue','red...
# Multiplication and Exponent Table #welcome message print("Welcome to the Multiplication/Exponent Table App") #Get the name and the number name = input("\nHello, What is your name:\t\t") number = float(input("What number would you like to work with:\t")) #Multiplication print("\nMultiplication Table For "+str(num...
#Temprature Conversion App #Welcome message print("Welcome to the Temprature Conversion Program") #gather the input temp = float(input("\nWhat is the given temprature in degrees Fahrenheit: ")) #Convert the fagreneheit to celsius and kelvin fahreneheit = temp Celsius = round(((fahreneheit - 32)*(5/9)),4) kelvin = ro...
#String format name = "Dhaval" age = 30 money = 50.3 #print using string concatenation print(name + " is "+ str(age) + " and has $"+str(money)+" dollars.") #Print using .format() method print("{0} is {1} and has ${2} dollars.".format(name,age,money)) #print using f-string print(f"{name} is {age} and has ${money} d...
#Elif chains age = int(input("what your age: ")) if age<18: print("\nyou are only "+str(age)+"!!") print("you can't gamble") elif age<21: print("okay you are at "+str(age)+"!") print("YOu can play blackjack but can't have a drink") else: print("\nOkay you can play blackjack and can have a drink")
#包含一个学生类 #一个say hello函数 #一个打印语句 class Student(): def __init__(self,name="haha",age=18): self.name = name self.age = age def say(self): print("My name is {0}".format(self.name)) def sayhello(): print("欢迎来到图灵学院") if __name__ == "__main__": print("我是木块p01")
import time,datetime t1 = time.clock() for i in range(10): print(i) time.sleep(1) t2 = time.clock() print(t2-t1) t3 = time.localtime() t4 = time.strftime("%Y{Y}%m{m}%d{d} %H{o}%M",t3).format(Y="年",m="月",d="日",o=":") print(t4) d5 = datetime.date(2018,3,3) print(d5) print(d5.year) print(d5.month) print(d5.day)...
l = [x*x for x in range(5)]#放在中括号中就是列表生成器 g = (x*x for x in range(5))#放在小括号中就是生成器 print(type(l)) print(type(g))#type函数就是返回的是括号内的变量类型 def odd(): print("Step 1") yield 1#在函数odd中,yield负责返回,不用return是因为 print("Step 2") yield 2 print("Step 3") yield 3 def fib(max): n,a,b = 0,0,1 while n < m...
import random from graphics import * win = GraphWin("Barnsley Fern", 500, 500) win.setBackground("black") class BarnsleyFern(object): def __init__(self): self.x, self.y = 0, 0 def transform(self, x, y): rand = random.uniform(0, 100) if rand < 1: return 0, 0.16 * y ...
#!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that pers...
'''Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character. Return the minimum number of steps to make t an anagram of s. An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.''' class Solution: ...
#Xiang Fan #Gefei Tian import copy import math from graphics import* class Player(): def __init__(self,color): self.color = color def move(self, game): flag = 0 while flag == 0: try: pos = input('Enter a number: ') if pos in game.re...
from tkinter import * def covert(): m = float(miles.get()) killometer = m*1.609 result.config(text = f"{killometer}") window = Tk() window.title("MILES TO KM CONVERTER") window.config(padx = 20,pady=20) miles = Entry(width = 5) miles.grid(column =1, row=0) label = Label(text = "miles") label...
# Knapsack problem weight = [3, 1, 3, 4, 2] # weight of the items value = [2, 2, 4, 5, 3] # Value of the items def knapsack(C, W, V): """ This function calculates the highest value possible for the items in respect to their weights and maximum capacity. :param C: (int) Maximum capacity of the ...
""" Program that reads a PDB file and extracts each atom coordinates """ import pandas as pd def coord(file): """ The function that reads the PDB file and extracts the atoms coordinates it returns as a result a list of lists containing the atom name and its coordinates. Arguments : ...
import csv import os from .AbstractLoader import AbstractLoader class CsvLoader(AbstractLoader): """ A helper to load a folder of CSV files and to represent it by: - a numpy array for the positions, [n_tracks, n_pos_per_track, 3 (x/y/z)] - a numpy array for attributes, [n_tracks, n_pos_per_track,...
import pygame import random # ---------------Türkis--------Gelb-----------Lila-----------Grün---------Rot----------Blau---------Orange block_colors = [(0, 255, 255), (255, 255, 0), (128, 0, 128), (0, 255, 0), (255, 0, 0), (0, 0, 255), (255, 127, 0)] block_size = 20 board_width = block_size * 16 board_height = block_...
import json name = input("Please enter your name: ") print("Thank you for completing your name, " + name + "...") print("\nBy the way, Hello World!")
from random import randint class Calcular: def __init__(self: object, dificuldade: int, /) -> None: # somente posicional self.dificuldade: int = dificuldade self.valor1: int = self._gerar_valor self.valor2: int = self._gerar_valor self.operacao: int = randint(1, 3) # 1: +, 2: -, ...
x = int(input("Ente the value for x: ")) y = int(input("Ente the value for y: ")) z = int(input("Ente the value for z: ")) n = int(input("Ente the value for N: ")) a = [[a, b, c] for a in range(x + 1) for b in range(y + 1) for c in range(z + 1) if a+ b + c != n] print(a)
def main(): try: num1 =float(input("Please enter first number: ")) num2 =float(input("Please enter second number: ")) print("INSTRACTIONS".center(50, "=")) print(""" Please=> Enter 'a' for addition Enter 's' for substraction Enter 'm' for...
from random import choice def main(): print("Rule of the game".center(60, "=")) print(""" Rock smashes scissors. Paper covers rock. Scissors cut paper. """) computer_sco=0 player_sco=0 tie=0 while True: poss_ac=["rock", "paper", "sciss...
def mergeSort(alist): if len(alist) > 1: mid = len(alist)/2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i = 0 j = 0 k = 0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] <...
class Node: def __init__(self,initdata): self.data = initdata self.next = None def getData(self): return self.data def getNext(self): return self.next def setData(self,newdata): self.data = newdata def setNext(self,newnext): self.next = newnext c...
import os def rename(): path = input("请输入路径:") name = input("请输入开头名:") start_number = input("请输入开始数:") file_type = input("请输入后缀名(如 .jpg、.txt等等):") print("正在生成以" + name + start_number + file_type + "迭代的文件名") count = 0 file_list = os.listdir(path) for files in file_list: old_dir ...
print("******* PROGRAMA QUE MATRICULA E IMPRIME LA CONSTANCIA DE MATRICULA *******") import os import sys from modulog import * def menu(): print("Estas en el menu principal") print("1) MATRICULA") print("2) MODIFICAR MATRICULA") print("3) CONSTANCIA DE MATRICULA") print("4) SALIR") tr...
""" LA1 Comp 445 - Fall 2018 HTTP Client Library """ import socket from urllib.parse import urlparse import ipaddress from packet import Packet class Response: """Represents an HTTP response message. Attributes: http_version (str): HTTP version. code (int): Status code. status (str):...
def solution(number): count = 0 sum = 0 while count < number: if count%3 == 0 or count%5 == 0: sum = sum + count count += 1 return(sum)
""" Generating randomness """ import random # current = len(final_data) # remain = 100 - len(final_data) print("Please give AI some data to learn...") def datastring(): final_data = '' while len(final_data) < 10: print( f'Current data length is {len(final_data)}, {10 - len(final_data)} sy...
def sayHello(name): print(f"hello {name}, how are you ?") # sayHello("Mohit") def sum(x, y): z = x+y return z # print(sum(12,32)) def getSum(num1, num2): return num1 + 2*num2 print(getSum(1, 3)) str1 = "2751" # 7215 str2 = "3219" # 2391 arr = [] arr[:] = str1 print(arr) res = " " x = res.joi...
import matplotlib import glob from pylab import median, mean, std from random import shuffle from seq import * def pn(name): """Returns the prefix of a name, with the prefix separated by '_' for the remainder of the name. name - string """ return name[:name.find('_')] def ps(sequence): ...
failure = object() class Result: """ Wraps a callable and calls it with the given arguments if an exception is raised in the callable, it is wrapped. """ def __init__(self, _callable, *args, suppress=Exception, **kwargs): """ >>> w = Result(lambda x: x, 1) >>> w.unwrap() ...
""" Some computations that are necessary for the polygon intersection algorithm.""" from __future__ import division from fractions import * def point_in_polygon(point, polygon): """ Return true if the point point is contained in the polygon polygon. Input: point: a 2D point as [x,y] polyg...
"""The class face.""" class Face(object): """ Class to represent a face. Properties: - outer_component: half edge on its outer boundary when traversed counter clockwise. - inner_components: list of half edges, on of each of the holes in the face. None if the face does...
"""Module with unit tests for the triangle module.""" import unittest from triangle import * class Test_triangle_point_in_triangle(unittest.TestCase): """Unit tests for the method point_in_triangle in the module triangle.""" def setUp(self): """.""" pass def test_point_in_triangle(self)...
str = input() if str.islower(): print('a') else: print('A')
# Dan Wu # 1/26/2021 # 4a - Modify the binary search function from the exploration so that, instead of returning -1 when the target value is not in the list, # raises a TargetNotFound exception (you'll need to define this exception class). class TargetNotFound(Exception) : """define exception when target value is no...
import datetime as dt now = dt.datetime.now() year = now.year day_of_week = now.weekday() print(f"Year={year}") print(f"Day Of week:{day_of_week}") dob = dt.datetime(year=1980, month=12, day=31, hour=4, minute=45, second=58, microsecond=2568) print(dob)
import pandas data = pandas.read_csv("weather_data.csv") # data_dict = data.to_dict() # print(data_dict) temp_list = data["temp"].to_list() # avg_temp = sum(temp_list)/len(temp_list) # print(avg_temp) avg_temp = data["temp"].mean() print(f"Average Temp: f{avg_temp}") max_temp = data["temp"].max() print(f"Max Temp: ...
row1=[' ',' ',' '] row2=[' ',' ',' '] row3=[' ',' ',' '] map=[row1,row2,row3] print(f"{row1}\n{row2}\n{row3}") position=input("Where do you want to place the treasure?") print("Position is "+position[0:1]+","+position[1:1]) map [int(position[0:1])-1] [int(position[1:2])-1]="X" print(f"{row1}\n{row2}\n{row3}")
import random tie=0 my_choice=3 while my_choice not in (0,1,2): my_choice=int(input("enter your choice - 0 for Rock ; 1 for Paper ; 2 for Sciccors:")) comp_input=random.randint(0,2) print(f"You chose:{my_choice}") print(f"Computer chose:{comp_input}") if (my_choice==comp_input): print("You're tied! Pls play...
# def summ_n_diff(a, b): # return a+b, a-b # # def sum(a): # return a[0]+a[1] # # print(sum(summ_n_diff(10,3))) import datetime as dt print(dt.datetime.utcnow())
from tkinter import * window = Tk() window.title("Mils to Kms Converter") window.minsize(width=400, height=200) window.config(padx=40, pady=40) def convert_miles_to_km(): miles = input_miles.get() kms = (int(miles)*1.609) show_result(kms) def show_result(kms): kms_val_label.config(text=kms) input...
import jsonpickle class Parser: """Contains methods for storing and loading objects to and from JSON files""" file_path = "" def dump_to_file(self, object, file_name): """Save an object to a JSON file of the provided name NOTE: The file path should be set before calling this method. ...
# Don't forget to change this file's name before submission. import sys import os import enum import struct import socket class TftpProcessor(object): """ Implements logic for a TFTP client. The input to this object is a received UDP packet, the output is the packets to be written to the socket. ...
a = 1 b = 2 print (a,b) w ="Do I love Anan?" print("I said:%r" % w)
# https://colab.research.google.com/notebooks/mlcc/tensorflow_programming_concepts.ipynb#scrollTo=SDbi6heigEGA from __future__ import print_function import tensorflow as tf import matplotlib.pyplot as plt # Dataset visualization. import numpy as np # Low-level numerical Python library. import pandas as...
# https://stackabuse.com/creating-a-neural-network-from-scratch-in-python/ """ Neural Network Theory A neural network is a supervised learning algorithm which means that we provide it the input data containing the independent variables and the output data that contains the dependent variable. In the beginning, the ...
# -*- coding: utf-8 -*- """ Created on Mon Feb 18 10:56:56 2019 PURPOSE: Return a numpy array that contains binary labels for "male" and "female" REQUIRES: import numpy as np from sklearn.preprocessing import LabelEncoder INPUT: df: pandas dataframe col: str name of column t...
tupla = ("Python","Java","Android",12,[1,2,3],(1,2)) tupla[0] #A saída disso será 'Python' print(tupla) dir(tupla) tupla.append(15) #Retorna uma exception porque tupla é imutável tupla.count("Python") #Quantas vezes python aparece na tupla tupla[4].append(4) #Isso funciona porque está manipulado uma lista dentro de uma...
class Node: def __init__(self, value): self.value = value self.next = None class SinglyLinkedList: def __init__(self): self.head = None def __len__(self): count = 0 head = self.head while head: count += 1 head = head.next ret...
from typing import Callable, Any, List # Problem: https://challenges.wolframcloud.com/challenge/flutter def flutter(f: Callable, x: Any, items: List[Any]) -> List[Callable]: """ params: X = 2 L = [a, b, c, d] returns: {f[2, a], f[2, b], f[2, c], f[2, d]} """ results = [] ...
def dijkstra_algorithm(): heap = [] heappush(heap, (0, start)) # Initialize start with zero cost came_from = {} # For node n, g_score[n] is the cost of the cheapest path from start to n currently known. g_score = defaultdict(int) g_score[start] = 0 result = None while heap: ...
""" Imports """ def straight_insertion_sort(_a: list): """ The simplest insertion sort is the most obvious one """ _n = len(_a) for j in range(1, _n): i = j - 1 k = _a[j] _r = _a[j] while i >= 0 and k < _a[i]: _a[i + 1] = _a[i] i = i - 1 ...
import re def polish_function(expression): expression = re.sub(r'\s+', '', expression) maps = { '+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x / y } stack = [] error = '' for item in expression: try: ...
def fib(d): a = 0 b = 1 n = 1 while 1: x = a + b a = b b = x n += 1 if count_digits(x) == d: break return n def count_digits(n): t = 0 while n >= 10: n //= 10 t += 1 return t + 1 result = fib(1000) print(result)
import math from time import sleep from collections import Counter from read_file import read_data def part_one(timers, days=80): n_timers = timers number_of_fish = len(n_timers) counter = Counter(n_timers) # Keep a count of each timer ncount = 0 def _process(timer): k = timer - 1 ...
import base64 from encoding import split_in_twos def read_file(filename): return open(filename) def create_file(encoded_file: str): # Create and manually unzip or you can do it with python using zipfile lib with open('data/output.zip', 'wb') as f: base64.decode(encoded_file, f) def decode(): ...
from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.optimizers import Adam from keras.layers.normalization import BatchNormalization from keras.layers import Conv2D, MaxPooling2D def get_small_cnn_model(input_shape=(28, 28, 1),num_classes=10): # Three steps ...
#Everett Williams #14JUL17 as of 150755JUL17 #HW3 Problem 4 #Make Change program def buildCoinsArr(coinsUsed, coinSet): start = len(coinsUsed)-1 numCoinsUsed = [] #initialize numCoinsUsed to 0. This array will be used to track #the number of each coin that was used. for i in range(0, len(coinSet)...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def fun1(x,n=2): s = 1 while n > 0: n = n - 1 s = s * x return s def fun2(*numbers): s = 0 for n in numbers: s = s + n * n return s def add_end(L=None): if L is None: L = [] L.append('END') return L def ...
class Tree: def __init__(self, me, left, right): self.me = me self.left = left self.right = right self.visit = 0 def make(tree): if tree.visit == 0: tree.left = Tree(tree.me + 1, 0, 0) make(tree.left) tree.visit = 1 tree.right = Tree(tree.left.me...
def check(line): temp = [] i = 0 for cnt in range(len(line)): if line[i] == '{': temp.append('{') if line[i] == '(': temp.append('(') if line[i] == '}': if not temp: return 0 if temp[-1] == '(': return 0 ...
def find(N): global board t = int(input()) for tc in range(1, t+1): N = int(input()) board = [[0]*N for i in range(N)] res = find(N) print("#{} {}".format(tc, res))
for i1 in range(1, 4): for i2 in range(1, 4): if i2 != i1: for i3 in range(1, 4): if i3 != i1 and i3 != i2: print(i1, i2, i3) def perm(n, k, m): # m 개의 숫자들에서 k자리의 순열 n은 현재 위치 global arr if k == n: print(arr) else: for i in range(...
def change(i, j, S, ok): global board global setting global N di, dj = setting[S] # 증가값 ni, nj = i + di, j + dj # 변화값 before = board[i][j] after = board[ni][nj] if S == 'up': print(board) if i == 0 and after == 0: if i < N - 2: change(i + 1,...
#!/usr/bin/env python # -*- coding: utf-8 -*- from sort_utils import swap def sort(array): """ Selection sort Complexity Memory O(n) - since all swaps "in place" and no addition data strictures requires Time Always O(n^2) - because no matter how array e...
import random import nltk from sequences import * """ Best sequence eg. for she were today (if there is not any appearence of 'she were today') she <is> today she <was> <yesterday> Generate random [w1,w2,w3][w2,w3,w4][w3,w4,w5]... r.prob [w1,w2,w3]hp[w2,w3,w4].......
""" Your chance to explore Loops and Turtles! Authors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder, their colleagues and Jeremy Roy. """ ######################################################################## # Done: 1. # On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name. ###...
def fib_dict(i, d): """ Get Fibonacci Sequence using dictionary which is more efficient than using recursion i - get n of Fibonacci Sequence d - dictionary that store Fibonacci Sequence """ if (i == 0 or i == 1) and i not in d: d[i] = 1 return d[i] if i in d: re...
from getpass import getpass d = { "spy": "spy", "p": "private", "serg": "sergeant", "2l": "2nd lieutenant", "1l": "1st lieutenant", "capt": "captain", "m": "major", "lc": "lieutenant colonel", "col": "colonel", "1g": "1 star general", "2g": "2 star general", "3g": "3 st...
from random import shuffle def print_board(queen_pos): """ Prints board on screen :param queen_pos: list of queens' positions """ board_size = len(queen_pos) for x in range(board_size): for y in range(board_size): if queen_pos[y] == x: print(' Q ', end='') ...
done = False while not done: number = int(input("What numbers times table would you like? > ")) upto = int(input('what number would you like it to go up to? > ')) upto += 1 for i in range(1,upto): answer = i*number print(i,"x",number,"=",answer) again = input('would you like to enter...
1 = "januarry" 2 = "Febuary" 3 = "March" 4 = "April" 5 = "May" 6 = "June" 7 = "July" 8 = "August" 9 = "September" 10 = "October" 11 = "November" 12 = "December" month = int(input("Enter a month (number) > ")) if number > 12 and number < 1: print("Between 1 and 12!") elif number == 1: print(1) elif number == 2: ...
#running total total = 0 for i in range(5): new_number = int(input("Enter a number: " )) total += new_number print("The total is: ", total)
import random print('Welcome to Camel!') print('You have stolen a camel to make your way across the great Mobi desert.') print('The natives want their camel back and are chasing you down! Survive your') print('desert trek and out run the natives.') done = False traveled = 0 thirst = 0 tiredness = 0 Ndistance = 30 drink...
temp = int(input("What is the temperature of the water?(degrees) > ")) if temp > 100: print("The water is boiling") elif temp < 0: print("The water is frozen) else: Print("The water is liquid")
number = 1 while number < 10: print("This is turn ",number) number += 1 print("The loop is now finnished")