text
stringlengths
37
1.41M
student = { "name": input("Insert name: "), "modules": [ { "subject" : input("Subject: "), "grade": input("Grade: ") }, { "subject" : input("Subject: "), "grade": input("Grade: ") } ] } print("Stud...
age = int (input("what is your age")) height = int (input("Height?")) result = age * height if result == 4: print(result, "is normal") elif result >4: print(result, "is huge") elif result <4: print(result, "is tiny")
#program will strip any leading or trailing spaces, and will also convert the string to lowercase string = input("please enter a string: ") normalised = string.strip().lower() stringlength = len(string) normalisedlength = len(normalised) print("Normalised string is: {}". format (normalised)) print("The original st...
#!/usr/bin/env python """ Copyright (c) 2005 Dustin Sallings <dustin@spy.net> """ import sys def tail(f, n=100, est_line_len=175): while True: try: f.seek(-1 * est_line_len * n, 2) except IOError: f.seek(0) atstart = (f.tell() == 0) lines = f.read().spli...
#SET: set used to store multiple items in single variable _set = { "abhi","sai","kiran","charan"} print(_set) _set.add("subba") print(_set) thisset ={"bala","shashi"} _set.update(thisset) print(_set) print(len(_set))
def odd(): s = 1 while True: s = s + 2 yield s def cj(m): return lambda x: x % m > 0 def primes(): yield 2 it = odd() while True: a = next(it) yield a it = filter(cj(a), it) for n in primes(): if n < 1000: print(n) else: break...
numerator = 1 denominator = 1 for y in range(10,100): for x in range(10,100): if x >= y: break x_str = str(x) y_str = str(y) for i in x_str: if i == '0': continue elif x % 11 == 0 or y % 11 == 0: continue elif i in y_str: y_divs = y_str.replace(i,'') x_divs = x_str.replace(i,'') ...
power = 1 for ind in range(0,1000): power *= 2 power_str = str(power) sumo = 0 for digit in power_str: sumo += int(digit) print(sumo)
''' Build Min Heap ''' class MinHeap: def __init__(self, capacity): self.size = 0 self.capacity = capacity self.arr = [None] * capacity def left_child(self, i): return (2 * i) + 1 def right_child(self, i): return (2 * i) + 2 def parent(self, i): return (i - 1)/2 def getmin(self): return self....
''' Find the number of islands: Given a boolean 2D matrix, find the number of islands. A group of connected 1s forms an island. For example, the below matrix contains 5 islands Input : mat[][] = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0, 0, 0, 0...
# https://leetcode.com/problems/binary-tree-postorder-traversal/ # Approach: Iterative approach. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Stack: def __init__(self): self.items = []...
''' https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q...
from argparse import ArgumentParser from re import match import shlex import sys class ArgsParser(ArgumentParser): '''ArgumentParser that adds an "--args" flag that takes extra arguments as a single Bash string. The value passed to "--args" will be split with `shlex`, and converted into potentially multiple argu...
""" Exercise 1. A company is organized hierarchically in departments. Each department has one person in charge and exactly two subdepartments, or else is a single person. We have a structure that records the productivity of every person in it, as a numerical value. We are asked to tell the (sub)department that has...
def abreMochila(mochila) : if len(mochila) == 0: print('Bolso Vazio!') return False if len(mochila)!= 0: print("Itens no bolso:\nDigite o numero correspondente dele para escolher") for item in mochila: print(mochila.index(item)+1,"-",item) i=input("Escolha:",)...
from tkinter import * class Main(Frame): def __init__(self, master=None): if(master != None): master = Tk() master.title("学习") super().__init__(master) self.button = { 'bg': "#f5f5f5", 'fg': "#333333", } self.pack() sel...
#!python from __future__ import print_function import unittest ###################################################################### # this problem is from # https://www.interviewcake.com/question/python/reverse-linked-list # # Hooray! It's opposite day. Linked lists go the opposite way today. # Write a function fo...
#!python from __future__ import print_function from operator import itemgetter import unittest ###################################################################### # this problem is from # https://www.interviewcake.com/question/highest-product-of-3 # interviewcake 4 # https://www.interviewcake.com/question/python/m...
#!python from __future__ import print_function import unittest ###################################################################### # this problem is from # https://www.interviewcake.com/question/highest-product-of-3 # Given a list_of_ints, find the highest_product you can get from three of # the integers. # The ...
#!python from __future__ import print_function import unittest ###################################################################### # this problem is from # https://www.interviewcake.com/question/python/which-appears-twice # # I have a list where every number in the range 1...n appears once # except for one number...
def max_list_iter(int_list): # must use iteration not recursion """finds the max of a list of numbers and returns the value (not the index) If int_list is empty, returns None. If list is None, raises ValueError""" pass if int_list == None: #error for None value raise ValueError elif len(in...
#!/usr/bin/env python3 import csv def read_csv_file(filename, delimiter=' '): labs = [] feats = [] with open(filename, 'r') as f: reader = csv.reader(f, delimiter=delimiter) for row in reader: labs.append(row[0]) feats.append(list(map(float, row[1:]))) return fe...
''' 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 alphabetical position in the list to obtain a name score. For example...
""" 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) c...
''' Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. digits: https://projecteuler.net/problem=13 ''' with open('numbers.txt') as f: numbers = [i.split() for i in f.readlines()] working_value = 0 for rows in numbers: working_value = working_value + int(rows[0]) print(st...
# -*- coding: utf-8 -*- ## @package cliask # # A module for getting validated user input via the console. import re ## Ask for input until a valid response is given and return the # response. # @param question A string containing a question asking for # input. # @param default ...
# Creare un decoratore di classe per far si che la classe di partenza sia modificata in modo # da creare un dizionario interno contenente tutti gli attributi e i valori della classe. def decoratorDictionary(cls): def decorator(*args, **kwargs): diz= dict() for i in range(len(args)): diz...
#Scrivere la classe MyDictionary che implementa gli operatori di dict riportati di seguito. # MyDictionary deve avere solo una variabile di istanza e questa deve essere di tipo lista. # Per rappresentare le coppie, dovete usare la classe MyPair che ha due variabili di istanza # (key e value) e i metodi getKey, getValue...
#Scrivere una funzione che prende in input un intero positivo #ne restituisce e produce un generatore degli interi #0, 1, 3, 6, 10, .. In altre parole, l’i-esimo elemento #e`(0 + 1 + 2 + ... + i-1) def gen(n): x= 0 for k in range (0, n): x+= k yield x for k in gen(5): print(k)
import random class Treasure: def __init__(self): type=random.randint(1,2) self.creat_treasure(type) def creat_treasure(self,type): if type==1: self.name="木剑" self.attack_max=5 self.attack_min=1 self.level=2 self.belonging=0 ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @course: Python is Easy @assignment: Homework #2 @description: functiona and how to call them Created on Thu Feb 11 21:36:13 2021 @author: Claus Derlien """ # defines name of artist/group/band #Artist = "Pink Floyd" # defines music style/genre #Genre = "Progressiv...
# # chant = print("We Will Rock You") # # print(chant) # print("Let's test your programming knowledge.") # print("""Why do we use methods? # 1. To repeat a statement multiple times. # 2. To decompose a program into several small subroutines. # 3. To determine the execution time of a program. # 4. To interrupt the execu...
num = 9 # def evaluate_num(num): # return if num > 10: print('greater') elif num == 10: print('equal') else: print('less') # pass
''' I came across this problem in code war and I had fun and productive time coding this. And learned the importance of order of operation and how it effects the result you want to get. Just enter a numer and it will return an array with all of the integer's divisors(except for 1 and itself) from smallest to larges...
#Even-tual Reduction Problem Code: EVENTUAL #You are given a string S with length N. You may perform the following operation any number of times: choose a non-empty substring of S (possibly the whole string S) such that each character occurs an even number of times in this substring and erase this substring from S. (T...
""" 输入非负整数n计算n! Version: 0.1 Author: 骆昊 Date: 2018-03-01 """ #calculate the factorial def factorial1(n): result = 1 # for x in range(1, n + 1): # result *= x # print('%d! = %d' % (n, result)) for y in range(n,0,-1): result *= y print('%d!=%d'%(n, result)) return result factor...
""" 检查变量的类型 Version: 0.1 Author: 骆昊 Date: 2018-02-27 """ a = 100 b = 1000000000000000000 c = 12.345 d = 1 + 5j e = 'A' f = 'hello, world' g = True h = {"age":"18"} i = [1,2,3] print(type(a))#<class 'int'> print(type(b))#<class 'int'> print(type(c))#<class 'float'> print(type(d))#<class 'complex'> print(type(e))#<clas...
""" 类型转换 Version: 0.1 Author: tester Date: 2019-11-25 """ #use the function type() to get the variable's type a = 100 print(a)#100 print(type(a))#<class 'int'> b = str(a) print('the value of b is:',b)#the value of b is: 100 print(type(b))#<class 'str'> c = 12.345 print('the value of c is:',c) print('the type of c is:'...
""" 用while循环实现1~100之间的奇数求和 """ sum,num = 0,1 while num <= 100: sum += num num += 2 print("1到100的奇数之和为:",sum) #1到100的奇数之和为: 2500
# encoding: utf-8 ''' @author: developer @software: python @file: word_count.py @time: 2019/12/25 21:30 @desc: ''' def count_words(filename): """计算一个文件大致包含多少个单词""" try: with open(filename, 'rb') as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file ...
class Arvore: def __init__(self, raiz = None): self.__raiz = raiz @property def raiz(self): return self.__raiz def inserir_elemento(self, no): no.no_direito = None no.no_esquerdo = None if self.__raiz is None: self.__raiz = no else: ...
#!/usr/bin/env python3 # Activity7 # Vahini Madipalli # Course: ISQA3900-850: Web Application Development # Date: 11-12-2020 # Creating python program which reads from the csv files, display the list, search based on cust_id from Customer import Customer import csv FILENAME = "customers.csv" customer_details = [] d...
groceries = ['candy', 'hot pockets', 'kung fu movie', 'peanut butter', 'bread', 'cat food', 'wine'] for index, item in enumerate(groceries, 1): print(f'{index}. {item}')
import time from timeit import default_timer as Timer def fib(number): if number <= 1: return 1 return fib(number - 2) + fib(number - 1) start = time.clock() for _ in xrange(4): fib(30) end = time.clock() print('\nserial time', end - start)
from abc import ABC, abstractmethod from enum import Enum, unique @unique class VEHICLE_TYPE(Enum): CAR = 'car' TRUCK = 'truck' class IVehicle(ABC): @abstractmethod def get_wheels(self): pass @abstractmethod def get_type(self): pass @abstractmethod def max_speed(self...
a = [ {"name": 2, "age": 3}, {"name": 3, "age": 4}, ] def f(): for x in a: yield x["name"] for x in f(): print x
# coding:utf-8 import os def mkdir(path, dir_list): for x in dir_list: os.mkdir(os.path.join(path, x)) def a_z(): return [chr(x) for x in range(97, 97+26)] def A_Z(): return [chr(x) for x in range(65, 91)] if __name__ == '__main__': dir_list = [str(x) for x in range(12)] path = r'C:\Us...
def hourglassSum(arr): listSum=[] for i in range(len(arr)-2): sum=0 for j in range(len(arr)-2): sum=arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2] listSum.append(sum) return max(listSum) # arr=[[1, 1, 1, 0, 0, 0], # [0,...
from collections import Counter def reverse(split): return split[::-1] def shufflestr(rev): def splitstr(s): count=Counter(s) str="" for i in count: str=str+i return str def reverseShuffleMerge(s): split=splitstr(s) rev=reverse(split) shuffle=shufflestr(rev) s="abc...
def jumpingOnClouds(c): num_of_jumps=0 i=0 while i<len(c)-1: num_of_jumps+=1 if i==len(c)-2: break if c[i+2]==1: i+=1 else: i+=2 return num_of_jumps c=[0,0,0,1,0,0] print(jumpingOnClouds(c))
# -*- coding: Latin-1 -*- """ # -*- coding: Latin-1 -*- rien d'assez complexe le code source écrit en vue d'une relation pour une formation #la suite directaffiche une table de mutiplication nbr = input("\t veillez saisir un nombre") nbr = int(nbr) i = 0 while i <= 20: print("\t", nbr, "*" , i ,"=", nbr * i ) ...
"""ceci est mon programme en ligne de commande de calcul de base""" #fonction de calcul def Addition(): resultat =nbr0 + nbr1 print("\t {} + {} ={}".format(nbr0,nbr1,resultat)) """ ceci est ma fonction d'addition """ def Soustration(): resultat = nbr0 - nbr1 print("{} - {} = {}".format(nbr0,nb...
""" while chaine.lower() != "q": print("Tapez 'Q' pour quiter...") chaine= input() print("merci tchao.....!") """
santa= 8 print(santa) nouritures = ['pomme de terre','riz au gras','ayimolou'] loisires = ['dormir','gaming sur android','la programation web en html'] favoris = loisires + nouritures print(favoris) n1 = "Kokou Amétépé joseph" n2 ="HOMAWOO" texte_blague = '''bonjour %s %s. bonjour comment vas tu Mr luck''' print(texte_...
# The following programe provides the user with an output that varies upon # whether the program is run during the week or at the weekend import datetime # "The datetime module supplies classes for manipulating dates and times." - docs.python.org - /module-datetime x = datetime.datetime.now() # This Command is used ...
# Print sum of all even numbers from 1 to 10 numbers ? sum=0 for x in range(1,11): if x%2==0: sum=sum+x print("Sum of even numbers:",sum)
class Person(object): def __init__(self): self.__age = 0 # 装饰器方式的property, 把age方法当做属性使用, 表示当获取属性时会执行下面修饰的方法 @property def age(self): return self.__age # 把age方法当做属性使用, 表示当设置属性时会执行下面修饰的方法 @age.setter def age(self, new_age): if new_age >= 150: print("成精了")...
import threading import time # 唱歌任务 def sing(): # 扩展: 获取当前线程 # print("sing当前执行的线程为:", threading.current_thread()) for i in range(3): print("sing %d" % i) time.sleep(1) # 跳舞任务 def dance(): # 扩展: 获取当前线程 # print("dance当前执行的线程为:", threading.current_thread()) for i in range(3): ...
''' 进程 1.进程是系统分配资源的最小单位,一个进程一旦创立就会需要分配资源.比较耗资源. 2.各个进程之间无法通信,也无法共享任何资源,哪怕是全局变量的数据,进程间也无法共享 线程 1.线程是程序执行的最小单位,进程负责分配资源,线程负责执行程序 2.可以认为,进程是线程的容器,一个进程里至少需要有一个线程 3.线程本身不拥有系统资源, 4.属于同一个进程的多个线程之间可以共享资源. ''' import threading import time # 唱歌任务 def sing(num): # 扩展: 获取当前线程 # print("sing当前执行的线程为:", threading.current_...
import copy # 使用深拷贝需要导入copy模块 # 可变类型有: 列表、字典、集合 ''' 可变类型进行深拷贝会对该对象到最后一个可变类型的每一层对象就行拷贝, 对每一层拷贝的对象都会开辟新的内存空间进行存储。 ''' a1 = [1, 2] b1 = copy.deepcopy(a1) # 使用copy模块里的deepcopy()函数就是深拷贝了 # 查看内存地址 print(id(a1)) print(id(b1)) print("-" * 10) a2 = {"name": "张三"} b2 = copy.deepcopy(a2) # 查看内存地址 print(id(a2)) print(id(b2)) pr...
# defining a function; giving it a name and telling what arguments we need. def cheese_and_crackers (cheese_count, boxes_of_crackers): print(f"You have {cheese_count} cheeses!") print(f"You have {boxes_of_crackers} boxes of crackers!") print("Man that's enough for a party!") print("Get a blanket.\n") #...
# printing a string print("Mary had a little lamb.") # printing a string with formated string of snow print("Its fleece was white as {}.".format('snow')) # printing a string print("And everywhere that Mary went.") #printing a string "." and multiplying it by 10 print("." * 10) # what'd that do? it printed string '.' 10...
''' def swoop(stuff, increment): i = 0 numbers = [] while i < stuff: print(f"At the top i is {i}") numbers.append(i) i = i + increment print("Numbers now: ", numbers) print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers: print(num) crazy = 15 increment = ...
""" This defines a class for a tic-tac-toe game. """ from itertools import cycle from random import choice class tic_tac_toe: """A game of tic-tac-toe between two players, human or computer.""" def __init__(self, n_humans = 2): self.board = [['-' for i in range(3)] for i in range(3)] self.n_humans ...
def search(nums,target): for i in range(len(nums)): if nums[i]==target: return (i) if target not in nums: return -1 nums = [10,20,30,40] target = 3 k = search(nums,target) print(k)
def search(nums,target): if target not in nums: return -1 l = 0 r = len(nums)-1 while l<=r: mid = (l+r)//2 if nums[mid]<target: l = mid+1 elif nums[mid]>target: r = mid-1 else: return mid nums = [10,20,30,40] t...
#this prepares to turn the words from arrays into strings def listToString(s): str1 = "" for ele in s: str1 += ele return str1 message = (input("enter your message (3 words max): ")) #this splits the sentence into individual words s = message.split(" ") start = s [0:1] middle = s [1:2] end = s [2:...
def removeDuplicates(nums): if len(nums) <= 2: return i = 0 j = 2 while True: if len(nums) <= j: break if nums[i] == nums[j]: nums.pop(j) else: i += 1 j += 1 if __name__ == "__main__": nums = [1,1,1,2,2,3] removeDuplicates(nums) print(nums) ...
def lengOfLastWord(str): LastWord = str.split(" ") temp = [] for i in LastWord: if len(i) > 0: temp.append(len(i)) return int(temp[-1]) if __name__ == "__main__": strings = "hello world " print(lengOfLastWord(strings))
def PlusOne(digits): carry = 0 result = [] temp = 1 for i in reversed(digits): value = (i + carry + temp) % 10 carry = (i + carry + temp) // 10 result.insert(0, value) temp = 0 if carry == 1: result.insert(0, carry) return result if __name__ == "__main__": ...
# 在数组中找x + y = target,输出x, y的下标 # 遍历数组通过字典记录x, 同时查询hash值查找字典中有无target - x def twoSum(nums, target): hashtable = dict() for i, num in enumerate(nums): if target - num in hashtable: return [hashtable[target - num], i] hashtable[num] = i return [] if __name__ == '__main__': n...
import numpy as np def detect_growth_events(areas, threshold=-350): """Given a list of bacterial growth areas, detect growth events. A growth event is defined as when the bacterial area changed by a certain threshold value. :param areas: list of areas :type areas: list :param threshold: the b...
# Faça um programa que tenha uma função chamada área(), # que receba as dimensões de um terreno retangular (largura e comprimento) # e mostre a área do terreno: def area(comprimento,largura): r=comprimento*largura print(f'A area é de {r:.2f}') c=float(input('Digite o comprimento:\n')) l=float(input('Digite a...
salario_inicial=float(input('Informe o seu salario atual \nR$')) aumento = 0 percentual = 0 reajuste1 = 20 reajuste2 = 15 reajuste3 = 10 reajuste4 = 5 if salario_inicial <= 280: aumento = salario_inicial*(reajuste1/100) percentual = reajuste1 print(f'Salario inicial R${salario_inicial}') print(f'{percentual}%...
#Escreva um programa que pede a senha uma senha ao usuário, e # só sai do loop quando digitarem #corretamente a senha. A senha é “Blue123” #2b - Exiba quantas vezes o usuário errou a digitação. #senha = 'Blue123' #usuario = input('Digite a senha:\n') #while usuario != senha: # usuario = input('Digite a senha:\n'...
#Crie um dicionário em que suas chaves serão os números 1, 4, 5, 6, 7, e 9 (que podem ser armazenados em uma lista) e seus valores correspondentes aos quadrados desses números. lista = [1,4,5,6,7,9] quadrados = dict() for i in lista: quadrados [i] = i**2 print(quadrados) # Crie um dicionário em que suas chaves...
# 9.Faça um Programa que leia um vetor A com 10 números inteiros, calcule e mostre a soma dos quadrados dos # elementos do vetor. lista=[] vezes =0 while vezes != 10: num = int(input('Digite um valor:\n')) num2 = num*num lista.append(num2) vezes +=1 resultado=sum(lista) print(resultado)
#Reading Files --ex15.py from sys import argv #how to unpack argv script, filename = argv #open the file txt = open(filename) #display the file name and read it print "Here is your file %r:" % filename print txt.read() #Be courteous, clean up after yourself! txt.close() #Ask for file name again with a prompt prin...
# Doing things to Lists - ex38.py ten_things = "Apples Oranges Crows Telephone Light Sugar" #print "The list 'ten_things:", ten_things # unnecessary - this list is parsed and printed on lines 7,8 # print "Number of items in list 'ten_things", len(ten_things) # This will count every single character including spaces pri...
from random import randint import sys sys.path.append(".") from Card import * class Deck: def __init__(self, empty = False): self.contents = [] if not empty: self.construct_deck().shuffle_deck() def construct_deck(self): suits = ["Diamonds", "Hearts", "Spades", ...
# Facade pattern hides the complexities of the system and provides an interface # to the client using which the client can access the system. This pattern involves a single class # which provides simplified methods required by client and delegates calls to methods of existing system classes from abc import ABC, abstra...
# Adapter pattern works as a bridge between two incompatible interfaces. # This pattern involves a single class which is responsible to join functionalities # of independent or incompatible interfaces. # from abc import ABC, abstractmethod # Target interface class Target(ABC): def __init__(self): self._ad...
"""Realizar una funcion que devuelva un valor booleano indicando si un numero que se le pasa por argumento es o no un numero perfecto. Un numero perfecto es aquel que es igual a la suma de sus divisores incluyendo el uno y excluyendo al un numero mismo. Utilizando esta funcion realizar un programa que escriba a lista ...
def buildMemo(): # Memo matrix builder m = [-1] * (items + 1) for i in range(items): m[i] = [-1] * (capacity + 1) return m def backpack(i, cc): if memo[i][cc] != -1: return memo[i][cc] # Return if this operation has already been processed if i == (items - 1) or cc == 0: # All...
# https://leetcode.com/problems/game-of-life/ class Solution(object): def getOriValue(self, board, i, j): if i < 0 or j < 0 or i >= self.row_num or j >= self.col_num: return None if self.change_status[i][j]: ori_value = 1 - board[i][j] else: ori_value =...
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ use_dp = True if use_dp: return self.isMatch_v2(s, p, 0, 0) # if len(p) == 0: # return len(s) == 0 # # first_match ...
# https://leetcode.com/problems/maximal-rectangle/ class Solution(object): def maximalRectangle(self, matrix): """ :param matrix: List[List[str]] :return: int """ if len(matrix) == 0: return 0 cur_height_list = [] max_area = 0 for each_row in matrix:...
#!/usr/bin/env python # https://leetcode.com/problems/reorder-list/ # Definition for singly-linked list. def print_list(head): cur = head list_str = "" while cur is not None: list_str += str(cur.val) + "->" cur = cur.next print(list_str[:-2]) class ListNode(object): def __init__(se...
import numpy from math import * boundaries_x = list(map(float, input("Enter boundaries x (using space): ").split())) step_x = float(input("Enter step x: ")) boundaries_y = list(map(float, input("Enter boundaries y (using space): ").split())) step_y = float(input("Enter step y: ")) function = eval("lambda x, y: " + in...
import tkinter as tk from tkinter import * import os #attach things to this to effect the app as a whole root = tk.Tk() root.geometry('400x200') root.configure(background="teal") def button_command(): eg = e.get() fg = f.get() gg = g.get() hg = eg.replace(fg,gg) e.delete(0, END) f.delete(0...
#A complete classification of the English Language, by BCPI #Yes it's inefficient but it works. #Copyright me 2/8/2020 AD opening = ''' English words list A python code that classifies all words by letter, length, and letter and length. To use: You need to have the python library nltk installed To do this in your termi...
import numpy as np """ 创建Numpy数组 """ print('使用普通一维数组生成NumPy一维数组') data = [1, 2, 3.2, 4, 7] arr = np.array(data) print(arr) print('元素类型:',arr.dtype) print() print('使用普通二维数组生成NumPy二维数组') data = [[1, 2, 3, 4], [5, 6, 7, 8]] arr = np.array(data) print(arr) print('数组维度:',arr.shape) print() """ zeros(),zeros_like(),ones...
def get_images_and_labels(img_dict): """ Given an img_dict, creates two lists img_labels and img_list Generally img_dict is modelled as to contain label as key and the key's value contains a list which has all the images present in the category. Parameters: ...
''' Exemplo de aplicação das fórmulas de predador-presa com o método de Runge-Kutta de 4 ordem importando os métodos do módulo que está nessa mesma pasta. Exemplo aplicado: problema 27.22 do livro Chapra Canale Métodos Numéricos para engenharia ''' from RK4predadorpresa import * x = 2 y = 1 t = 0 tStop = 30 h = ...
''' Nesse código, uma funcao que calcula o K1 do metodo RungeKutta de 2 ordem para que o próximo y seja calculado: yi+1 = y + K1 No final tem um comentário com um exemplo de aplicação com a equação => y' = sen(y) y(0) = 1 Exemplo 7.3 livro Kiusalaas Numerical python ''' import numpy as np import math def integ...
""" Author: Vivek Rana Usage : Just run the script in a Python enabled computer. Date : 12-Aug-2016 """ def findPrime(N): while( N%2 == 0): N = N//2 if N == 1: return 2 i = 3 sqrtN = int(N**0.5) while(i<=sqrtN and i<N): if (N%i == 0): N = N//i i = 3 ...
#This program tells if a number is pallindrome or not #This program is made by Saksham Gupta #This function makes sure input is a positive integer def IntegerGetter(str): while True: try: num = int(input(str)) except ValueError: print("That's not an Integer. Please Enter Det...
#This program makes a pascal triangle #This program is made by Saksham Gupta #This function makes sure input is a positive integer def IntegerGetter(str): while True: try: num = int(input(str)) except ValueError: print("That's not an Integer. Please Enter Details again.") ...
import random def guess_number(number): while True: input_number = int(raw_input('Input your number:\n')) if input_number > number: print "Your number is bigger" elif input_number < number: print "Your number is smaller" else: print "Bingo" ...
from data_structures import Queue from factories import stack_factory def interleave_stack(stack): ''' This problem was asked by Google. Given a stack of N elements, interleave the first half of the stack with the second half reversed using only one other queue. This should be done in-place. Recall that you can...