text
stringlengths
37
1.41M
import time print(ch06.module.time()) # 1970년 1월 1일 자정 이후를 초로 환산 print(time.localtime()) print(time.ctime()) # 날짜와 시간 요일 표시 print(time.strftime('%x', time.localtime())) print(time.strftime('%c', time.localtime())) # time.sleep(1) : 1초간 대기 : # 파이썬에서는 1초를 1로 표기 for i in range(1, 11): print(i) time.sleep(1)
# test03 # 1번 a = "Life is too short, you need python" if "wife" in a: print("wife") elif "python" in a and "you" not in a: print("python") elif "shirt" not in a: print("shirt") elif "need" in a: print("need") else: print("none") # 2번 result = 0 i = 1 while i <= 1000: if i % 3 == 0: result += i i += 1...
# 윈도우(폼) 만들기 from tkinter import * root = Tk() # Tk()클래스의 객체 생성 root.title("window") root.geometry("200x100+300+400") # width x height + x좌표 + y좌표 frame = Frame(root) # root 위에 위치하는 프레임 객체 frame.pack() # 레이아웃 담당하는 메서드 # 문자열 출력 - Label 클래스 Label(frame, text = "Hello Python").grid(row=0, column=0) # 버튼 클래스 Button(fra...
# 학생 클래스 생성과 사용 class Student: def __init__(self, sid, name): self.__sid = sid #학번 self.__name = name def getsid(self): return self.__sid def getname(self): return self.__name s1 = Student(1001, '김산') print(s1.getsid(), s1.getname()) s2 = Student(1002, '이강') print(s2.get...
import random # 주사위 10번 던지기 ''' for i in range(10): dice = random.randint(1, 6) print(dice) print('='*40) ''' # 리스트에서 랜덤하게 단어 추출하기 word = ['sky', 'moon', 'space', 'earth'] w = random.choice(word) print(w)
# mydb에 member 테이블 생성 # db프로세스 # 1. db에 연결 # 2. 테이블 생성 from libs.db.dbconn import getconn def create_table(): conn = getconn() # dbconn 모듈에서 getconn 호출(객체 생성) cur = conn.cursor() # db 작업을 하는 객체(cur) # 테이블 생성 - sql 언어 DDL sql = """ create table member( mem_num int primary key, ...
# -*- coding: utf-8 -*- def combine(str1, str2): ans = "" #i = 0 str_len = max(len(str1), len(str2)) for i in range(0, str_len): ans = ans + str1[i:i+1] + str2[i:i+1] #ans = ans + str[str_len:] return ans print combine("cat","dog")
# Read in number of test cases. t = int(input()) # For each test case. for _ in range(t): # Read the number of zucchinis. n = int(input()) # Grab the heights of each zucchini in a list. heights = list(map(int, input().split(" "))) # Build our other list and initialize to False. We use two extra i...
def chess(n : int) -> int: if n == 0: return 1 return chess(n-1)*2 print(chess(4)) def sum_total(n : int) -> int: if n == 0: return 1 return sum_total(n - 1) + chess(n) print(sum_total(4))
# -*- coding: utf-8 -*- # @Time : 2018/9/5 08:37 # @Author : yunfan class MyStack: """ ONLY CAN USE APPEND AND POP(0), Time COMPE IS TOO HIGHT """ def __init__(self): """ Initialize your data structure here. """ self._a = [] def push(self, x): """ ...
class Solution: def addOperators(self, num, target): def dfs(ops): res = [] for op in ops: res.append(op + ['-']) res.append(op + ['+']) res.append(op + ['*']) res.append(op + ['']) return res def ch...
# -*- coding: utf-8 -*- # @Time : 2018/8/31 14:04 # @Author : yunfan class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ l = -1 for i in range(len(nums)): ...
# -*- coding: utf-8 -*- # @Time : 2018/9/5 08:48 # @Author : yunfan ''' Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1. Example 1: Input: 0 0 0 0 1 0 0 0 0 Output: 0 0 0 0 1 0 0 0 0 Example 2: Input: 0 0 0 0 1 0 1 1 1 Output: 0 ...
# -*- coding: utf-8 -*- # @Time : 2018/8/29 10:50 # @Author : yunfan """ Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: ...
# -*- coding: utf-8 -*- # @Time : 2018/8/29 16:50 # @Author : # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def _lenght_make_circle(self, head): node = head res = 1 while no...
# -*- coding: utf-8 -*- # @Time : 2018/6/28 18:13 # @Author : yunfan """ Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. Example 1: Input: "aba" Output: True Example 2: Input: "abca" Output: True Explanation: You could delete the character 'c'. """ c...
# -*- coding: utf-8 -*- # @Time : 2018/9/2 14:25 # @Author : yunfan ''' An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535). Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value ne...
''' The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth term of the cou...
while True: try: w = int(input()) if w % 2 == 0: if w > 2: print("YES") continue print("NO") except EOFError: exit()
def sum(): sum = 0 for n in range(1,101): sum = sum + n return sum print(sum()
# Damien Connolly G00340321 # Project for Applied Databases # Lecturer: Gerard Harrison # Code for this project adapted from lectures and examples @ https://learnonline.gmit.ie/course/view.php?id=2564 # Import MySQL and Mongo to connect to database and call functions import mysql import mongo # Main function def main...
# solve linear equation using Python x= 10-500+79 print(x) # for a second degree equation, use quadratic formula ax squared + bx+c = 0 # quadratic formula #x1 and then x2 = -b + square root of b squared minus ac, everything divided by 2a a = 1 b = 2 c = 1 D = ( b**2 - 4*a*c)**0.5 # now evaluate x1 and x2 x_1= (-b...
''' dispersion - tells us how far away the numbers in a data set are from the mean of the data set ''' # three methods of dispersion: range, variance, standard deviation ''' Finding the range of a set of numbers The range shows the difference between the highest and the lowest number ''' # find the range def find_r...
class Person: def __init__(self, name, age): self.name=name self.age=age def details(self): print(self.name, self.age) person_list = [] for i in range(0,5): person = Person("person"+ str(i), 30+i) person_list += [person] for i in person_list: i.details()
class Math: def __init__(self, x, y): self.x = x self.y =y def sum(self): return self.x + self.y class Mathextend(Math): def __init__(self, x, y): super().__init__(x, y) def subtract(self): return self.x - self.y math_obj = Mathextend(5,2) print(math_obj.subtract())
#!/usr/bin/env python3 import random from utils import write from block_at_three import * def offense_next_to(x, y, map, check) : pos_x = x - 1 while pos_x < x + 2: pos_y = y - 1 while pos_y < y + 2 : if pos_x == x and pos_y == y or pos_x > 19 or pos_y > 19 or pos_x < 0 or pos_y < 0...
from sys import argv script, file_name = argv text = open(file_name, encoding = 'utf-8') print(f"file {file_name}'s contents :") print(text.read()) text.close() print("Type the file name once again.") file_again = input("> ") text_again = open(file_again) print(text_again.read()) text_again.close()
from sys import argv script, user_name = argv prompt = 'Your anwser is... ' print(f"Hello {user_name}, I'm {script} script.") print("I'd like to ask you a few questions.") print(f"Do you like me, {user_name}?") likes = input(prompt) print(f"Where do you live, {user_name}?") lives = input(prompt) print("What kind of...
#-*-coding:utf-8-*-2:wq # Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str ...
#!/usr/bin/env python # encoding: utf-8 """ Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. """ # python 位...
#!/usr/bin/env python # encoding: utf-8 """ Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For example, If n = 4 and k = 2, a solution is: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] """ class Solution(object): def combine(self, n, k): """ ...
#!/usr/bin/env python # encoding: utf-8 """ Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. For example: Given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. Note: The order of the result is not ...
#-*-coding:utf-8-*- """ Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target) will be positive integers. Elements in a ...
#Write a function to find the longest common prefix string amongst an array of strings. class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) < 1: return ""; elif len(strs) == 1: ret...
#!/usr/bin/env python # encoding: utf-8 """ Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a time Each intermediate word must exist in the word list For example, Given: ...
#!/usr/bin/env python # encoding: utf-8 """ Sort a linked list using insertion sort. """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # 不满足题意,但是快 class Solution(object): def insertionSortList(self, head): r...
#!/usr/bin/env python # encoding: utf-8 """ Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. For example: Given a...
#!/usr/bin/env python # encoding: utf-8 """ Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engag...
#!/usr/bin/env python # encoding: utf-8 """ Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example, Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return [1,2,3,6,9,8,7,4,5]. """ class Solution(object): def spiral...
""" Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. """ class Solution(object): def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do n...
#!/usr/bin/env python # encoding: utf-8 """ Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaini...
#-*-coding:utf-8-*- """ Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. 罗马数字是阿拉伯数字传入之前使用的一种数码。罗马数字采用七个罗马字母作数字、即Ⅰ(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)。记数的方法: 相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3; 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12; 小的数字(限于 Ⅰ、X 和 C)在大的数字的...
#!/usr/bin/env python # encoding: utf-8 """ Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time complexity. """ class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int """ def getn(x, ...
#!/usr/bin/env python # encoding: utf-8 """ Given an array of integers, every element appears twice except for one. Find that single one. """ # Xor 的用法,一次过 class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ re = 0 for ...
""" The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence. Note: The sequence of integers will be represen...
#!/usr/bin/env python # encoding: utf-8 """ Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Some examples: ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) ...
#!/usr/bin/env python # encoding: utf-8 """ The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to ...
""" Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # bug1: [[1,1,2],[1,2,2]]返回了第一个,没有合并: class Solution(object): def ...
#!/usr/bin/env python # encoding: utf-8 """ Implement a basic calculator to evaluate a simple expression string. The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . You may assume that the given expression is always valid. Some ex...
#!/usr/bin/env python # encoding: utf-8 """ Follow up for "Search in Rotated Sorted Array": What if duplicates are allowed? Would this affect the run-time complexity? How and why? Write a function to determine if a given target is in the array. """ # 看网上答案,9次过 class Solution(object): def search(self, nums, ...
#!/usr/bin/env python # encoding: utf-8 """ Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. For example: Given n = 13, Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. """ # 13次过,递归没有考虑请 class Solution(object): ...
#!/usr/bin/env python # encoding: utf-8 """ All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. Write a function to find all the 10-letter-long sequences (substrings) that occu...
#!/usr/bin/env python # encoding: utf-8 """ Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return a string instead of an integer. """ # 提交12次,各种...
# -*- coding: utf-8 -*- roomList = { "livingRoom", "masterBedroom", # "secondBedroom", # "thirdBedroom", "bathroom", "kitchen", "diningRoom", "studyRoom" } width = 30 height = 30 from houses import house # myHouse = house(roomList, width, height) # myHouse.printHouseInfo() from human import human # clas...
# Print message for user. print("What is your name?") # Take user name as input name = input() print(f"hello, {name}")
#skip by twos #use slices number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def oddnumber(number): odds = number[0:11:2] return odds print oddnumber(number)
a, b, c, d = 0, 0, 0, 0 x = input("please Enter Your Password: ") if len(x) >= 6 : for i in x: if i.islower(): a+=1 elif i.isupper(): b+=1 elif i.isdigit(): c+=1 elif(i=='@'or i=='$' or i=='_'or i=="!" or i=="%" or i=="^" or i=="&" or i=="*" or i=="(" or i==")" or i=="-" or i=="+"): ...
x=list(input("Pleas Enter your list fo data: ").split()) x.sort() print("Your Max is :",x[0]) x.reverse() print("Your Min is :",x[0])
"""[Matrix operation simulate Neural network operation]""" #Y_output = activation(X_input * Weight + bias) X = tf.Variable([[0.4, 0.2, 0.4]]) W = tf.Variable([[-0.5, -0.2], [-0.3, 0.4], [-0.5, 0.2]]) b = tf.Variable([[0.1, 0.2]]) XWb = tf.matmul(X, W) + b Y1 = tf.nn.relu(tf.matmul(X,W)...
#!/bin/python3 # -*- coding: utf-8 -*- ''' Created on 2016年2月24日 @author: qiuxiangu ''' class MyNgram(set): def __init__(self, N=0): self.N = N def split(self,string): self.str = string tmp = '' bigram = [] if self.N == 0 : bigram.append(...
# coding=utf-8 # encoding=utf8 import sys # from aetypes import end #[1] No sistema de numeração romana as cifras escrevem-se com as letras I, V, X, L, C, D e M. # Exemplo: 125 é representado por CXXV. Implemente um programa que leia um número inteiro, # caso ele esteja dentro do intervalo de 1 a 999, mostre o n...
# coding=utf-8 #PONTIFÍCIA UNIVERSIDADE CATÓLICA DO PARANÁ ESCOLA POLITÉCNICA #RACIOCÍNIO ALGORÍTMICO #PROF. HENRI FREDERICO EBERSPÄCHER #Estudante: Ricardo Varjão # PROBLEMAS LISTA 5: Selecao Composta def alg1(): #[1] A partir das informações contidas na tabela abaixo, elabore um algoritmo que leia a massa ...
# coding=utf-8 import requests import json #Uma empresa de câmbio permite a compra de dólares, libras e euros. # Elabore um algoritmo que leia o código da moeda que o cliente quer comprar e qual o # montante que ele quer adquirir nessa moeda. Mostre então quanto ele deverá pagar em reais # para concretizar a ...
from Tkinter import * #0 root=Tk() #1 root.title("demo") #2 l=Label(root, text="Hello World", width=20) #3 l.pack() #4 root.mainloop() #5 """ Step 0 : Import classes from Tkinter module Step 1 : Create a tk root widget. This is created in almost a...
ac=int(input("Dati anul curent:")) bc=int(input("Dati luna curenta:")) cc=int(input("Dati ziua curenta:")) an=int(input("Dati anul nasterii:")) bn=int(input("Dati luna nasterii:")) cn=int(input("Dati ziua nasterii:")) if bn>bc: print((ac-an)-1,"ani") elif(bn==bc): if( cc==cn or cc>cn): print(a...
a=int(input("Dati prima varsta:")) b=int(input("Dati a doua varsta:")) c=int(input("Dati a treia varsta:")) if((a>18) and (a<60)): print(a) if((b>18) and (b<60)): print(b) if((c>18) and (c<60)): print(c) else: print("Nimeni nu are varsta cuprinsa intre 18-60 ani")
from flask import Flask, redirect, url_for, render_template app = Flask(__name__) @app.route('/') def index(): return "There's nothing here. Try '/hardcoded', '/first_template', or '/second_template/<name>'" # Below you see an example of hardcoding: programming without the possibility # of any variability. This HT...
#python3 from time import sleep from random import choice palavras = ['hello word','dinheiro','vida','complexidade','inferior','gta','comida'] pontos = 0 jogas = 0 while True: jogas += 1 ale = choice(palavras) print(20 * '-') print(ale) print(20 * '-') pergunta = input('PALAVRA: ') if pergunta == ale: pr...
import sqlite3 conn = sqlite3.connect('films.db') c = conn.cursor() def CREATE_TABLES(): c.executescript('''/* Delete the tables if they already exist */ drop table if exists Movie; drop table if exists Reviewer; drop table if exists Rating; /* Create the schema for our tables */ ...
import math def dynamic(money,coins): table=[] # table list for maintaining the results for reusing newValue = money + 1 for x in range(newValue): table.append(0) # appends 0 to table list table[0] = [] # creates list at 0th index of table for i in range(1, newValue): for j in coins...
# encoding UTF-8 # Autor: Jaime Orlando López Ramos, A01374696 # Descripción: Un programa que lea el radio de una esfera y calcue diámetro, área y volumen para luego imprimirlos # Crear una función que calcule el diámetro tomando el radio como parámetro, multiplicando el radio por 2 def calcularDiametro(radio): d...
import numpy as np import matplotlib.pyplot as plt from util import get_data X,Y = get_data() label = ['Anger', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral'] def main(): while True: for n in range(7): x,y = X[Y==n],Y[Y==n] N =len(y) i = np.random.choice(N) plt.imshow(x[i].reshape(48,48),...
#In this game, we roll two dice and the player guesses whether the resulting number will be odd or even. For example, if the first die scores 1 and the second die scores 2, the total score is 3 (odd). #import packages - random import random #create a list of possible numbers (let's make it two lists - imagine there a...
# input nums = [[1,2,3],[3,4,5]] r = 3 c = 2 # algorithm row = len(nums) col = len(nums[0]) m = [] mat = [] if r*c != row*col: print(nums) else: for i in range(row): m += nums[i] for i in range(r): mat.append(m[c*i:c*i+c]) print(mat)
nums = [1,3,4,5] target = 6 i,l = 0,len(nums) # if target not in nums: # i = 0 if target<nums[0] else l # else: # while target > nums[i]: # i += 1 while i < l and target > nums[i]: i += 1 print(i)
def repeat_until_valid(input_prompt, *valid_values, case_insensitive=True, output_change_case=True): choice, raw_choice = '', '' compare_values = valid_values invalid_choice = True if case_insensitive: compare_values = {str(v).lower() for v in valid_values} while invalid_choice: raw...
def shorten(package_name: str, max_length: int, level: int = 1) -> str: """ Shorten package name like Convention Word in logback - but in a simpler version. Eg: package.name.class.Function will be shorten to p.n.c.Function @param package_name: name of package to shorten @param max_length: max l...
# -*- coding: utf-8 -*- """ Created on Wed Apr 3 08:21:14 2019 @author: rasik """ def findDuplicate(A): arr = {} for e in A: if e not in arr: arr[e]=1 else: arr[e] = arr[e]+1 duplicates = [] for e in arr: if arr[e]>1: ...
# -*- coding: utf-8 -*- """ Created on Sat Apr 13 00:57:50 2019 @author: rasik """ """ Given a length n, l, r of a string “lllmmmmmmrrr”, write a function to calculate the length m of middle sub-string where n is the length of whole string, l is the length of left sub-string, r is the length of right sub-string and...
currentYear = int(input("What year are we in now? ")) birthYear = int(input("Please enter the year in whitch you were born. ")) if birthYear > currentYear: print("You are not yet born.") exit(0) if birthYear <= 1900: print("That is too old!") exit(0) if (currentYear - birthYear) > 120: print("Yo...
#This is a variable. radius = 5 #This is a constant myConstPi = 3.14 print("The radius of the circle is", radius) print("The circumference of a circle is :", 2*myConstPi*radius) print("The circumference of crcle as an integer s:", int(2*myConstPi*radius))
""" # 查看变量类型 A = 10 print(type(A)) B = "小明" print(type(B)) # 怎一个爽字了得,根本不用可考虑类型的取值范围 C = 450000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 print(type(C)) print(type(2**32)) print(type(2**64)) print(C) """ """ # python之间不同的数据类型如何进行计算 # 在python中只要是数字型变量就可以直接计算,...
def longest_pallindrome(s): if s == s[::-1]: return len(s), s else: if len(s) > 2: left = longest_pallindrome(s[:-1]) right = longest_pallindrome(s[1:]) if left[0] > right[0]: return left else: return right ...
import random print('I am thinking of a 3-digit number. Try to guess what it is.\n\ Here are some clues:\n\ When I say: That means:\n\ Cold No digit is correct.\n\ Warm One digit is correct but in the wrong position.\n\ Hot One digit is correct and in the right posit...
import pygame; import random; class Point(): def __init__(self, x, y): self.x = x; self.y = y; def x(self): return self.x; def y(self): return self.y; class maze(pygame.sprite.Sprite): size = 1; def __init__(self): print("Maze Being Generated"); ...
from bintreeFile import Bintree def makeTree(): tree = Bintree() data = input().strip() while data != "#": tree.put(data) data = input().strip() return tree def searches(tree): findme = input().strip() while findme != "#": if findme in tree: print(findme, "f...
#A palindromic number reads the same both ways. #The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. #Find the largest palindrome made from the product of two 3-digit numbers. def is_palindrome(num): num_d = [] while num != 0: num_d.append(num%10) ...
##For a positive integer n and digits d, we define F(n, d) as the number of the divisors of n whose last digits equal d. ##For example, F(84, 4) = 3. Among the divisors of 84 (1, 2, 3, 4, 6, 7, 12, 14, 21, 28, 42, 84), three of them (4, 14, 84) have the last digit 4. ## ##We can also verify that F(12!, 12) = 11 and ...
print('Введіть дату в форматі: ХХ.ХХ.XXXX:\n') day, month, year = map(int, input().split('.')) a = ((14 - month) / 12) y = year - int(a) m = month + 12*int(a) - 2 day_number = (day + int(y) + int(y/4) - int(y/100) + int(y/400) + int((31*m) /12)) % 7 if day_number == 0: day_name = "Sunday" elif day_number == 1: ...
from IPython.display import clear_output class ROIcalc(): def __init__(self): self.income = [] self.expenses = [] self.investment = [] self.proplist = [] self.totalincome = {} self.totalexpenses = {} self.totalinvestment = {} self.ROI = {} def p...
import datetime import random class Cache: def __init__(self): # Constructor self.cache = {} self.MaxSize = 5 def empty(self): return self.cache == {} def size(self): return len(self.cache) def __contains__(self, key): return key in self.cache d...
user = int(input("Choose one level for the game:")) while user == 1: if user == 1: import random numero = random.randint(0,100) print(numero) print("Choose an integer between 0 and 99") intento_1 = int(input())
# -*- coding: utf-8 -*- class Vehicle(object): def __init__(self, vehicle_brand, vehicle_model, number_of_kilometers, date_service): self.vehicle_brand = vehicle_brand self.vehicle_model = vehicle_model self.number_of_kilometers = number_of_kilometers self.date_service = date_servic...
def subtotal_calc(c_price, a_price, t_childrem, t_adults): return (c_price * t_childrem) + (a_price * t_adults) def sales_tax_calc(subtotal, tax): return (subtotal * tax) / 100 def total_calc(subtotal, sales_tax): return subtotal + sales_tax def change_calc(payment_amout, total): return payment_am...
print('Please enter the following:\n') # inputs adjective = input('adjective: ') animal = input('animal: ') verb_1 = input('verb: ') exclamation = input('exclamation: ') verb_2 = input('verb: ') verb_3 = input('verb: ') # preparing the story finalStyory = f'The other day, I was really in trouble. It all started when ...
import random number = random.randint(1, 100) user_input = -1 while number != user_input: user_input = int(input('What is your guess? ')) if (user_input < number): print('Higher') else: print('Lower') print('You guessed it!')
def convertToPigLatin(inputString): # inputString = [[j for j in i] for i in inputString.split(" ") ] # print(inputString) # seperate into words inputString = inputString.split(" ") # Move initial consonants to end for index, word in enumerate(inputString): for i in word: i...
# 6.00 Problem Set 4 # # Caesar Cipher Skeleton # import string import random WORDLIST_FILENAME = "/Users/macbookpro/Documents/CS/CS600/hw/ps4/words.txt" # ----------------------------------- # Helper code # (you don't need to understand this helper code) def load_words(): """ Returns a list of valid words. W...
# Question 11 # Level 2 # # Question: # Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. # Example: # 0100,0011,1010,1001 # Then the ...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def rotateRight(self, head, k) -> ListNode: if not head: return None if not head.next: return head p = head n = 1 while p.next: ...