text
stringlengths
37
1.41M
def create_list(): list1 = [] number1 = int(input("Enter the number of value in list ")) for i in range(0, number1): list_number = int(input("Enter the number")) list1.append(list_number) print(list1) return list1 def sum(numbers): sum = 0 for iteration in numbers: ...
class Bank_Account: def __init__(self, Acct_no, Acct_name): self.Acct_no = Acct_no self.Acct_name = Acct_name def bank_details(self): print("The user account number:", self.Acct_no) print("The user name:", self.Acct_name) class saving_acct(Bank_Account): def __init__(self,...
def replace_occurence(given_string): result_string = given_string.split('%20') string_value = ('===').join(result_string) print(string_value) given_string = "we%20use%20%%20to%20find%20remainder" replace_occurence(given_string) # output= we===use===%===to===find===remainder
# -*- coding: utf-8 -*- """ Created on Sat Jun 13 14:28:17 2020 @author: Priscilla Mungai """ import numpy as np import pandas as pd from matplotlib import pyplot as plt import random as rd import datetime # Upload Djibouti Travelling Sales Man Problem city coordinates data djibouti_data = pd.read_table(...
from sys import exit from random import randint from textwrap import dedent class Scene(object): def enter(self): print("This scene is not yet configured.") print("Subclass it and hit enter().") exit(1) class Engine(object): # scene_map = central_corridor def __init__(self, scene...
import numpy as np import matplotlib.pyplot as plt class LinearRegression: def __init__(self, learning_rate=0.001, epochs=10000): self.m = np.random.randn() self.c = np.random.randn() self.learning_rate = learning_rate self.epochs = epochs pass def train(self, training...
class Animal: def __init__(self,name,color,age,size): self.name = name self.color = color self.age = age self.size = size def printAll(self): print(self.name) print(self.color) print(self.age) print(self.size) def sleep(self): print("the animal named " + self.name + " is sleeping") def eat(s...
import sys # Step 1: find and count word pair pairs = list() for line in sys.stdin: # strip line, break into words line = line.strip() words = line.split(" ") if len(words) < 2: continue ## iterate to end of list for i in range(len(words) - 1): pair = words[i: i+2] pair...
password = 'a12345' x = 0 while x < 3: psw = input('请输入密码: ') if psw == password: print('登入成功') break else: x = x + 1 y = 3 -x print('密码错误') if x < 3: print('密码错误,请重新输入,还有', y,'次机会') else: print('没有机会了,您的账户被锁住了!')
import numpy as np from ..layers.convolutional import Convolutional from ..layers.dense import Dense from src.loss import softmax_loss class ThreeLayerConvNet(object): """ A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The netw...
# -*- coding: utf-8 -*- """ about: scikit-learn toy data sets (regression) author: jubran akram """ from sklearn.datasets import make_blobs def print_horizontal_line(line_string='---', string_reps=10): print(line_string*string_reps) if __name__ == '__main__': # parameters params = {'n_samples': 500,...
#program to find area of circle in Python using math file import math r = float(input("Enter the radius of the circle: ")) area = math.pi* r * r print("%.2f" %area) print ("--------------------------------------------------") #program to find area of circle in Python using π PI = 3.14 r = float(input("Enter...
"""Author - Anantvir Singh, concept reference:= CLRS Page 695""" #-------------- Floyd-Warshall-Running Time = O(V^3)------------------------- #---------------->>>>>>> Main Idea <<<<<<------------------------------ # Here in each iteration, we add a vertex to the # The Floyd-Warshall algorithm relies on the followi...
import sqlite3 import json import pandas as pd def main(): conn = sqlite3.connect("movie_db.db") cursor = conn.cursor() df = pd.read_csv('mini_metadata.csv') # print(df.genres) # for i in range() idx = 0 # print(df.columns) for i in df.iterrows(): if df['genres'][idx] == "[]": pass else: genre_data...
def time_conversion(time_seconds): """Converts time in seconds to hours, minutes and seconds Parameters ---------- time_seconds : int Time in seconds Returns ------- tuple Tuple (hours, minutes, seconds) """ hours, remainder = divmod(time_seconds, 3600) minutes,...
name = str(input("Hello, what's your name? ")) age = int(input("How old are you?")) print(f'Hello {name}, you will be 100 in the year {2020+(100-age)}')
option = ['rock','paper','scissors'] first = str(input("Player 1. rock, paper or scissors? ")).lower() second = str(input("Player 2. Rock, Paper or Scissors? ")).lower() a = option.index(first) b = option.index(second) results=[['Draw', 'P2 Win', 'P1 Win'],['P1 Win', 'Draw','P2 Win'],['P2 Win','P1 Win','Draw']] pr...
#import modules import pygame from pygame.locals import * import numpy as np import random pygame.init() screen_height = 300 screen_width = 300 line_width = 6 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Tic Tac Toe') #define colours red = (255, 0, 0) gr...
from src.abstractsort import AbstractSort class BubbleSort(AbstractSort): def __init__(self): super().__init__() self.sort_method_name = 'Bubble sort' def get_numbers_list(self, numbers: list): print('I should get numbers list here ', numbers) self.numbers = numbers def ...
print(".:: Program Luas Segitiga ::.") pil = True while (pil == True): try: alas = input('Alas : ') alas = float(alas) if alas < 0: raise AssertionError() except ValueError: print("Nilai yang anda masukkan bukan berupa angka, nilai 1 akan dimasukkan sebaga...
def faktorial(nilai): hasil=1 for i in range(nilai): print(f'{nilai-i}', end='') hasil+=hasil*(nilai-i) if i==nilai-1: print(f' = {hasil}') else: print(end=' x ') faktorial(int(input('\nMasukkan Angka : ')))
# -*- coding: utf-8 -*- """ Created on Tue Aug 13 19:53:22 2013 @author: heather """ class MortgageCalculator(): P = 0; i = 0; N = 0; def __init__(self, P, i, N): self.P = P self.i = i / 12.0 self.N = N def calculate(self, P, i, N): retu...
from spellchecker import SpellChecker spell = SpellChecker(language='de') string = "blinken nachricht sichtbar ref 0zid blinken empfangslampe tc0 einschalten ton persönlich karte nachsehen aktuell nachrichten manager herrn steinegger passieren erhalten nachrichten jahren tc0 melden gelb karte richtig situation anschau...
from turtle import Turtle class Ball(Turtle): def __init__(self): super().__init__("circle") self.color("white") self.penup() self.xMove = 10 self.yMove = 10 self.theMoveSpeed = 0.04 def move(self): theX = self.xcor() + self.xMove theY = self.yc...
##The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); ##so the first ten triangle numbers are: ##1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... ##By converting each letter in a word to a number corresponding to ##its alphabetical position and adding these values we form a word value. ##For example, th...
##2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. ##What is the sum of the digits of the number 2^1000? x = str(2**1000) targetsum = 0 for i in x: targetsum = targetsum + int(i) print targetsum
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 25 12:02:47 2021 @author: ab2018 """ #Print the first 10 positive integers using a while loop i = 1 while i <=10 : print(i) i += 1 #have to put the increments of the loop i+=1 otherwise loop will continue
import turtle import math import random import swarm class Position : # A data structure to conveniently hold an x,y position def __init__(self, x, y): self.x = x self.y = y # Made use of operator overlading for the purposes of determining if an object is in bounds def __gt__(self, other...
class Element(): def __init__(self, name, symbol, number): self.name = name self.symbol = symbol self.number = number # 6.6 def dump(self): print('name: {}, symbol: {}, number: {}'.format(self.name, self.symbol, self.number)) example = Element('Hydrogen', 'H', 1) # 6.5 di...
from tkinter import * import pygame.mixer def play_correct_sound(): num_good.set(num_good.get() + 1) correct_s.play() def play_wrong_sound(): num_bad.set(num_bad.get() + 1) wrong_s.play() # Create a tkinter application window called "app" app = Tk() # Give the window a name app.title("TVN Game Sho...
''' Average least common multiple The function lcm(a,b) denotes the least common multiple of a and b. Let A(n) be the average of the values of lcm(n,i) for 1<=i<=n. E.g: A(2)=(2+2)/2=2 and A(10)=(10+10+30+20+10+30+70+40+90+10)/10=32. Let S(n) = SUM A(k) for 1<=k<=n. S(100)=122726. Find S(99999999019) mod 999999017. ...
''' Highly divisible triangular number The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: ...
import random print('-'*30) #=============================================================================== # ARGS & KWARGS #=============================================================================== def print_args(p, *args): print('param: ', p, '\nargs: ',) for a in args: print(a,) print_args("ciao", ...
# Important functions of List: n=[1,2,2,2,2,3,3] print(len(n)) print(n.count(1)) print(n.count(2)) print(n.count(3)) print(n.count(4)) print(n.index(1)) print(n.index(2)) print(n.index(3))
# wap to print elements from the list1) list=eval(input("Enter List:")) for x in list : print(x)
# display odd no from 10 to 1 in desc order for x in range(10,0,-1): if(x%2 != 0): print(x)
from turtle import Screen from net import Net from paddle import Paddle from ball import Ball from scoreboard import Scoreboard from time import sleep screen = Screen() screen.setup(height=600, width=800) screen.bgcolor("black") screen.title("Pong") screen.tracer(0) net = Net() red_paddle = Paddle(350, "red") blue_pa...
def print_prime(n): for i in range(n+1): if prime(i) is True: print i def prime(n): if n == 0: return False elif n == 1: return False else: j = 2 while j < n: if n % j == 0: return False else: j...
def number_needed(a, b): hash_a = {} hash_b = {} num_needed = 0 for x in a: if x in hash_a: hash_a[x] = hash_a[x] + 1 else: hash_a[x] = 1 for x in b: if x in hash_b: hash_b[x] = hash_b[x] + 1 else: hash_b[x] = 1 for ...
# STAT/CS 287 # HW 01 # # Name: Michael Arnold # Date: 09-12-18 import numpy as np import matplotlib.pyplot as plt from problem2_mvarnold import coin_flip def dependent_coin_flip(p, q1, q2): """ returns a tuple representing the flip outcomes of two coins with the probablities of the second depend on the first...
contador=1 suma_numeros=0 while(contador<=10): numero=int(input(f"Ingrese el valor de la Posicion {contador} :")) suma_numeros=suma_numeros+numero contador=contador+1 print(f"La suma de los 10 numeros es: {suma_numeros}")
__author__ = "Raymond Gee" # Your name __credits__ = [""] # Your list of helpers __email__ = "geern@mail.uc.edu" # Your email address def sprout_leaves(t,vals): """Sprout new leaves containing the data in vals at each of the deepest leaf in the original tree t and return the resulting tree. >>> t1 = tree(1,...
"""HW01.py: Egyptian Greedy Algorithm""" __author__ = "James Garrett" __credits__ = ["Joe Snider"] __email__ = "garretjb@mail.uc.edu" import math from fractions import Fraction #Function def greedy(num): result = [] while num.numerator != 1: if num.numerator == 1: #if numerator is 1, code is done ...
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) uniqueLists = {} def Unique(listText): ...
#!usr/bin/env python class Animal: def __init__(self, name=None): self.name = name def bark(self): return f'{self.name} barks.' if self.name else 'My animal barks.' def poop(self): return f'{self.name} poops.' if self.name else 'My animal poops.' class Dog: d...
#!usr/bin/python import tkinter as tk lastX, lastY, size = 0, 0, 3 colour = "black" def store_position(event): global lastX, lastY lastY = event.y lastX = event.x def on_click(event): store_position(event) def on_drag(event): global size canvas.create_line(lastX, lastY, event.x, event.y...
# Project 3: GEARS Robot # File: build_maze.py # Date: 3/14/21 # By: Alex Wiseman # ajwisema # Ben Chappell # chappeb # Trevor Moorman # tmoorma # Cole Kingery # ckinger # Section: 5 # Team: 70 # # ELECTRONIC SIGNATURE # Ben Chappell # Cole Kingery # Trevor Moorman # Alex Wiseman # # The electronic signatures above in...
LINES = [] with open('input.txt') as f: for fl in f: LINES.append('(' + fl.strip() + ')') def extract_brackets(l): i_start = 0 for i_stop in range(1, len(l)): if l[i_stop] == ')': a = '' if i_start == 0 else l[0:i_start] b = l[i_start+1:i_stop] c = '' if ...
with open('input.txt') as f: input = f.readline() input = input.strip().split('-') input_min = int(input[0]) input_max = int(input[1]) def pwd_to_digits(pwd): digits = [] pwd_str = str(pwd) while len(pwd_str) > 0: digits.append(int(pwd_str[0])) pwd_str = pwd_str[1:] return digi...
#!/usr/bin/env python3 from collections import defaultdict, deque def number_at_turn(target, start): start = list(map(int, start.split(","))) turn = 1 number = None last_number = None last_spoken = defaultdict(lambda: deque([], 2)) while turn <= target: if start: number, sta...
# -*- coding:utf-8 -*- from Fibonacci import * class Problem2(object): def __init__(self,first,second): self.__first = first self.__second = second self.__answer = 0 def SumOfEvenValue(self,maxValue): self.__maxValue = maxValue self.__fib = Fibonacci(self.__first,self.__...
with open('formula.txt', encoding='utf8')as f: formula = f.read().rstrip() def parser(formula): for num in range(len(formula)): if formula[num] == '/': print(formula[:num], formula[num + 1:]) return division(formula[:num], parser(formula[num + 1:])) elif formula[num] ==...
from config import punc_table, stemmer, nltk, stop_words #tokenize and clean a string. Lower case it, remove punctuation, remove non-alphanumeric tokens, and remove stop-words def cleanWord(word): word = word.lower() #lowercase wor...
import collections as co arr = [] check_row = [] small_arr = [] new_arr = [] result = True for i in range(9): temp = list(map(int, input().split())) arr.append(temp) transpose_arr = [[arr[j][i] for j in range(len(arr))] for i in range(len(arr[0]))] # def split_matrix(arr): # start # for i in range...
from pytree.binary_search_tree import BinarySearchTree mytree = BinarySearchTree() mytree[3] = "red" mytree[1] = "blue" mytree[6] = "yellow" mytree[2] = "at" print(mytree[7]) #print(mytree.delete_node(4)) mytree.print_in_order() mytree.print_pre_order() mytree.print_post_order() newtree = BinarySearchTree(...
#!/usr/bin/env python # read text files and plot them import matplotlib.pyplot as plt import numpy as np import sys # data file to read given as argument if len(sys.argv) < 2: print "Give the name of the file to read as an argument\n" exit() file = np.loadtxt(sys.argv[1] ,skiprows=1) time = file[:,0] force = fil...
#1. Crear un nuevo repositorio #2. Tomar de base el programa de la clase pasada #3. Vamos a modificar el programa para que solo tome como válidos números entre 1 y 120 # (si pone un número entre -inf y 0 o 121 a inf debe volver a preguntar) #3. Al inicio del programa preguntar cuantas personas registrar #4. Hacer que e...
""" Hackathon - Level 6 """ alphabet = "abcdefghijklmnopqrstuvwxyz" def cipher(str, x): return "".join([alphabet[(alphabet.index(s)+x)%26] for s in str]) if __name__ == '__main__': # Add any code to test your solution here # As per the example, this should return salve print(cipher('pxisb', 3))
#cau 6 x = input("Nhap chuoi: ") print("Chuoi in hoa: ", x.upper()) print("-------------------------") #cau 9 s = 0 for i in range (1, 21): s = s + i print("Tong 20 so tu nhien dau tien: ", s)
print("hello world") # input() will return a str answer = input("enter your name: ") # format input to int age = int(input("enter your age: ")) print(age) print(answer) # string formatting print("hello %s %d %d" %(answer, 1, 2)) # %s %d %f #string literal - precede with 'f', use {} with variable name print(f"hello, ...
#!/usr/bin/python3 class MethodNode(object): def __init__(self, name, return_type): self.name = name self.return_type = return_type self.isPublic = False def __str__(self): symbol = "-" if self.isPublic: symbol = "+" return "{} {}() : {}\\l".format(...
def in1(): return (set([int(x) for x in raw_input().split(" ")])) n=int(raw_input()); st1=set([int(x) for x in raw_input().split(" ")]); m=int(raw_input()); for i in range(2*m): li= [raw_input().split(" ")]; if(li[0]=="intersection_update"): st2=in1() st1.intersection_update(st2); #p...
def swap_case(s): r= "" for i in s: if(i.islower()): r+=i.upper(); elif(i.isupper()): r+=i.lower() return r str1=raw_input(); print(swap_case(str1));
User = input('Hello! Would you please tell your name?: ') print('Good day, Sir/Maam'+ User +'!') import os R = 0.0821 #Ideal Gas Constant in L*atm/mol*k def converter(Pressure): #Conversion of all Pressure Values into Atmospheric units (atm) atm = Pressure.find('atm') KPa = Pressure.find('KPa') mmHg ...
def not_divisible(num, primes): for prime in primes: if suggest_number % prime == 0: return False return True n_th = 10_001 primes = [2] suggest_number = 1 while True: suggest_number += 2 # 既に約数に含まれていなければ、それを次の素数とする if not_divisible(suggest_number, primes): primes.appen...
def gcdRecur(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' if b == 0: return a else: return gcdRecur(b, a%b) a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) print("GCD of "+str(a)...
def genFib(): fib_1 = 1 # fib(n-1) fib_2 = 0 # fib(n-2) while True: nextFib = fib_1 + fib_2 yield nextFib fib_2 = fib_1 fib_1 = nextFib newfib = genFib() newfib.__next__() newfib.__next__() newfib.__next__() newfib.__next__() # Every time __next__() is called, it runs until...
N =int(input()) maxsum=0 cur=0 for i in range(N): cur+=int(input()) if cur>maxsum: maxsum=cur if cur<0: cur=0 print(maxsum)
import json from difflib import SequenceMatcher from difflib import get_close_matches dict = json.load(open("dict.json")) def strip_def(w): out = "" for e in w: out += e + '\n' return out def define(w): w = w.lower() if w in dict: return strip_def(dict[w]) elif w.title() in di...
def list_part(lst, split_parts, *, start=None, end=None): """ Return a part of list or tuple :param lst: list :param split_parts: number of parts for dividing lst :param start: :param end: :return: list """ if start is not None: if start < 0 or start > split_parts: ...
a = "HelloWorld!" b = 3 c = -11 print(a) print(b) print(c) print(b+c) print(a,b,c) print("HelloWorld") f = 4 g = 6 print(f + g)
def pre_flop_strength_1(): # Sklansky hand groups: lower group value means better ranking of cards # "http://www.thepokerbank.com/strategy/basic/starting-hand-selection/sklansky-groups/" ranks = "23456789TJQKA" suits = "cdhs" # input hand for evaluation hand = input('Enter the hand:').split()...
class Stack(): def __init__(self,x): self.itens=[""]*x self.top=-1 def push(self,x): self.top+=1 self.itens[self.top]=x def is_empty(self): if self.top==-1: return True return False def pop(self): if not self.is_empty(): ...
def fatorial(n): if n==1 or n==0: return 1 else: return n*fatorial(n-1) N=int(input()) while N!=-1: print(fatorial(N)) N=int(input())
class No(object): def __init__(_self_,Key=None,Next=None): _self_.Key=Key _self_.Next=Next class L(object): pass def __Init__(_self_,Nil=None): _self_.Nil=Nil def Insert(_self_,y): x=_self_.Nil.Next while x.Next!=None: x=x.Next x.Next=No(y) ...
n1=int(input()) n2=int(input()) print("O resultado da soma entre %d e %d = %d"%(n1,n2,(n1+n2)))
""" Help function for making predictions """ import numpy as np def get_chunks(iterable, chunk_size): """ Generator that divides an iterable into chunks Args: iterable: iterable chunk_size: size of each chunk as an integer Returns: iterable in chunks """ size = iterable.shape...
""" Author: iLoveTux Date: 06/04/14 purpose: to provide a class which abstracts away handling of current timestamps. usage: >>> from timestamp import Timestamp >>> timestamp = Timestamp() >>> print timestamp Wednesday June 04, 17:51:59 >>> print timestamp.epoch 1401918719 >>> print timestamp.timestamp 201406...
# Make regression predictions using the trained MLP regression model from trainNet.py # Dylan Greene (dgreene2) import numpy as np import pickle from pybrain.datasets import SupervisedDataSet from pybrain.structure.networks import FeedForwardNetwork import math if __name__ == '__main__': # Load and prepare the te...
# coding: utf-8 ## Edge Detection with skimage # This tutorial illustrates edge detection with Python's skimage commands ### import packages # In[9]: get_ipython().magic(u'matplotlib inline') import numpy as np import matplotlib.pyplot as plt #import matplotlib.image as img from PIL import Image from skimage.dat...
import numpy as np import matplotlib.pyplot as plt from matplotlib import rcParams rcParams['font.family'] = 'serif' rcParams['font.size'] = 16 # PHYSICAL PARAMETERS # h --> the altitude of the rocket ms = 50 # mass of the rocket shell (kg) mpo = 100 # mass of the rocket propellant at time t=0 (kg) ve = 325 # exh...
import heapq class Sort: def bubble_sort(self, items): """ Implementation of bubble sort """ for i in range(len(items)): for j in range(len(items)-1-i): if items[j] > items[j+1]: items[j], items[j+1] = items[j+1], items[j] # Swap! def inserti...
############ Logitech F310 Gamepad Controller GUI - gui_main.py ########## # Original Author: John Zeller # Description: GUI_Main displays the values being stored in the states # python dictionary in a very simple labeled Tkinter GUI # to make them easily viewable. import Tkinter as tk # Native Python GU...
weight_lbs = input("Weight lbs: ") weight_kg = int(weight_lbs)*0.45 print (weight_kg)
# problem : 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, find the sum of the even-value...
import cv2 def convert_image(original_img, source_format, destination_format): """ Change image color format given source color (RGB, BGR) and destination_format:destination color (RGB, HSV, GRAY) """ key = (source_format.upper(), destination_format.upper()) converting_codes = { ("RGB"...
""" Merge two dict """ from common import * import pprint import util def merge_recurse_inplace(d1, d2, clstype=None): """ Merge small dict to large dict recursive manner """ if (isinstance(d1, dict) or (clstype and isinstance(d1, clstype))) \ and isinstance(d2, dict): for key in d2.keys...
import math a, b, c = map(int, input().split()) def d(a, b, c) -> float: return def area(a, b, c) -> float: return 0.5 * a * b * math.sin(math.radians(c)) def length(a, b, c) -> float: tmp = (a ** 2 + b ** 2 - 2 * a * b * math.cos(math.radians(c))) ** 0.5 return a + b + tmp def height(a, b, c) -> f...
# 参照: https://onlinejudge.u-aizu.ac.jp/solutions/problem/ALDS1_7_C/review/1680736/bs5lNkJ/Python3 class BinaryTree: class Node: def __init__(self, num, left_child, right_child): self.num = num self.left_child = left_child self.right_child = right_child d...
class BinarySearchTree: def __init__(self): self.root = None def print_inorder(self): def _print_inorder(node): if node: _print_inorder(node.left) print(' {0}'.format(node.key), end = '') _print_inorder(node.right) _print_inord...
def insertionSort(n, arr): for i in range(n): v = arr[i] j = i - 1 while j >= 0 and arr[j] > v: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = v print(" ".join([str(x) for x in arr])) return n = int(input()) arr = list(map(int, input().split())) insertio...
# def isPrime(num): # if num <= 1: # return False # for i in range(2, num - 1): # if num % i == 0: # return False # return True def isPrime(num): if num == 2: return True elif num <= 1 or num % 2 == 0: return False else: next for i in ra...
from queue_l.queue_link import Queue class DiGraph(object): '''有向图''' def __init__(self, v): # 顶点数目 self.v = v # 边的数量 self.e = 0 # 邻接表 self.adj = [Queue() for i in range(v)] def get_v(self): '''获取顶点数目''' return self.v def get_e(self): ...
""" The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) ...
n, sum = 0, 0 while (n < 1000): if (n % 3 == 0) or (n % 5 == 0): sum += n n += 1 print(sum)
# -*- coding: UTF-8 -*- # Use Python 2.x to run this script """ Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabet...
from dataclasses import dataclass from db import Database import json BOARD_WIDTH=7 BOARD_HEIGHT=7 MARKS_FOR_WIN=4 """Movements to check winner""" INCREASES=[ {"increase_x":1,"increase_y":1}, {"increase_x":1,"increase_y":-1}, {"increase_x":1,"increase_y":0}, {"increase_x":0,"increase_y":1} ] @da...
def check_pt_1(input_number): test = str(input_number) for digit in range(1, len(test)): if int(test[digit]) < int(test[digit - 1]): return False if len(set(test)) == len(test): return False return True def check_pt_2(input_number): test = str(input_number) for digi...
from copy import copy def calculate_sum_total_of_memory_pt_1(input_memory): # this function works with bit masking, where the mask overwrites the value at each memory location # with wildcard values marked by X # eg mask of 0XX1 on value 1010 would give a value of 0011 # the requirement is that we ad...
import sys import tkinter from tkinter import * from app import App from tkinter import scrolledtext class RedirectText(object): def __init__(self, text_ctrl): self.output = text_ctrl def write(self, string): self.output.insert(tkinter.END, string) # Window config window = Tk() window.titl...