text
stringlengths
37
1.41M
# b = { # "name": "teacher1", # "subject": "math", # "salary": 1000, # "age": 50 # } # keys = [] # values = [] # for i in b: # keys.append(i) # values.append(b[i]) # print(keys) # print(values) d = {} keys = ['name', 'subject', 'salary', 'age'] values = ['teacher1', 'math', 1000, 50] # code n =...
numbers = [ ["футболка", 2], ["шорты", 4], ["кофта", 6], ] # 0 1 # 0[1, 2], # 1[3, 4], # 2[5, 6], # 3[7, 8] print(numbers[0][0], numbers[0][1]) # футболка print(numbers[1][0], numbers[1][1]) print(numbers[2][0], numbers[1][1])
#while -> пока(до тех пор) # while условие: # действия number = 20 while number != 10: print("ok", number) number = number - 1 print("end of cycle")
# Пользователь делает вклад в размере a рублей сроком на years лет под 10% годовых # (каждый год размер его вклада увеличивается на 10%. Эти деньги прибавляются к сумме вклада, # и на них в следующем году тоже будут проценты) a = int(input("сумма:")) years = int(input("года:")) percent = 0.1 i = 1 while i <= years: ...
number=int(raw_input()) for i in range(2, number): if number%i == 0: print(number, "is not a prime number") break else: print(number, "is a prime number")
print("Enter an integer") if (number % 2 == 0): print("the number is even") else: print("the number is odd")
from basic.stack import Stack # 一维字符串的消消乐 def xiaoxiaole(strings): s = Stack() list = [] for str in strings: # 如果与栈顶相同则消去栈顶, 不同则压入栈顶 if str == s.peek(): s.remove() else: s.push(str) if s.isEmpty(): return None else: while not s.isEmpty(): ...
from basic.stack import Stack def parChecker(string): s = Stack() index = 0 balance = True while index < len(string) and balance: symbol = string[index] if symbol in "{[(": s.push(symbol) else: if s.isEmpty(): balance = True ...
import argparse import youtube_dl import os.path parser = argparse.ArgumentParser( description="Converts a Youtube video to MP3", epilog="python youtube_mp3.py --video_url 'https://www.youtube.com/watch?v=CMNry4PE93Y'" ) parser.add_argument("--video_url", required=True, help="URL of video to be converted") par...
def distance(a,b): if a in r.smembers(b) or b in r.smembers(a): return 1 elif r.smembers(a).isdisjoint(r.smembers(b)) !=True: return 2 else: second_degree = set() for s in r.smembers(a): second_degree = second_degree.union(r.smembers(s)) print se...
# Problem: 5 (in base 10) = 101 (in base 2). Invert 101 to 010 (in base 2) = 2 (in base 10) # Input: 5 # Output: 2 def getIntegerComplement(n): a = '' while (n > 0): a = str(abs(1 - (n % 2))) + a n /= 2 i = 1 num = 0 for j in xrange(len(a) - 1, -1, -1): num += i * int(a[j]) ...
# Complete the function below. def say_what_you_see(input_strings): res = [] for s in input_strings: curr = s[0] count = 1 cres = "" for c in s[1:]: if c != curr: cres += str(count) + curr curr = c count = 1 ...
from random import randint def start(): print(''' #################### Игра "15 спичек" ################ Всего в куче 15 спичек. Каждый игрок по очерди берёт от ################### 1 до 3 спичек. #################### Выигрывает тот, кто заберёт последние спички из кучи. ''') # def get_turn()...
#!/usr/bin/env python # coding: utf-8 # ### Observations from the data # * 1. Male players are signficantly more numerous than female players, with more than five times the number of players. This can inform future advertising and promotional efforts, advertising in bars, live streams of sporting events, and male-cen...
r = float(input("Enter the radius of the sphere: ")) x = input("Enter P for Perimeter, A for Area and V for volume: ") if x == 'P': def sphere_perimeter(): p = 4*3.14*r print("Perimeter of the sphere is: ", p) sphere_perimeter() elif x == 'A': def sphere_area(): a = (4*3.14*...
# Copyright (C) 2015 by Per Unneberg class NotInstalledError(Exception): """Error thrown if program/command/application cannot be found in path Args: msg (str): String described by exception code (int, optional): Error code, defaults to 2. """ def __init__(self, msg, code=2): sel...
#this program should take a video and display the grayscaled version to the user, i had some issues with this program and im not sure what is wrong:( import numpy as np #bring numpy in and call it np for aberivation import cv2 as cv # import cv2 module as cv #this program gave me a number of issues when i put m...
# Binary Search Algorithm is one of the most important and fundamental search algorithms every programmer should know. # In order to perform binary search, it is crucial that the list is sorted first. # We will be using our merge sort algorithm to sort our list. # Then, we will perform binary search. # Time Complex...
products = [] # 有一個叫做 products 的空清單 while True: # 進入迴圈 name = input('請輸入商品名稱:') # 請使用者輸入商品名稱,創建為 name if name == 'q': # 如果使用者輸入 q break # 離開程式 price = input('請輸入商品價格:') # 請使用者輸入商品價格,創建為 price products.append([name, price]) # 把 p 這個清單裝到 products 這個清單裡 print(products) products[0][0] # products 清單的第 0 格中的第 0 格
# ============================================================================= # tuple() # ============================================================================= a = ("Doreamon","sdjfhan","Tom and Jerry") b = (1,2,3,4,5,3,3) print(b.count(3)) print(sorted(a,reverse=True)) print(a.index("Tom and Jerry")) p...
# ============================================================================= # print() or output # ============================================================================= print("codinglaugh","learn","something","everyday",10,20,sep="*") print("codinglaugh","hdsjbhfh",end="\n\n") print("learn something everyd...
# -*- coding: utf-8 -*- """ Created on Fri Oct 4 17:31:45 2019 @author: niko1 """ def resolver1(pal1,pal2): #frozenset re ordena los caracteres en formato ASCII, pasando, por ejemplo, la palabra cosa a a-c-o-s x = frozenset(pal1) y = frozenset(pal2) if(x==y): print(pal2,' es un anagrama de ',...
import numpy as np class Hill_cipher: 'Hill cipher is use matrix as key. in this block by block encryption' list1=[] list2=[] pt=[] pt1=[] ct=[] k=[] n=1 key=[] inverseKey=[] result=[] planeText="" cipherText="" def input_pt(se...
import pygame import defs import colors import random pygame.init() class Grid(): def __init__(self): self.x = defs.width * defs.x_grid_gap self.y = defs.height * defs.y_grid_gap self.square_len = defs.grid_square_len self.width = self.square_len * defs.x_grid_squares self...
# making right trinagle ''' like this: * ** *** **** ***** ****** ''' x = int(input('inter the hight of triangle: ')) star = "*" for i in range(x): print('{}'.format(star * i)) # making isosceles triangle for i in range(x): print("{}".format((star*i).center(x+1))) # making right 90^ triangle for i in ra...
""" INSERT YOUR NAME HERE """ from __future__ import division from __future__ import print_function import sys import cPickle import numpy as np # This is a class for a LinearTransform layer which takes an input # weight matrix W and computes W x as the forward step class LinearTransform(object): def __init_...
# tutorial: https://machinelearningmastery.com/multi-step-time-series-forecasting-long-short-term-memory-networks-python/ import numpy as np import pandas as pd import keras from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error, confusion_matrix from matplotlib import pyplot as ...
import math import unittest from typing import List class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp = [amount + 1] * (amount + 1) dp[0] = 0 for i in range(1, amount + 1): for coin in coins: if i - coin < 0: con...
import unittest from typing import List class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: def backtrack(pos, target): if 0 == target: res.append(stack[:]) elif 0 < target: for i in range(pos, len(candid...
import unittest from typing import List class Solution: def convertToBase7(self, num: int) -> str: base7 = [] isNegative = False if num < 0: isNegative = True num = -num while num >= 7: base7.append(str(num % 7)) num = num // 7 ...
import unittest from typing import List class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: def dfs(pos, B): print(num, A[pos], B) if pos == len(A) or len(B) == 0: result.append(num[0]) return for i in range(le...
import unittest from typing import List class Solution: def __init__(self): self.dp = [] for i in range(5): self.dp.append(i) def integerBreak(self, n: int) -> int: if n < 4: return n - 1 elif 4 < n < len(self.dp): return self.dp[n] ...
import unittest from collections import defaultdict from typing import List class Solution: def findMaxLength(self, nums: List[int]) -> int: d = {0: -1} count = 0 max_len = 0 for index, num in enumerate(nums): if num == 0: count -= 1 else: ...
import math class MinStack: def __init__(self): self.stack = [] self.min_stack = [math.inf] def push(self, x): self.stack.append(x) self.min_stack.append(min(x, self.min_stack[-1])) def pop(self): self.stack.pop() self.min_stack.pop() def top(self): ...
import requests import json host_url = "http://thetestingworldapi.com" body = { "id": 555, "first_name": "monika", "middle_name": "sen", "last_name": "gupta", "date_of_birth": "11/11/1985" } response_code = requests.post(host_url+"/api/studentsDetails", data=body) print("the re...
import anagram, getopt, Levenshtein, string, sys, ap_encoding THRESHHOLD = 3 def distance(w1, w2): return Levenshtein.distance(w1,w2) def get_distance(text): exclude = set(string.punctuation) text = ''.join(ch for ch in text if not ch in exclude) words = text.split() return [words[i] for i in xrange(len(words))...
#! /usr/bin/python import getopt, re, sys, ap_encoding def powerball(text,balls): #initialize containers, explode word array, parse out the last number as the "powerball" index = 0 result = "" ball = [] full_text = text.split() ball = balls.split() powerball = ball[5] #remove the last number of sequence from ...
def toStr(n,base): convertString='0123456789ABCDEF' if n<base: return convertString[n] else: return toStr(n//base,base)+convertString[n%base] # 使用栈 class Stack: def __init__(self): self.items=[] def isEmpty(self): return self.items==[] def push(self,item): ...
class Stack: def __init__(self): self.items=[] def isEmpty(self): return self.items==[] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): re...
#python内建的filter()函数用于过滤序列 #和map()类似,filter()也接收一个函数和一个序列,和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False #决定保留还是丢弃该元素 #在一个list中,删掉偶数,只保留奇数: def is_odd(n): return n%2==1 list(filter((is_odd,[1,2,3,4,5,6,7,8])))
#当我们在传入函数时,有时候不需要显示定义函数,直接传入匿名函数更方便 list(map(lambda x:x*x,[1,2,3,4,5,6])) #通过对比可以看出,匿名函数lamaba x:x*x实际上就是 def f(x): return x*x #关键字lamba表示匿名函数,冒号前面的x表示函数参数 #匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果 #用匿名函数的好处是,函数没有名字,不必担心函数名冲突。 #此外,匿名函数也是一个函数对象,也可以吧匿名函数复制给一个变量,在利用变量来调用该函数。 f=lambda x:x*x #也可以吧匿名函数作为返回值返回 def bu...
# Maximum Edge of a Triangle # Create a function that finds the maximum range of # a triangle's third edge, where the side lengths are all integers. def next_edge(side1, side2): # side1 - side2 < side3 < side1 + side2 side3_max = (side1 + side2) - 1 print(side3_max) return (side1 + side2) - 1 next_edge(8,...
# Luke, I Am Your ... # Luke Skywalker has family and friends. # Help him remind them who is who. # Given a string with a name, # return the relation of that person to Luke. # Person Relation # Darth Vader father # Leia sister # Han brother in law # R2D2 droid # Examples # relation_to_l...
# Find the Perimeter of a Rectangle # Create a function that takes # length and width and finds the perimeter of a rectangle. def find_perimeter(side1, side2): perimeter = (side1 + side2) * 2 print(perimeter) return (side1 + side2) * 2 find_perimeter(6, 7) # ➞ 26 find_perimeter(20, 10) # ➞ 60 find_perim...
import numpy as np a=np.array([1,2,3]) #declares an array with type as numpy.ndarray print(a.shape) #prints size #all the elements can be changed and can be brought by normal indexing b = np.array([[1,2,3],[4,5,6]]) #2d array print(b.shape) # Prints "(2, 3)" print(b[0, 0], b[0, 1], b[1, 0]) # [...
#used for predicting catogarical values """ classification can be done by decision trees naive bias linear discriminent analysis k-nearest neighbor logistic regression neural networks support vector machines mechanism-> by given data we can obtain a scatter plot then we find nearest point for our values which are to p...
""" Board module for tic tac toe. Displays and maintains the state of the board """ import sys import numpy as np class Board: """ maintains board state as a numpy int array where: -1 -> blakn 0 -> player 1 mark 1 -> player 2 mark """ M = -1 N = -1 K = -1 def __init...
def binary_search(key, arr): low = 0 high = len(arr)-1 mid = (low+high)//2 while(high>low): if(arr[mid]==key): return mid if(arr[mid] > key): high = mid-1 elif(arr[mid] < key): low = mid+1 mid = (low+high)//2 return mid ...
#Counting Organizations #This application will read the mailbox data (mbox.txt) count up the number email messages per organization #(i.e. domain name of the email address) using a database with the following schema to maintain the counts. #CREATE TABLE Counts (org TEXT, count INTEGER) #When you have run the progr...
class Product: def __init__(self, name, price, discount=0, stock=0, max_discount=20.0): self.name = name.strip() if not len(self.name) >= 2: raise ValueError('Too short name') self.price = abs(float(price)) self.stock = abs(int(stock)) self.max_discount = abs(int(...
if 10 > 5: print("10 greater than 5") print("Program ended") spam = 7 if spam > 5: print("five") if spam > 8: print("eight") num = 12 if num > 5: print("Bigger than 5") if num <= 47: print("Between 5 and 47") x = 4 if x == 5: print("Yes") else: print("No") num = 7 if num == 5: ...
# 要求:设计一个简单的计算器,让用户输入2个数字,返回这两个数的和 # print("the sum is:" + str(float(input("input 1st number:"))@ # + float(input("input 2nd number:")))) # x = input("input 1st number:") # y = input("input 2nd number:") # print("the sum is:" + str(float(x) + float(y))) x = float(input("input 1st number:")) ...
import random def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if ints: ints_len = len(ints) if ints_len < 2: return ints[0], ints[0] i = 0 ...
print("====Calculo de total de calorias num dia====") calorias_total = 0 alimentos = int(input("Quantos alimentos consumiu hoje? ")) for x in range(1,alimentos+1): calorias = int(input("Quantas calorias tem o alimento {}? ".format(x))) calorias_total = calorias_total + calorias print("Você consumiu ...
from bs4 import BeautifulSoup #HTML Code - the html content that we are going to parse using Beautiful Soup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were thre...
import sys n = int(input('Please enter an integer value: ')) a = 1 b = 1 while a>=1 and b>=1: print(a) temp = a + b a = temp + b print(a)
import sys n = str(input('Please enter a binary number: ')) a = str.len(n) #c = n.count(0) for i in range(0,2) b = i(2**a) while b = i: break if n%10 = 0: while 1 == 1: a -= 1 b = 2**a + 2**(a) print(b)
import sys import math ## t= temperature in Fahrenheit ## v= wind speed in miles per hour ## w= wind chill t = float(sys.argv[1]) v = float(sys.argv[2]) if math.fabs(t) > 50: print("Error: t should be greater than -50 and less than 50.") exit() if (v > 120 or v < 3): print("Error: v should be greater than 3 and le...
line = input().split(" ") x, y, z = line a = float(x) b = float(y) c = float(z) if a >= b and a >= c and a < (b + c): print("Perimetro = %.1f" %(a+b+c)) elif b >= a and b >= c and b < (a + c): print("Perimetro = %.1f" %(a+b+c)) elif c >= a and c >= b and c < (a + b): print("Perimetro = %.1f" %(a+b+c)) e...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: res = [] if root is None: ret...
import time import random welcome_message = 'welcome to the magic number game!' print(welcome_message) ask_user_for_number = int(input('Can you please select a number between 0-10? ')) time.sleep(0.5) magic_number = random.randint(0,10) magic_number_message = f'The magic number for this round was {magic_number}...
''' Carly's Clippers You are the Data Analyst at Carly’s Clippers, the newest hair salon on the block. Your job is to go through the lists of data that have been collected in the past couple of weeks. You will be calculating some important metrics that Carly can use to plan out the operation of the business for the re...
#importing the necessary libraries import pandas as pd from io import BytesIO from urllib.request import urlopen from zipfile import ZipFile import rasterio as rt from rasterio.mask import mask import shutil from Typing import List, Dict class GeoTiff: """ Class GeoTiff is where we get all the details about t...
def letter_histogram(word): result = {} for char in word: result[char] = word.count(char) print(result) if __name__ == "__main__": letter_histogram(input("Give a word to start. "))
letras = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '.', '!', '#'] numeros = [0, 1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 , 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28] palavra = str(input('Digite a palavra: ')).st...
def add_list_to_words(words: dict, new_words: list): for word in new_words: words[word] = words.get(word, 0) + 1 def get_repeated_words(words: dict) -> list: return [k for k, v in words.items() if v > 1] def get_unique_words(words: dict) -> list: return [k for k, v in words.items() if v == 1] ...
# For the exercise, look up the methods and functions that are available for use # with Python lists. x = [1, 2, 3] y = [8, 9, 10] # For the following, DO NOT USE AN ASSIGNMENT (=). # Change x so that it is [1, 2, 3, 4] # YOUR CODE HERE x.append(4) print(x) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] #...
import tkinter as tk # 使用Tkinter前需要先匯入 import tkinter.messagebox from evaluate import evaluate # 第1步,例項化object,建立視窗window window = tk.Tk() # 第2步,給視窗的視覺化起名字 window.title('政治立場分析') # 第3步,設定視窗的大小(長 * 寬) window.geometry('500x300') # 這裡的乘是小x # 第4步,在圖形介面上設定輸入框控制元件entry框並放置 # 第5步,定義兩個觸發事件時的函式insert_point和insert_end...
#!/usr/bin/env python # coding: utf-8 # In[ ]: [簡答題] 請問 type(...) 跟 a.dtype 這兩個語法有什麼不同? # In[1]: import numpy as np a=np.arange(12).reshape(3,4) print(a) print('dtype:',a.dtype) print('type(a):', type(a)) #type(...)得出的是numpy array的類型 #a.dtype則是得出a 的data 種類 # In[ ]: [簡答題] 承上題,請判斷下列三種寫法為何不正確? # In[18]: de...
import requests, json from requests.exceptions import ConnectionError from urllib3.exceptions import NewConnectionError print("Let's look at the weather today!") ZIPCODE = input("Enter zipcode: ") BASE_URL = "https://api.openweathermap.org/data/2.5/weather?" URL = BASE_URL + "zip=" + ZIPCODE + ",us&appid=" + "9...
""" 该类的作用主要是 对文件的增删改查操作 读取配置文件:返回一个dict 写配置文件:传入key-value值,根据相应的key值,修改配置文件 可以照着其他的类写,所有的变量都要求是私有的,用@property来进行获取或者赋值,可参照其他类 """ import configparser #import os # _*_ coding:utf-8 _*_ class FileUtil(object): def __init__(self, file: str): self.__configfile = file self.__cfg = configp...
""" 画text的类 """ import pygame class Text: def __init__(self, text: str, posx: int, posy: int, text_height: int=10, font_color: tuple=(0, 0, 0), background_color: tuple=(255, 255, 255)): self.__text = text self.__pos_x = posx self.__pos_y = posy self.__text_height ...
from datetime import timedelta intervals = { 'y': timedelta(days=365.25), 'w': timedelta(days=7), 'd': timedelta(days=1), 'h': timedelta(hours=1), 'm': timedelta(minutes=1), 's': timedelta(seconds=1), } def parse_interval(text: str) -> timedelta: current = '' total = timedelta(seconds...
numero = float(input('Digite um número: ')) if numero > 0: print('O numero digitado é posivito!') elif numero < 0: print('O número digitado é negativo!') else: print('O numero digitado é o elemeno neutro 0.')
print('Programa para ler uma temperatura em Celsius e retornar os valores destas temperaturas em Fahrenheit e Kelvin') celsius = float(input('Digite a temperatura, em Celsius: ')) kelvin = celsius + 273 fahrenheit = ((9/5) * celsius) + 32 print('Temperatura em Celsius: {:.1f}° C; Temperatura em Fahrenheit: {:.1f}...
ang1 = int(input('Digite o primeiro valor do ângulo interno do triângulo: ')) ang2 = int(input('Digite o segundo valor do ângulo interno do triângulo: ')) ang3 = int(input('Digite o terceiro valor do ângulo interno do triângulo: ')) # TESTE PARA VERIFICAR SE OS VALORES ANGULARES DIGITADOS FORMAM UM TRIÂNGULO tria...
from queue import Queue class Node: def __init__(self,value): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self,root): self.root = Node(root) def traverse(self,type): if type is"preorder": print(type+" "+self.preorder_traversal(self.root,""...
# bsdk idhar kya dekhne ko aaya hai, khud kr!!! # from math import * # from itertools import * # import random def isprime(x): for i in range(2, x): if x % i == 0: return False else: return True n, k = map(int, input().split()) count_ = 0 if isprime(k) == False: print("NO") e...
# bsdk idhar kya dekhne ko aaya hai, khud kr!!! # from math import * # from itertools import * # import random cd = input() col = cd[0] row = int(cd[-1]) if col == "a" or col == "h": if row == 1 or row == 8: print(3) else: print(5) elif col == "b" or col == "c" or col == "d" or col == "e" or col...
# bsdk idhar kya dekhne ko aaya hai, khud kr!!! # from math import * # from itertools import * t = int(input()) for i in range(t): n = int(input()) arr = list(input()) if n < 11: print("NO") elif n == 11 and arr[0] != "8": print("NO") elif n == 11 and arr[0] == "8": print("YE...
n = int(input()) if n % 3 <= 1: print(1, 1, n-2) else: print(1, 2, n-3)
class rankMatrix(): def __init__(self, matrix): self.rows = len(matrix) self.cols = len(matrix[0]) def swap(self, matrix, row1, row2, col): for i in range(col): temp = matrix[row1][i] matrix[row1][i] = matrix[row2][i] matrix[row2][i] = temp def r...
#4.1 myList=[7,9,'a','cat',False] print myList #4.2 #a myList.append(3.14) myList.append(7) print myList #b myList.insert(2,'dog') print myList #c myList.index("cat") print myList #d myList.count(7) print myList #e myList.remove(7) print myList #f myList.pop(myList.index('dog')) print myList ...
""" The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ def prime_factors(n): "Returns all the prime factors of a positive integer" factors = [] d = 2 while (n > 1): while (n % d == 0): factors.append(d) n /= ...
"""" https://open.kattis.com/problems/nodup https://repl.it/repls/ShoddySuperBagworm different inputs: THE RAIN IN SPAIN IN THE RAIN AND THE SNOW """ string_input = input().split() flag = True for i in string_input: count = string_input.count(i) if count > 1: print("no") ...
# Exercise 5 from pathlib import Path import numpy as np import pandas as pd import xarray as xr import urllib.request # import functions from utils here data_dir = Path("data") solution_dir = Path("solution") # 1. Go to http://surfobs.climate.copernicus.eu/dataaccess/access_eobs.php#datafiles and # download the ...
''''' You are here: Home / Basics / Date and Time in Python Date and Time in Python Author: PFB Staff Writer Last Updated: August 27, 2020 Date and Time in Python In my last post about datetime & time modules in Python, I mostly used the strftime(format) method to print out the dates and times. In this post, I will s...
maior = 0 salarios = [ [float(input("Digite seu salário: ")), float(input("Digite seu salário: ")), float(input("Digite seu salário: "))], [float(input("Digite seu salário: ")), float(input("Digite seu salário: ")), float(input("Digite seu salário: "))], [float(input("Digite seu salário: ")), float(...
# Vasya was appointed the manager of the tourist group and he approached the preparation responsibly, # compiling a food guide indicating calories per 100 grams, # as well as the content of proteins, fats and carbohydrates per 100 grams of product. # He could not find all the information, so some cells were left blank ...
''' Product Inventory Project - Create an application which manages an inventory of products. Create a product class which has a price, id, and quantity on hand. Then create an inventory class which keeps track of various products and can sum up the inventory value. (additional requirement: name, sku number, batch...
def insertion_sort(list): n = len(list) for i in range(1,n): key = list[i] j = i-1 while j >=0 and key < list[j]: list[j+1] = list[j] j -= 1 list[j+1] = key print(list) insertion_sort([2,1,0,5,6])
class Counter(object): def __init__(self,low,high): self.current = low self.high = high def __iter__(self): return self def __next__(self): if self.current > self.high: raise StopIteration else: self.current += 1 return self.current - 1 c=Counter(5,10) iterator = iter(c) while True: try: x=ite...
def left_slash(num): for i in range(int(num)): print("\\", end="") def right_slash(num): for i in range(int(num)): print("/", end="") def jump_line(num): for i in range(int(num)): print() def space(num): for i in range(int(num)): print(" ", end="") def upper_part(...
#place objects import tkinter as tk from tkinter import messagebox window = tk.Tk() window.title("My window") window.geometry("200x200") """"""""" #方法1: pack+side tk.Label(window, text=1).pack(side="top") tk.Label(window, text=1).pack(side="bottom") tk.Label(window, text=1).pack(side="left") tk.Label(window, text=1)...
# Read file into list with open("names.txt", "r") as f: for line in f.readlines(): names = line.split(",") names.sort() total = 0 for i in range(len(names)): #for name in names: sum = 0 names[i] = names[i].strip('\"').lower() for letter in names[i]: sum += (ord(letter) - ord('a') + 1) ...
#Printing hello limit=int(input()) for i in range(limit): print("Hello")
print("Quiz 2") # Marathon App using loops Quiz 2: # Declaration and intialization distance_to_cover = 102 # in miles distance_covered_by_first_walker = 0 # in miles per hour distance_covered_by_second_walker = 0 # in miles per hour walking = True while walking: # Start loop distance_covered_by_first_walker +...
# I reffered an article for this. Please # check it if you have trouble understanding this # Brief Introduction to OpenGL in Python with PyOpenGL # By Muhammad Junaid Khalid # https://stackabuse.com/brief-introduction-to-opengl-in-python-with-pyopengl/ # This code includes refernces using # unique reference code so th...
matrix = [] test = [] def countCharVal(): sum = 0 for val in test: sum += val print("Total sum of all decripted character values is {}".format(sum)) def testForEnglish(): isEnglish = False times = 0 # number of 'the ' found in text // 116 104 101 32 for index in range(3,len(test)): ...
print("Amicable Numbers Q21") #Evaluate the sum of all the amicable numbers under 10000. def divisorSum(num): sum = 0 for divisor in range(1,int(num/2)+1): #int(num/2+1) if num % divisor == 0: sum += divisor return sum total = 0 for n in range(1,10000): a = divisorSum(n) b =...