text
stringlengths
37
1.41M
n = 1 i = 0 # Um abaixo do outro while n < 21: print(n), n = n + 1 # Um ao lado do outro print("") for i in range(1, 21): print(i, end = ' ')
n1 = 0 n1 = int(input("Informe um Valor : ")) if (n1 > 0): print("O valor é positivo") elif (n1 < 0): print("O valor é negativo") else: print("O numero eh igual a 0")
turno = "" print("-- Em que turno voce estuda?") print("-- Digite M para matutino, V para vespertino ou N para noturno") turno = input("Opção escolhida: ").upper() if (turno == "M"): print("Bom dia!") elif (turno == 'V'): print("Boa tarde!") elif (turno == 'N'): print("Boa noite!") else: print("Valor...
nome = input('Informe seu nome: ') nome = nome.upper() nome_2 = list( nome ) nome_3="" for i in nome_2 : nome_3 += i print(nome_3)
frase = 'insira a frase aqui a ser analisada' contagem_espaco = int(frase.count(" ")) contagem_vogais = 0 for i in 'aeiou' : contagem_vogais += int(frase.count(i)) print("Espaços:{0}, vogais:{1}".format(contagem_espaco,contagem_vogais))
# -*- coding: utf-8 -*- """ Created on Wed Aug 1 21:55:05 2018 @author: Toby """ number=int(input("請輸入大於一的整數:")) for a in range(2,number): if (number%a==0): print("%d不是質數!"%(number)) break else: print("%d是質數!"%(number))
# -*- coding: utf-8 -*- """ Created on Tue Jul 31 12:43:20 2018 @author: Toby """ x=int(input("請輸入成績:")) if(x>=90): print("優等") elif(x>=80): print("甲等") elif(x>=70): print("乙等") elif(x>=60): print("丙等") else: print("丁等")
# -*- coding: utf-8 -*- """ Created on Tue Jul 31 20:23:29 2018 @author: Toby """ a=0 for x in range (1,int(input("請輸入正整數:"))+1): a+=x print("1到"+str(x)+"的整數合為"+str(a))
#Faça um programa que tenha uma função chamada ficha(), # que receba dois parâmetros opcionais: o nome de um jogador e quantos gols ele marcou. # O programa deverá ser capaz de mostrar a ficha do jogador, mesmo que algum dado não tenha sido informado corretamente. def ficha(nome = ''.strip(), gols = 0): print...
frase = input('digite uma frase ') a = len(frase) b = frase.count('a') c = frase.find('a') inv = frase[::-1] p = inv.find('a') r = a - p print('a letra a aparece {} vezes, aparece pela primeira vez o espaço {} e aparece pela ultima vez no espaço {}'.format(b,c,r))
#Crie um programa que tenha uma dupla totalmente preenchida com uma contagem por extenso, # de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso. extenso = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze',...
sexo = '' while sexo == '': sexo = input('qual o seu sexo, 1- masculino, 2- feminino: ') if sexo == '1': print('sexo masculino') exit() if sexo == '2': print('sexo feminino') exit() else: sexo = ''
numero = input('digite um numero entre 1 e 9999 ') a = numero[0] b = numero[1] c = numero[2] d = numero[3] print('unidade {}\n dezena {}\n centena {}\n milhar {}'.format(d,c,b,a))
'''Classe Bola: Crie uma classe que modele uma bola: Atributos: Cor, circunferência, material Métodos: trocaCor e mostraCor''' class Bola: def __init__(self, cor, circunferencia, material): self.cor = cor self.circunferencia = circunferencia self.material = material def tro...
num1 = float(input('Digite um numero ')) num2 = float(input('Digite outro numero ')) print('numero 1: {}\nnumero 2: {}'.format(num1,num2)) if num1 > num2: print('O numero 1 é maior ') elif num2 > num1: print('O numero 2 é maior ') else: print('Os números nao tem diferença ou seja sao iguais ')
import sys sexo = str(input('Qual o seu sexo (feminino) ou (masculino)? ')).lower() if sexo == 'feminino': print('mulheres nao tem alistamento obrigatorio') sys.exit() id = int(input('Qual seu ano de nascimento? ')) ano = 2019 - id anoda = id + 18 alist = 18 - ano if ano == 18: print('O de...
x = int(input('Digite um número para fazer a tabuada até o 10: ')) y = 1 while y <= 10: print(f'{x} X {y} = {x*y}') y = y + 1
#Defining the ride_costCalc function def ride_costCalc(pickup_time,drop_off_time): # Calculate_fair function ride_time = drop_off_time-pickup_time #Time in minutes used for a ride ride_cost=0 if ride_time<=30: ride_cost=0 elif ride_time>30 and ride_time<=60: ride_cost=1 elif ride_time>60 and ride_time<...
# -*- coding: utf-8 -*- """ Created on Sun Mar 18 21:16:22 2018 This script will clean up our terrorism event table. It will then create a tableby reading from the referenced csv file. The csv file had minor datamunging done in excel as well, including: -- eliminating columns we were not interested in. -- ...
from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger import time def mesclarPDF(): documento1 = input("Digite o caminho do arquivo 1: ") documento2 = input("Digite o caminho do arquivo 2: ") caminhos = [documento1,documento2] documentos_unificados = 'C:\\Projetos\\Python\\documentos\\Art...
# The task you have to perform is “Your Age In 2090”. This task consists of a total of 10 points to evaluate your performance. # Problem Statement:- # Take age or year of birth as an input from the user. Store the input in one variable. Your program should detect whether the entered input is age or year of birth and ...
import math x = float(input("Enter x:")) y = float(input("Enter y:")) # координаты прямоугольника x1 = -1 x2 = 6 y1 = -2 y2 = 1 # центр окружности и радиус yc = 0 xc = 2 r = 3 #прямая линия y=kx+b k = 1 b = -2 if(y<k*x+b): if((x-xc)**2+(y-yc)**2<r**2): if(x1<x<x2) and (y1<y<y2): print("Обл.4"...
#82.题目:计算字符串中子串出现的次数。 str1=input("请输入一个字符串:") str2=input("请输入一个字符串:") print(str1.count(str2))
#58.在一个长字符串中查找短字符串的位置 str1 = input('请输入第一个字符串:') str2 = input('请输入第二个字符串:') print(str1.find(str2))
#71.题目:循环输出列表 list1 = [1, 2, 3, 4, 5] for i in range(len(list1) - 1): print(list1[i], end=' ') print(list1[i + 1])
a_list=list(input('请输入一行字符:')) letter=[] space=[] number=[] other=[] for i in range(len(a_list)): if ord(a_list[i]) in range (65,91) or ord(a_list[i]) in range(97,123): letter.append(a_list[i]) elif a_list[i]==' ': space.append(' ') elif ord(a_list[i]) in range(48,58): number.append...
sum,n=0,1 while n<=100: sum=sum+n n=n+1 print("1+2+3+...+100=",sum)
def hourglassSum(arr): # Write your code here w = len(arr[0]) h = len(arr) _max = 0 if w<3 or h<3: print("array dimension is not enough for hourGlass implementation") else: rowLoop = w-2 columnLoop = h-2 print(columnLoop) #columnLoop--------- for ...
# Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree link node # @return nothing def connect(self, root): ...
#!/usr/bin/env python3 """Turning an LED on as long as the switch is pressed""" import RPi.GPIO as GPIO OUTPIN = 15 SWITCHPIN = 21 GPIO.setmode(GPIO.BOARD) GPIO.setup(OUTPIN, GPIO.OUT) GPIO.setup(SWITCHPIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) status = True def switch_led_status(channel): """detects if the LED is...
from math import sqrt def distance(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 return sqrt(dx*dx + dy*dy) print(distance (0,0, 3,4))
#!/usr/bin/env python """ Prints word counts for given files. """ import sys if len(sys.argv) < 2: # No filenames given, print usage info. print "USAGE: python {0} FILE1 [FILE2] ...".format(sys.argv[0]) print "Prints the number of words per file given." sys.exit() for filename in sys.argv[1:]: tr...
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib.pyplot as plt def heat_equation(t0, t1, dt, n, m, u, f, nu, verbose=False): """ Solves heat equation where t0 is start time, t1 is end time, dt is time step, n is rectangle is rectangle width, m is rectangle height, u are the initial val...
#Getting an input: NOTE this works when getting text fromm the user # name= input("Enter your name: ") # print("Hello " + name, "Welcome home for breakfast") # This is use for getting number from the user # num= eval(input("Enter a number: ")) # print("Your number square: ", num*num) # NOTE:The (eval) function conve...
name_surname_birth_date = input("Podaj swoje imie, nazwisko i date urodzenia: ") print(f"Twoje dane to: {name_surname_birth_date}")
# 题目:输入三个整数x,y,z,请把这三个数由小到大输出 while True: arr = [] for i in range(1, 4): item = int(input('请依次输入三个整数')) arr.append(item) brr = arr.reverse() print('排序后的数组', arr, brr)
# 题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身 arr = [] def getArr(min, max): for i in range(min, max): ge = i % 10 shi = i // 10 % 10 bai = i // 100 if ge**3 + shi**3 + bai**3 == i: arr.append(i) return arr print('水仙花数组', getArr(100, 1000))
# 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数 obj = {} while True: astr = str(input('输入一串字符串')) print(astr) # for i in range(astr):
"""Find the smallest integer in the array (7 kyu). Given an array of integers your solution should find the smallest integer. For example: Given [34, 15, 88, 2] your solution will return 2. Given [34, -345, -1, 100] your solution will return -345. You can assume, for the purpose of this kata, that the supplied array ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 26 14:10:16 2020 @author: vanessa """ # functions for iterators for efficient looping from itertools import groupby import numpy as np import pandas as pd from scipy.stats import linregress def aggregate_returns(returns,convert_to): """ ...
from Tkinter import Tk, Canvas import math, time class Planet(): def __init__(self, x, y, space, color): self.x = x self.y = y self.space = space self.color = color self.radius = 5 self.draw() def draw(self): self.id = self.space.create_oval(self.x - se...
#Output # enter the size:4 # 1 1 # 1 2 2 1 # 1 2 3 3 2 1 # 1 2 3 4 4 3 2 1 n=int(input("enter the size:")) for i in range(1,n+1): for j in range(1,i+1): print(j,end=" ") x=(2*n)-(2*i) for j in range(x): print(" ",end=" ") ...
def tower_of_brahma(n,A,C,B): if n == 1: print("Move disk {0} from rod {1} to rod {2}".format(n,A,C)) return tower_of_brahma(n-1,A,B,C) print("Move disk {0} from rod {1} to rod {2}".format(n,A,C)) tower_of_brahma(n-1,B,C,A) if __name__ == '__main__' : tower_of_brahma(3,'A','C','...
def merge_overlapping(intervals): merge_list = [] if len(intervals) == 0: return merge_list intervals.sort(key = lambda x: x[0]) tenmp_interval = intervals[0] for interval in intervals: if interval[0] <= tenmp_interval[1]: tenmp_interval[1] = max(interval[1],tenmp_interva...
An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, , of size , each memory location has some unique index, (where ), that can be referenced as (you may also see it written as ). Given an array, , of integers, print each element in reverse order a...
# -*- coding: utf-8 -*- from collections import defaultdict class StatCalculator(object): def median(self, data): new_list = sorted(data) if len(new_list) % 2 > 0: return new_list[len(new_list) / 2] elif len(new_list) % 2 == 0: return (new_list[(len(new_list) / 2)] +...
#problem=58 top=100000 primes = [2,3,5,7] for j in range(8, top): i = 0 div = primes[i] while div**2<=j and j%div!=0 and i < len(primes)-1: i+=1 div=primes[i] if j%div!=0: primes.append(j) #print(primes) print("primes array has been created") def isprime(num): ...
import Queue class Graph: def __init__(self, directed): self.graph = {} self.directed = directed def add_edge(self, first, second, depth=0): if first in self.graph and second not in self.graph[first] and second is not None: self.graph[first].append(second) elif fir...
class MarkovAlgorithm: class Rule: def __init__(self, l_part, r_part, terminal=False): self.l_part = l_part self.r_part = r_part self.terminal = terminal __special_symbol = "*" def __init__(self, rules): self.rules = rules def execute(self, word): ...
from itertools import combinations def distance(codes): return min(sum(bit1 != bit2 for bit1, bit2 in zip(code1, code2)) for code1, code2 in combinations(codes, 2)) def detected(hdistance): return hdistance - 1 def correct(hdistance): return (hdistance - 1) / 2 codes_array1 = ['11110', '01011', '000...
""" This functions in this module perform validation to check that their inputs of the needed types for this project. """ def is_vector(to_check): """ Checks if the argument is a single-leveled list, meaning that all of its contents are one of three acceptable types: Int, Float, or String. Args: ...
a=int(input()) b=int(input()) if a<2: print("Before") elif a>2: print("After") else: if b<18: print("Before") elif b>18: print("After") else: print("Special")
a=int(input()) if a%2==0: if (a//2)%2==0: print(2) else: print(1) else: print(0)
while 1: a,b,c=input().split() if a=="#":break if int(b)>17 or int(c)>=80:print(a, "Senior") else:print(a, "Junior")
n=int(input()) for _ in range(n): a,b=map(float,input().split()) c,d=map(float,input().split()) if a/b > c*c*3.14/d:print("Slice of pizza") else:print("Whole pizza")
for _ in range(int(input())): n=int(input()) for i in range(n): for j in range(n): print(f"{'#' if i==0 or i==n-1 or j==0 or j==n-1 else 'J'}",end='') print() print()
n=int(input()) r=0.0 l=list(map(float,input().split())) for i in l: r+=(i**3) print(f"{r**(1/3.0):.6f}")
n=int(input()) res=0 for i in range(n+1): for j in range(i, n+1): res+=i+j print(res)
n=int(input()) print("Gnomes:") for i in range(n): a,b,c=map(int,input().split()) if (a<b and b<c) or (a>b and b>c):print("Ordered") else:print("Unordered")
# Uses python3 def calc_fib(n): if (n <= 1): return n #initializing total_last(n-2)th and (n-1)th fibonacci number total_last=0 total_current=1 #also introducing variable that will tabulate fib_n (nth fib number) fib_n=0 for i in range(2,n+1): fib_n=total_last+total_curr...
def reachable(graph, node): reachable_nodes = [] nodes_to_travel = graph[node] #print(nodes_to_travel) while nodes_to_travel: current_node = nodes_to_travel.pop() #print(current_node) if current_node not in reachable_nodes: #print(graph[current_node]) ...
from functools import reduce values = [1,2,3,4,5, 6, 2, 3,6,7] def addthem(currentsum, nextelement): return currentsum + nextelement complicatedsum = reduce(addthem, values, 0) def buildset(currentset, nextelement): currentset.add(nextelement) return currentset setfromlist = reduce(buildset, values, se...
def bubblesort(dataset): for i in range(len(dataset)-1,0,-1): #O(n^2) performance due to the nested for loop for j in range(i): if dataset[i] > dataset[j+1]: temp = dataset[j] dataset[j] = dataset[j+1] dataset[j+1] = temp print("c...
# Import Game modules import pychallenge import tictactoe import typing #Main Menu print ("""Hello, welcome to our arcade! Which of the following games would you like to play? 1. Python Challenge 2. Text Adventure 3. Guess my Color 4. Tic Tac Toe 5.Exit/Quit """) ans=int(input("What would y...
def fib(n): a, b = 0, 1 c = a + b counter = 0 result = [] result.extend((a, b, c)) if n == 0: return 0 elif n == 1 or n == 2: return 1 else: while counter < n: # this here's a *wild* loop a, b = b, c c = a + b counter += 1 ...
from board import Block, Board import random from bfs import BFS class Generator: # accumulative probability P = { Block.BlockKinds.OBSTACLE: 0.05, Block.BlockKinds.PURPLE_CAR: 0.40, Block.BlockKinds.BLUE_CAR: 0.7, Block.BlockKinds.TRUCK:1.0 } def __init__(self): ...
""" A particular cell phone plan includes 50 minutes of air time and 50 text messages for $15.00 a month. Each additional minute of air time costs $0.25, while additional text messages cost $0.15 each. All cell phone bills include an additional charge of $0.44 to support 911 call centers, and the entire bill (inclu...
# -*- coding: utf-8 -*- """ Created on Thu Jan 21 17:21:12 2021 @author: Mohamed Amr """ import pandas as pd import math class DataPreProcessing: def get_data(path, label_path = "", shuffle = False): ''' Used to get feature matrix and label vector out of les. The feature matrix is a...
from types import MethodType class Student(object): # 控制对象可以添加的属性。在__sorts__ 不存在的属性不允许添加 slots__ = ("name", "age", "score") pass @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, (int, float)): raise ValueError('score must be an integer!') if ...
#Напишите программу, которая считывает целое число и выводит текст, аналогичный приведенному в примере (пробелы важны!). number = int(input()) print('The next number for the number',number, 'is', number+1) print('The previous number for the number',number, 'is', number-1)
def bouncingBall(h, bounce, window): counter = 0 if h <= window or bounce <= 0 or bounce >= 1 or h < 0 or window < 0: return -1 else: while h > window: if h * bounce > window: #ball passes up and down h = h * bounce counter = counter + 2 ...
#!/usr/bin/env python3 import random FIRST_MONEY = 10_000 BET = 1000 # ユーザーの辞書型を作る def create_user(user_name): return {'money': FIRST_MONEY, 'name': user_name} # userのお金を見てゲームが終わってるかを見る def is_finish_game(users): for user in users: if user['money'] <= 0: print("{}さんは破産しました".format(user[...
# -*- coding: utf-8 -*- ''' 第 06 题 author: Honglei1990 url:http://www.pythonchallenge.com/pc/def/channel.html 有一个按钮提示 Paypal 捐赠。图片一个裤子的图标 查看源代码提示 作者希望对 pythonchallenage 做出一些捐赠,想象一下作为解密游戏,是不是有其他玄机。 channel 管道。 源代码最上端显示 - zip -- 是不是跟这个模块有关呢 事实证明捐赠的和本关游戏毫无关系 zip指向 html <html> <!-- <-- zip --> 把channel 替换zip 登陆网页 提示 yes, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 4 10:20:25 2018 @author: madeline """ import pandas as pd import numpy as np import plotly plotly.tools.set_credentials_file(username='madelinelee', api_key='FW2B67yKVADiMx2Ahz5G') import plotly.plotly as py from plotly import tools import plotly...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 6 21:01:18 2021 @author: aswin """ import csv def read_data(filename): with open(filename,'r') as csvFile: datareader = csv.reader(csvFile,delimiter=',') headers = next(datareader) metadata = [] traindata = [] ...
#http://www.careercup.com/question?id=5747769461440512 #graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation #!usr/bin/env python class Solution: def __init__(self): pass def nextHigh(self, x): _len = 1 while x & (1 << (32 - _len)) == 0: _len += 1 _len = 32 - _len one = -1 zero = -1 i = ...
#http://www.careercup.com/question?id=15542726 #!usr/bin/env python class Solution: def __init__(self): self.matrix = [['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']] def remote(self, text): t...
def find_cart(list1, list2, n1, n2): for i in range(0,n1): for j in range(0,n2): print("\n" "\n" "{",list1[i],", ",list2[j],"}, ",sep="" , end="") # creating an empty list list1 = [] list2 = [] # number of elemetns as input m1 = int(input("Enter number of elem...
my_list = [6, 5, 3, 2, 2] while True: new_el_int = input('Введите натуральное число для его оценки в нашем рейтинге:\nДля выхода введите "Quit".') if new_el_int.isdigit() and new_el_int != 'Quit': new_el_int = int(new_el_int) i = 0 for el in my_list: if new_el_int <= el: ...
import numpy as np import math def levenshtein(x,y): ''' Author: Sungjun Han Description: computes levenshtein distance x : str y : str ''' dp = [[0]*(len(y)+1) for _ in range(len(x)+1)] for i in range(1, len(x)+1): for j in range(1,len(y)+1): if x[i-1] == y[j-1]: dp[i][j] = min(dp[i-1][j-1], d...
#my first programme in python3 def is_proper(sudoku): """ This function checks if all numbers in each row, column and subsquare are unique. """ return rows_proper(sudoku) and columns_proper(sudoku) and square_proper(sudoku) def rows_proper(sudoku): for row in sudoku: for i, element in enumerate(row): # ...
from collections import deque, defaultdict def dfs_topo(i, stack): explored.append(i) for edge in graph[i]: if edge not in explored: dfs_topo(edge, stack) stack.insert(0, i) def Toposrt(): stack = [] for i in range(1, len(graph) + 1): if i not in explored: ...
from collections import deque def bfs(graph, vertex): queue = deque() queue.append(vertex) explored = {vertex: True} level = {vertex: 0} while queue: temp = queue.popleft() for edge in graph[temp]: if edge not in explored: level[edge] = level[temp]+1 ...
def long_repeat(line: str) -> int: """ length the longest substring that consists of the same char """ max_count, count = 0, 0 letter = '' for symbol in line: if symbol == letter: count += 1 if count > max_count: max_count = count elif symbol != letter...
def frequency_sort(items): dct = dict() recorded_items, ans = [], [] for element in items: if element in recorded_items: continue recorded_items.append(element) count_element = items.count(element) if count_element in dct: dct[count_element] += [elem...
# Щедрый покупатель # Добавляет к счету чаевые в расчете 15 и 20 % от суммы # Дополнена возможностью выбора процента obed = float(input('Введите сумму за обед')) n = float(input('Сколько желаете оставить(в %)?')) chai_15 = obed * 1.15 chai_20 = obed * 1.20 chai_n = obed * (1+ n / 100) print('Сумма к оплате при 15...
'''Напишите программу, на вход которой подается одна строка с целыми числами. Программа должна вывести сумму этих чисел. Используйте метод split строки.  ''' s = 0 numbers = [int(i) for i in input().split()] for number in numbers: s += number print(s)
''' Напишите программу, на вход которой подаётся список чисел одной строкой. Программа должна для каждого элемента этого списка вывести сумму двух его соседей. Для элементов списка, являющихся крайними, одним из соседей считается элемент, находящий на противоположном конце этого списка. Например, если на вход подаётся ...
# Урок 5 задание 1 # Создайте программу, которая выводит список слов в случайном порядке. # На экране должны печаться без повторения все слова из представленного списка words = ['Создайте', 'программу', 'которая', 'выводит', 'список', 'слов', 'в', 'случайном', 'порядке'] import random while words: word ...
'''Напишите программу, на вход которой подаётся список чисел одной строкой. Программа должна для каждого элемента этого списка вывести сумму двух его соседей. Для элементов списка, являющихся крайними, одним из соседей считается элемент, находящий на противоположном конце этого списка. Например, если на вход подаётся с...
def count_consecutive_summers(num): s, count = 0, 0 i, first_num = 0, 0 while i <= num: if s == num: count += 1 s -= first_num first_num += 1 elif s < num: s += i i += 1 elif s > num: s -= first_num f...
# Урок 4 задача 2 # Печатаем текст наоборот # # word = input('Введите слово и получите его наоборот ') new_word = '' while word: length = len(word) - 1 new_word += word[length : ] word = word [:length] print(new_word.capitalize()) input('\nНажмите Enter для выхода')
def checkio(text: str) -> str: dct = {} for symbol in text.lower(): if symbol < 'a' or symbol > 'z': continue if symbol in dct.keys(): dct[symbol] += 1 else: dct[symbol] = 1 popular_symbol = sorted(dct.keys())[0] for key in sorted(dct.keys()):...
#Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". Example: biggie_size([-1, 3, 5, -5]) returns that same list, but whose values are now [-1, "big", "big", -5] print("---Biggie Size---") # def biggie_size(a_list): # for val in a_list: # if(int(val) > -1)...
var = 100 if var == 100: print "Value of expression is 100" elif var == 1000: print "Value of expression is 1000" else: print "Value of expression is not 100 or 1000" print "Good bye!"
def check_binary(word): ret = True for b in word: if b == '1' or b == '0': ret = True else: return False return ret def Xor(a,b): xor = '' for i,j in zip(a,b): if i == j: xor = xor + '0' else: xor = xor + '1' return...
"""Provide the user with a programming problem from r/DailyProgrammer and a language in which the problem should be solved. """ import argparse from itertools import chain from random import choice from datetime import datetime from dailyprogrammer.challenges import get_challenges from dailyprogrammer.utils import JSO...
import tkinter as tk import tkinter import pika class TextExtension( tkinter.Frame ): """Extends Frame. Intended as a container for a Text field. Better related data handling and has Y scrollbar now.""" def __init__( self, master, textvariable = None, *args, **kwargs ): self.textvariable = te...
class User: """ Class that generates new users. """ userList = [] def __init__(self, name, username, password): self.username = username self.name = name self.password = password def save_user(self): ''' function that saves User objects into userList ...
def find_max_min(values): min = values[0] for elm in values[1:]: if elm < min: min = elm max = values[0] for elm in values[1:]: if elm > max: max = elm res = set() res.add(min) res.add(max) return sorted(list(res))