text stringlengths 37 1.41M |
|---|
def isPrime(n):
for i in range(2,int(pow(n,0.5))+1):
if n%i==0:
return False
return True
n,m=map(int,input().split())
prime=0
for i in range(n+1,m+1):
if isPrime(i):
prime=i
break
if prime==m:
print("YES")
else:
print("NO") |
# 1.6 Задача «Следующее и предыдущее»
number = int(input())
nextnum = number + 1
prevnum = number - 1
dot = '.'
print('The next number for the number', number, 'is', nextnum)
print('The previous number for the number', number, 'is', prevnum)
|
# 6.13 Задача «Количество элементов, равных максимуму»
i = int(input())
max_el = 0
amount = 1
while i != 0:
if i > max_el:
max_el = i
amount = 1
elif i == max_el:
amount += 1
i = int(input())
print(amount)
|
# 7.10 Задача «Переставить min и max»
digits = [int(i) for i in input().split()]
maxValue = max(digits)
indexMax = digits.index(maxValue)
minValue = min(digits)
indexMin = digits.index(minValue)
digits[indexMin], digits[indexMax] = digits[indexMax], digits[indexMin]
print(' '.join([str(i) for i in digits]))
|
# 2.6 Сколько совпадает чисел
# s = input().split()
# for i in range(len(s)):
# s[i] = int(s[i])
s = []
for i in range(3):
s.append((input()))
if s[0] == s[1] == s[2]:
print(3)
elif s[0] == s[1] or s[1] == s[2] or s[0] == s[2]:
print(2)
else:
print(0)
|
# 3.1 Последняя цифра числа
x = int(input())
print(x % 10)
|
# 3.4 Задача «Первая цифра после точки»
from math import floor
x = float(input())
f_x = floor(x)
fractional_x = (x - f_x) * 10
print(floor(fractional_x))
|
# B351 final project
# Author: Boqian Shi, Sophia Beneski, & Grant Dennany
# Basic game rules and the function find the winner
from itertools import combinations
class Winner:
'''
Takes 3 input lists: playerCards AICards, and middleCards and determines the winner
example use:
winner = Winner(playe... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 27 09:39:00 2021
@author: SOMDEB SAHA
"""
"""
code for creating a simple animation for an aeroplane
the motions are described in 2-D as:
x = 800*t
y = 200
"""
#importing required libraries
import numpy as np
import matplotlib.pyplot as plt
import matplotlib... |
courses = ['Arts', 'Physics', 'Chemistry', 'Maths']
courses_supplementary = ['French', 'Hindi']
num_range = list(i for i in range(31))
# read course by index
# 0,1 (2 not included)
print(courses[0:2])
# num_list[-9:], read the part in the brackets as "9th from the end, to the end." or "-9, onwards"
print(courses[-2... |
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
shortest = min(strs, key=len)
for i, ch in enumerate(shortest):
for other in strs:
if other[i]... |
class Solution(object):
def uniquePaths(self, m, n):
"""
time O(mn)
space O(mn0
:type m: int
:type n: int
:rtype: int
"""
if not m or not n:
return 0
if m == 1 or n == 1:
return 1
d = [[0] * n for _ in range(m)]
... |
# 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 maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
... |
def is_abecedarian(word):
word = word.lower()
for i in range(len(word) - 1):
if word[i] > word[i + 1]:
return False
return True
print(is_abecedarian('AbCA')) |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSubtree(self, s, t): #mei xie chu lai
"""
深度优先搜索暴力匹配
深度优先搜索枚举 ... |
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return sorted(s) == sorted(t)
def isAnagram1(self, s, t):
dic1, dic2 = {}, {}
for item in s:
dic1[item] = dic1.get(item, 0) + 1
... |
"""
冒泡排序
"""
def bubbleSort(arr):
for i in range(1, len(arr)):
for j in range(0, len(arr) - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
def bubbleSort_opt(arr):
for i in range(1, len(arr)):
swap = False
for j in range(0... |
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: None
"""
self.stack.append(x)
def pop(se... |
class Solution(object):
def reverseString(self, s):
"""
Do not allocate extra space for another array, you must do this by modifying the input array
in-place with O(1) extra memory.
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""... |
import re
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} #使用set更快
# vowels = set(list('aeiouAEIOU'))
s = list(s)
left, right = 0, len(s) - 1
whil... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def minDepth(self, root): #mei xie chu lai
"""
方法一:深度优先搜索
首先可以想到使用深度... |
class Solution:
def findLongestWord(self, s, dictionary) :
dictionary = sorted(dictionary, key=lambda x: (-len(x), x))
print(dictionary)
for word in dictionary:
i = 0
for char in s:
if i < len(word) and word[i] == char:
i += 1
... |
"""
输入两个链表,找出它们的第一个公共节点。
如下面的两个链表:
在节点 c1 开始相交。
示例 1:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
示例 2:
输入:... |
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
res = {}
ll = []
from collections import Counter
n1 = Counter(nums1)
n2 = Counter(nums2)
for each... |
"""
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
注意:本题与主站 206 题相同:https://leetcode-cn.com/problems/reverse-linked-list/
"""
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
... |
from pythonds.basic import Stack
class Solution(object):
def isValid_stack(self, s): #导入栈模块
"""
:type s: str
:rtype: bool
"""
opens = '([{'
closes = ')]}'
parstack = Stack()
balance = True
for each in s:
if each in '([{':
... |
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
substring = [s[0]]
count_max = 1
for i in range(1, len(s)):
if s[i] not in substring:
substring.a... |
"""
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
示例1
输入
{67,0,24,58}
返回值
[58,24,0,67]
"""
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
res = []
while listNode:
res.append(listNode.val)
listNode = listNode.next
return res[::-1]
... |
"""
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.10000, 3
输出: 9.26100
示例 3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
-100.0 < x < 100.0
n 是 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1] 。
"""
class Solution(o... |
class Solution(object):
def majorityElement(self, nums):
"""
Hash Map
Time O(n)
Space O(n)
:type nums: List[int]
:rtype: int
"""
from collections import Counter
dic = Counter(nums)
max_val = max(dic, key=dic.get)
return max_val
... |
# 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 isSameTree(self, p, q):
"""
Recursion
time O(N)
space O(log(n)) in the best case of c... |
class Solution(object):
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype
"""
for i in range(1, len(s)):
if s[:i] * (len(s) // i) == s:
return True
return False
def repeatedSubstringPattern_cool_solution(self, str):
... |
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x <0:
return False
reversed_number = int(str(x)[::-1])
if reversed_number == x:
return True
else:
return False
if __name__=="__... |
class Solution(object):
def containsDuplicate(self, nums):
"""
or seen method in hash map
:type nums: List[int]
:rtype: bool
"""
from collections import Counter
if not nums:
return False
dic = Counter(nums)
return not max(dic.values... |
# 함수 기간 주소록 관리 프로그램
import sqlite3
# Dao : Data Access Object
class SqliteAddressDao:
"Sqlite에 주소록 입출력을 담당하는 클래스"
def __init__(self,filename):
self.conn = sqlite3.connect(filename)
self.cursor = self.conn.cursor()
def __del__(self):
self.cursor.close()
self.conn.close()
... |
#this program RSA encrypts a message from the user
from __future__ import print_function
import math
def gcd(x,y):
a=max(x,y)
b=min(x,y)
while(b!=0):
c=a%b
a=b
b=c
return a
def phi(x,y):
phicount=1
phicount=x*y-x-y+1
return phicount
def lin_soln(a,b):
x=1
... |
#PART 1: Terminology
#1) Give 3 examples of boolean expressions.
#a) 1 == 1
#b) 2 >= 3
#c) "Hello" != "bye"
# 3 points
#2) What does 'return' do?
# returns some form of output from a function
# 0 points
#
#
#3) What are 2 ways indentation is important in python code?
#a) clearly separates different parts of code
#b) te... |
import unittest
from .models import News,Sources
class NewsTest(unittest.TestCase):
'''
test instance to check the behavior of the news class
'''
def setUp(self):
'''
This method runs before every test
'''
self.news1 = News("New York Times", "Trump is a genius", "I don... |
# Using int() and float()
# a = input("Enter a string with letters,numbers,symbols")
# b = int(a) # Returns an error
# print(b)
# b = int("5.39") # A string that is float
# print(b) # Returns an error
# b = int(5.39) # float value
# print(b) # Returns the nearest integer sma... |
# for(start integer,stop integer,step for increment or decrement)
for i in range(1, 20, 2):
print(i)
|
ex_1 = (3.23*100+0.80*100)/100
ex_2 = 5/2 # Division
ex_3 = 5*2 # Multiplication
ex_4 = 5+2 # Addition
ex_5 = 5-2 # Subtraction
ex_6 = 5 % 2 # Modulo
ex_7 = 5//2 # Floor-Division
ex_8 = 5**2 # Exponentiation
print(ex_1)
print(ex_2)
print(ex_3)
print("Addition", ex_4)
print(ex_5)
print(ex_6)
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 22 15:31:19 2021
@author: 57314
"""
# Elaborar una función que reciba tres enteros y nos retorne el valor promedio de los mismos
def retornar_promedio(v1,v2,v3):
promedio=(v1,v2,v3)/3
return promedio
#
valor1=int(input("ingrese primer valor:"))
... |
from math import sqrt
def task_num_107():
""" Дано целое число m > 1 Получить наибольшое целое к, при котором 4^к < m """
m = int(input('\'Task 107\' Input your natural number : '))
counter = 1
a = 4
while a < m:
a *= a
counter += 1
return counter
def task_num_243_a():
""... |
import searchProblem;
import searchNode;
import state;
import cell;
import PriorityW;
import maze;
import queue;
class GCA(searchProblem.searchProblem):
"""description of class"""
def __init__(self):
self.myname = "GCA"
def search(self, maz, strategy, visualize):
print("ahmed");
... |
"""
Created by YASH MODI
CST8333_351
Assignment 4
"""
import Assign4_Controller
choice = ""
# Start the program
Assign4_Controller.start()
# loop for display menu
while choice != "y":
print("Coded by YASH MODI\n\n")
print("A.Display data entries\n" +
"B.Create data entries\n" +
"C.Edit ... |
from tkinter import *
#Raiz
raiz = Tk()
#Frame
miFrame = Frame(raiz)
miFrame.pack()
#Label
miLabel = Label(miFrame, text = "Nombre")
miLabel.grid(row = 0 , column = 0 , padx = 10,pady = 10)
#Texto
miTexto = Entry(miFrame)
miTexto.grid(row = 0 , column = 1, padx = 10,pady = 10)
raiz.mainloop() |
not_primes = []
def is_prime(number):
if number in primes:
return True
for factor in range(2, number):
if number % factor == 0:
not_primes.append(number)
return False
primes.append(number)
return True
def Sieve_of_Eratsthenes(limit):
primes = range(2, limit)
for i in primes:
not_primes = range(i*i... |
def sum_of_divisors(number):
total = 0
for divisor in range(1, (number / 2) + 1):
if number % divisor == 0:
total += divisor
return total
def is_abundant_number(number):
if sum_of_divisors(number) > number:
return True
abundant_list = [number for number in range(1, 28123) if is_abundant_number(number)]
ab... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 1 10:18:38 2017
@author: carles
"""
from games import Game
import random
class Catch(Game):
def __init__(self, frames_used):
Game.__init__(self, 10, 10, frames_used)
self.player_width = 3
# self.player_pos... |
#!/usr/bin/python
def getSubStrings(s):
startingPoint = 0
max = len(s) - 1
retVal = []
while startingPoint < max:
for i in xrange(1,len(s)+1):
substr = s[startingPoint:i]
if substr:
retVal.append(substr)
startingPoint+=1
retVal.append(s[max])
... |
def sum_square_diff(n=100):
sq = [i**2 for i in range(1, n+1)]
return sum(range(1, n+1))**2 - sum(sq)
if __name__ == "__main__":
res = sum_square_diff(100)
print(res) |
#!/usr/bin/env python
# concatenate.py
# Iterate over a range of values
for num in range(1,10):
# Use the modulo operator to get the remainder after division
# If the remainder after dividing by 2 is zero, the number is even
if num % 2 == 0:
print(str(num... |
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
class MyString(str):
def __str__(self):
return self[::-1]
print('Hello, World.')
print('Hello, World.'.upper())
print('Hello, World.'.lower())
print('Hello, World.'.capitalize())
print('Hello, World.'.swapcase())
print('Hello, World.'.title(... |
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
animals = ( 'bear', 'bunny', 'dog', 'cat', 'velociraptor' )
for pet in animals:
print(pet, end = " ")
print()
for i in range(10):
print(i, end = " ")
print()
for i in range(10):
print(i, end = " ")
if i == 5:
break
else:
p... |
#import numpy module
import numpy as np
#define numpy array as input
x=np.array([1,2,3,4,5])
# define the no of column
N =3
#Show vander array out put Method1
np.vander(x,increasing=True)
#show Vander array out with Method2
np.column_stack([x**(N-1-i) for i in range(N)])
|
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="2zkNKcz&EOZaRjc$",database="library")
mycursor=mydb.cursor()
BorrowersID=int(input("ENTER YOUR BORROWER_ID:- "))
mycursor.execute("INSERT INTO BOOKS [borrowers_ID] VALUES(BorrowersID)")
bookID=input("ENTER THE BOOK'S ID:- ")
... |
"""
This module tests the comment_validator methods
"""
import unittest
from app.api.v1.utils.comments_validator import CommentsValidator
class TestQuestionsValidator(unittest.TestCase):
def setUp(self):
""" Initializes app """
self.comment = {
"comment": "This is a comment",
... |
from flask import Flask, render_template # use Flask to render a template
from flask_pymongo import PyMongo # use PyMongo to interact with Mongo database
import scraping # to use scraping code, convert Jupyter notebook to Python
# Set up Flask
app = Flask(__name__)
# Use flask_pymongo to set up mongo connectio... |
"""
Name: Thomas Reus
Student-id: 11150041
Project: dataprocessing
This program does:
- Creates a dictionary from a
.csv file
- Creates a .json file from the
dictionary
"""
import csv
import json
# name of the input file
INPUT_NAME = "Bodemgebruik_data"
def create_dictionary(input_csv):
"""
Creates a ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 13:14:04 2020
@author: Ryan.Worth
"""
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
##1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#By considering the terms in the Fibonac... |
from random import randint
from time import clock
class Ponto:
def __init__(self):
self.x = 0
self.y = 0
self.movs = [self.cima, self.direita,
self.baixo, self.esquerda]
def movimento(self, r = 0):
#Gera um número aleatório para a direção
... |
'''
author: Ajay Tulsyan
email: atulsyan@wpi.edu
last update: 03/07/2020
Intro: This is code contains three basic search algorithms such as Breadth First Search,
Depth First Search, and Dijkstra, all the three algorithms are written as methods of a
class Graph. The alogorithms are built using adjecency matrix.
Note: ... |
import string
import random
from PyDictionary import PyDictionary
def getPasswordLen():
length = int(input("How long do you want your password: "))
return length
def useDigits():
answer = input("Do you want to use digits? True or False")
return answer.strip()
def useUpperLetters():
a... |
def quick_sort(L,low,high):
i=low
j=high
if i>=j:
return L
key=L[i]
while i!=j:
while i<j and L[j]>=key:
j=j-1
L[i]=L[j]
while i<j and L[i]<=key:
i=i+1
L[j]=L[i]
L[i]=key
quickSort(L,low,i-1)
quickSort(L,j+1,high)
return L
if __name__=='__main__':
print(quick_sort([3,7,24,5... |
#Print a singly linked list from tail to head.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
#运用栈“后进先出”
def printLinkedList1(self,head):
stack=[]
while head:
stack.append(head.val)
head=head.next
... |
import nltk
import re
import string
import pandas as pd
import numpy as np
# NKTK
from nltk.corpus import wordnet as wn
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
# Gensim
import gensim
import gensim.corpora as corpora
from gensim.utils import simpl... |
"""
This module provides a listbox with dynamic content that
can be updated by calling it's update function.
"""
from ..ui import create_listbox
class DynamicListBox(object):
"""
A listbox with dynamic content.
"""
def __init__(self, update_func, _listbox):
"""
@param update_func: fu... |
# Given a hotel which has 10 floors [0-9] and each floor has 26 rooms [A-Z]. You are given a sequence of rooms, where + suggests room is booked, - room is freed. You have to find which room is booked maximum number of times.
#
# You may assume that the list describe a correct sequence of bookings in chronological ord... |
# Imagine you have a special keyboard with all keys in a single row. The layout of characters on a keyboard is denoted by a string keyboard of length 26. Initially your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from ... |
def intersection(st, ave):
"""Represent an intersection using the Cantor pairing function."""
return (st+ave)*(st+ave+1)//2 + ave
def street(inter):
return w(inter) - avenue(inter)
def avenue(inter):
return inter - (w(inter) ** 2 + w(inter)) // 2
w = lambda z: int(((8*z+1)**0.5-1)/2)
def taxicab(a,b... |
def g(n):
if n <= 3:
return n
else:
return g(n-1) + 2 * g(n - 2) + 3 * g(n - 3)
def g_iter(n):
if n <= 3:
return n
else:
i = 4
a,b,c = 1,2,3
while i <= n:
a,b,c = b,c,(c + 2 * b + 3 * a)
i += 1
return c
|
import cv2
import numpy as np
def detect_finger_by_hsv(frame, l_hsv, u_hsv):
"""
detect the color set by the arguments l_hsv and u_hsv.
this function mask out the color outside the range and return the filtered image
:param frame:
:param l_hsv: list of lower HSV values
:param u_hsv: list of up... |
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
if not (board and board[0]):
return False
for r, row in enumerate(board):
for c, val in enumerate(row):
if val == word[0]:
if self.search(board, r, c, word... |
class Solution:
def isValid(self, s: str) -> bool:
ls = []
for char in s:
if char == '(' or char == '[' or char == '{':
ls.append(char)
elif char == ')':
if len(ls) == 0 or ls[-1] != '(':
return False
else:
... |
class Solution:
def isUgly(self, num: int) -> bool:
if num <= 0:
return False
x = num
while x % 2 == 0:
x /= 2
while x % 3 == 0:
x /= 3
while x % 5 == 0:
x /= 5
return x == 1
|
class Solution:
def isPalindrome(self, s: str) -> bool:
front = 0
end = len(s) - 1
while end > front:
while front < end and not s[front].isalnum():
front += 1
while end > front and not s[end].isalnum():
end -= 1
if ... |
import sys
import readline
from atexit import register
from interpreter.builtins import namespace
from interpreter.money import Currency
from interpreter.parser import Parser
register(Currency.save)
def interpret(expression):
try:
parser = Parser(expression)
node = parser.parse()
result... |
import math, numpy as np,random as rand
from tkinter import *
from tkinter import messagebox
from tkinter.filedialog import askopenfilename
np.set_printoptions(precision=15)
root = Tk()
canvas = Canvas(root, width=500, height=500)
# ------------------------------------------------------------------------------
# Func... |
#Please run the program directly. There is a print statement for each function.
# Notes: Followed modular approach where one function is passed into other functions
student=['adam','john','james','alice','sarah']
module=['cs','maths','geography','english']
mark=[[90,-1,70,85],[-1,90,50,60],[40,70,-1,60],[75,80,60,70],... |
class Solution(object):
def nextPermutation(self, nums):
"""
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending o... |
# import math
n = int(input('Enter number of teams: '))
passengers = n*15
# num_small = int(math.ceil(passengers/10)) #number of small buses
# math.ceil(x) returns the smallest integer not less than x.
small = 0
big = 0
cost = 0.0
min_num_small = small # to keep track of number of small buses which gives minimum cost
... |
# script : printVertical.py
# declare and call a function
# with an argument, but no return value
def printVertical(x):
"""Print x vertically"""
for c in str(x):
print(c)
printVertical("String")
printVertical(42)
|
# function returns list of all elements that occur multiple times in both lists
def multiple_elements(list1,list2):
result=[]
for i in list1: #for each item in list1
if list1.count(i)>1 and list2.count(i)>1 and i not in result:#each item that occurs more than once
result.append(i) #add item... |
# 13_marks.py
# Prompt for the number of marks and read them.
# Print the number of marks entered and the average (arithmetic mean) of marks
# Print the highest and lowest marks
# use definite loop - for loop
n = int(input("How many marks to be entered: "))
if n > 0: # only print average if n > 0
mark = float(inp... |
# palindrome program to check if reverse and original of string are same or not.
quit = ""
while True: # run this loop until user enters blank
sentence = input("Enter a string: ") # ask user to enter string input
string1 = sentence.upper() # convert string to upper case to compare
mirror = string1[::-1] # ... |
# 스택 2개로 큐 자료구조 구현하기
class Queue():
# __변수명 : private / __변수명__ : public / _변수명 : protected
__stack1 = [] # private
__stack2 = [] # private
def __init__(self):
self.__stack1 = []
self.__stack2 = []
def push(self,data):
self.__stack1.append(data)
def pop(self):
... |
import numpy as np
import math
import random
import time
def select_algorithm():
algorithm = input("Select the algorithm you wish to use: " + '\n' +
"1. Forward Selection" + '\n' +
"2. Backwards Elimination" + '\n' +
"3. Propinqua Algorithm" + '\n'... |
#aprimore o desafio 093 para que ele funcione com vários jogadores, incluindo um sistema de visualização de detalhes do aproveitamento de cada jogador.
#leia o nome do jogador e quantas partidas ele jogou, depois leia a quantidade de gols feitos em cada partida, salve o total de gols
print('\033[34m')
jogador = dict()
... |
#simulando um caixa eletronico utilizando notas de R$50,20,10,1
print(f'\033[32m-='*20)
print('{:^40}'.format('BANCO'))
print(f'-='*20,'\033[m')
valor = int(input('Quanto você gostaria de sacar? R$ '))
dinheiro = 50
dintotal = 0
while True:
if dinheiro <= valor:
valor -= dinheiro
dintotal += 1
e... |
#Par ou impar com o PC
from random import randint
print('Eae vamos jogar par ou impar')
cont = 0
while True:
jogador = str(input('Par ou impar? ')).strip().upper(), int(input('Diga um numero: '))
computador = randint(0,10)
total = jogador[1] + computador
if total % 2 == 0:
resultado = 'PAR'
... |
#crie um programa que mostre o seu dobro e o seu triplo
n = int(input('Digite um numero: '))
dobro = n * 2
triplo = n * 3
raiz = n ** (1/2)
print('O numero que você digitou é: {}' .format(n))
print('O dobro dele é: {}' .format(dobro))
print('O triplo dele é: {}' .format(triplo))
print('A raiz quadrada dele é: {:.2f}' ... |
# leia o comprimento de três retas. Diga ao usuario se elas podem formar um triângulo
cores = {
'azul': '\033[34m',
'verde': '\033[32m',
'vermelho': '\033[31m',
'branco': '\033[7m',
'reset': '\033[m',
}
reta1 = float(input('Digite o valor da reta1: '))
reta2 = float(input('Digite o valor da reta2: '... |
#Conversor de moedas
#Real para dolar
real = float(input('Digite um valor: R$'))
dolar = real/ 5.29
print('Real: R${:.2f} \nDollar: ${:.2f}' .format(real,dolar)) |
# calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento
p = float(input('Valor do produto: '))
c = str(input('Forma de pagamento\n1 - Dinheiro\n2 - Cartão\n: '))
if c == '1' or c.lower == 'dinheiro':
print('Seu produto tem 10% de desconto e será {}'.format(p - (p * 10 / ... |
#Mostre a ficha de um jogador
def ficha(nome="<Desconhecido>", gols=0):
print(f'\033[34mO jogador {nome} marcou {gols} gols')
a = str(input('Nome: ')).capitalize()
b = str(input('Gols: '))
if b.isnumeric():
b = int(b)
else:
b = 0
if a.strip() == '':
ficha(gols=b)
else:
ficha(a,b)
|
#leia uma frase e mostre
#quantas vezes a letra "a" aparece
#em que posição ela aparece a primeira vez
#em que posição ela aparece a ultima vez
frase = str(input('Digite uma frase = ')).upper().strip()
print('A letra "A" aparece: {} vezes'.format(frase.count('A')))
print('A letra "A" aparece pela primeira vez na posiçã... |
print('\033[34m')
#leia 5 valores e guarde em uma lista:
valores = []
for c in range(0,5):
valores.append(int(input('Digite um valor: ')))
#mostre qual o maior e o menor e suas posições na lista
if c == 0:
maior = menor = valores[c]
else:
if valores[c] > maior:
maior = valores[c]... |
#ler uma quantidade indeterminada de numeros e somar
n = c = s = 0
n = int(input('Digite um número [999 Stop]: '))
while n != 999:
c += 1
s += n
n = int(input('Digite um número [999 Stop]: '))
print('Digitos: {}'.format(c))
print('Soma: {}'.format(s))
print('FIM\n') |
#cadastre varios valores em uma lista
print('\033[34m')
valores = []
while True:
n = (int(input('Digite um valor: ')))
if n in valores:
print('Este numero já foi adicionado')
else:
valores.append(n)
while True:
continuar = str(input('Quer continuar [S/N]: ')).strip().upper()
... |
#verifique se o mesmo numero de parentes que abre também estão fechando
print('\033[34m')
expressão = str(input('Digite uma expressão com parenteses: '))
par = []
for l in expressão:
if l == "(":
par.append(l)
elif l == ")":
if len(par) == 0:
par.append(l)
break
e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.