text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
# Chapter 6 -- Creating Containers and Collectibles
# ----------------------------------------------------
# .. sectnum::
#
# .. contents::
#
# Existing Classes
# ##############################
# namedtuple
# ================================
from collections import namedtuple
BlackjackCard... |
'''
题目:取一个整数a从右端开始的4〜7位。
程序分析:可以这样考虑:
(1)先使a右移4位。
(2)设置一个低4位全为1,其余全为0的数。可用~(~0<<4)
(3)将上面二者进行&运算。
'''
a = int(input('input a number:\n'))
b = a >> 4
c=~(~0<<4)
d=b&c
print("%x"%(d)) |
'''
题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
'''
def inp(numbers):
for i in range(6):
numbers.append(int(input('输入一个数字:\n')))
p = 0
def arr_max(array):
max = 0
for i in range(1,len(array) - 1):
p = i
if array[p] > array[max] : max = p
k = max
array[0],array[k] = array[k],array[0]
def arr_min(array):
min = 0... |
class Node(object):
def __init__(self,name=None,value=None):
self._name=name
self._value=value
self._left=None
self._right=None
class HuffmanTree(object):
def __init__(self,char_weights):
self.a=[Node(part,char_weights[part]) for part in char_weights]
while len(self.a)!=1:
self.a.sort(key=lambda... |
#题目:将一个列表的数据复制到另一个列表中。
#
#程序分析:使用列表[:]。
a = list(range(10))
b = a[:]
print (b) |
'''
题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
'''
class Solution:
def LastRemaining_Solution(self, n, m):
# write code here
# 用列表来模拟环,新建列表range(n),是n个小朋友的编号
if not n or not m:
return -1
lis = list(range(n))
i = 0
while len(lis)>1:
i = (m-1 + i)%len(lis) # 递推公式
lis.pop(i)
ret... |
'''
题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数?
程序分析:请利用数轴来分界,定位。注意定义时需把奖金定义成长整型。
'''
income=int(input("净利润"))
arr =[1e6,6e5,4e5,2e5,1e5,0]
ra... |
import random, string
vowels = 'aeiouy'
consonants='bcdfghjklmnpqrstvwxz'
letters=string.ascii_lowercase
letter_input_1=input("What letter do you want? Enter 'v' for vowels, 'c' for consonants, 'l' for any letter: ")
letter_input_2=input("What letter do you want? Enter 'v' for vowels, 'c' for consonants, 'l' for any l... |
a=[]
a=[25,40,65,80,55,60]
a=[1,"hello",7,5]
print(a[2])
print(a[:2])
print(a[2:4])
a[2]=80
a[2:4]=[25,80,55,60]
a.append(80)
a.extend([25,80,55,60]
c=a+b
a.extend(b)
|
name = "Finn"
subjects = ["English", "Math", "Science", "Latin", "History"]
print("Hello " + name)
for i in subjects:
print("One of my classes is " + i)
countries = ["Germany", "South Africa", "Canada", "Great Britain", "Spain", "France", "Mexico", "China", "Indonesia", "Argentinia"]
for i in countr... |
#insertind an element in any desired position
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
self.next=None
def append(self,data):
n=Node(data)
if self.head is None:
... |
class Stack:
def __init__(self,size):
self.s=[]
self.n=size
self.i=0
def push(self,data):
if self.n>0 :
if data not in self.s:
self.n-=1
self.s.append(data)
else:
print('element already exists')
... |
def gates(s):
stack=[]
temp=0
for i in s:
if i=='(':
stack.append('(')
elif i==')':
if stack==[] or stack.pop()!='(':
return -1
temp+=1
if stack!=[] or temp==1:
return -1
return temp
s=input('enter gate notati... |
#Binary Tree with a single node
class Node:
def __init__(self,data):
self.left=None
self.right=None
self.data=data
class BinaryTree:
def __init__(self,root):
self.root=root
def print(self,root):
print(root.data)
T=BinaryTree(Node(20))
T.print(T.root... |
#adding nodes after a given node
#class for nodes
class Node:
#constructor for initialising list
def __init__(self,data):
self.prev=None
self.data=data
self.next=None
#class for doubly linked list
class DoublyLinkedList:
#co... |
"""
Python dict model
"""
from .Model import Model
class model(Model):
def __init__(self):
self.recipes = [{'recipe':'lasagna', 'ingredients':'olives, noodles, sauce, tomatoes', 'reviews':'its okay', 'time_to_cook':'ten minutes'},{'recipe':'peanut butter with jelly', 'ingredients':'bread, peanut, butter, ... |
# 1
total = input('What is the total amount for your online shopping?')
country = raw_input('Shipping within the US or Canada?')
if country == "US":
if total <= 50:
print "Shipping Costs $6.00"
elif total <= 100:
print "Shipping Costs $9.00"
elif total <= 150:
print "Shipping Costs $... |
# Напишите программу, которая обрабатывает результаты IQ-теста из файла “2-in.txt".
# В файле лежат несколько строк со значениями(не менее 4-х).
# Программа должна вывести в консоль среднее арифметическое по лучшим трем в каждой строке результатам(одно число).
a = []
n = []
t = True
f = open('2-in.txt')
for line... |
# Напишите программу, содержащую функцию вычисляющую функцию Эйлера для произвольного натурального числа.
# Программа должна считывать из файла массив чисел, находить ср.геометрическое значений функции Эйлера чисел массива.
def euler(n):
a = []
b = []
if n == 1:
return 1
for i in rang... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 4 23:10:05 2020
@author: phamk
"""
class Toyota:
def dungxe(self):
print("Toyota dừng xe để nạp điện")
def nomay(self):
print("Toyota nổ máy bằng hộp số tự động")
class Porsche:
def dungxe(self):
print("Porsche dừng xe để bơm ... |
def computeHCF(x, y):
# This function implements the Euclidian algorithm to find H.C.F. of two numbers
while(y):
x, y = y, x % y
return x
print("result=",computeHCF(300, 400))
|
"""
A rudimentary implementation of a Trie data structure that will suit our needs
for this project.
"""
class TrieNode:
def __init__(self, word, endOfLine=False):
self.word = word
self.endOfLine = endOfLine
self.children = set()
"""
Insert a node into the trie by adding it to its parent's list of children... |
import numpy as np
def menu_admin():
p = input('\nSelamat Datang di Aplikasi penyewaan kendaraan \n1. Tambah Data \n2. List data \n3. Keluar \ninput : ')
if p == "1":
tambah_data()
elif p == "2":
print("Status pinjaman kendaraan")
for x in arr_B:
for i in x:
print(i, end = " ")
... |
# !/usr/bin/env/python
# !-*- coding:utf-8 -*-
import socket
import os
import sys
HOST = '192.168.78.1'
PORT = 8888
def server(ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((ip, port))
# 开始监听
s.listen(1)
print('Listening at PORT:', port)
conn, a... |
"""
csv_writer_util.py
DESCRIPTION:
A wrapper and some logic around python's csv
library to write out csv files in various formats.
TO USE:
FILL THIS IN ~~~~
CREDITS:
- Logan Davis <ldavis@marlboro.edu>
Init date: 3/3/17 | Version: Python 3.6 | DevOS: MacOS 10.11 & <add here>
"""
import csv
class cs... |
def isArraySorted(A):
if len(A) == 1:
return True
return A[0]<=A[1] and isArraySorted(A[1:])
Array=[45,56,123,78,456,789]
if isArraySorted(Array):
print("The array is sorted")
else:
print("The array is not sorted") |
n=5
def factorial(num):
if num == 1:
return 1
return num*factorial(num-1)
ans = factorial(n)
print('factorial of {0} is {1}'.format(n, ans)) |
import calendar
import datetime
from decimal import Decimal
class BudgetFunctions:
def __init__(self):
self.balance = 0.00
self.expenses = {}
self.income = {}
self.month = 0
self.year = 0
self.income_counter = 0
self.expenses_counter = 0
def print_funct... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Convert from one temperature unit to another temperature unit."""
class ConversionError(Exception): pass
class InvalidInputError(ConversionError): pass
class NotIntegerError(Exception): pass
class LowLimitError(Exception): pass
def convertCelciusToKelvin(celcius):
... |
# N школьников делят K яблок поровну, не делящийся остаток остается в корзинке. Сколько яблок достанется каждому
# школьнику?
apples = int(input())
schools = int(input())
print(schools // apples)
|
# Запишите букву 'A' (латинскую, заглавную) 100 раз подряд. Сдайте на проверку программу, которая выводит эту строчку
# (только буквы, без кавычек или пробелов).
print('A' * 100, sep='')
|
# Дано натуральное число. Найдите цифру, стоящую в разряде десятков в его десятичной записи (вторую справа цифру или
# 0, если число меньше 10).
num = int(input())
print(num // 10 // 10 % 10)
|
#! usr/bin/env python
import string
# https://www.hackerrank.com/challenges/funny-string
def substract_letters(letter1, letter2):
"""Given 2 letters, returns the distance absolute between them
==> substract_letters("a", "z")
==> 25
"""
alph = string.lowercase
idx1 = alph.index(letter1)
i... |
#!/usr/bin/env python
"""
You have to make a function that receives an array
of strings representing times of day (in the format "HH:MM") and returns the integer
number of minutes between the two closest times.
00:00 can be represented as either "00:00" or "24:00", and you can be guaranteed that all other inputs will ... |
#! /usr/bin/env python
import pytest
"""
Write a function that compresses a string and returns it
eg. given a string like aaabbcccdff, return a3b2c3d1f2
"""
def iter_compress(input_string):
"""
Takes input string as input, returns compressed string.
Iterate over every character in input.
if the cha... |
#! usr/bin/env python
# https://www.hackerrank.com/challenges/fibonacci-modified
first, second, N = map(int,raw_input().split())
def func_fact(idx, first, second):
# funky fibonnaci, takes the first 2 values and returns value index idx
# T(n) = (T(n-1))**2 + T(n-2)
results = [first, second]
counter =... |
#! /usr/bin/env python
# https://www.hackerrank.com/challenges/taum-and-bday
def solve(num_black, num_white, price_black, price_white, price_sub):
if price_black + price_sub < price_white:
return num_black*price_black + num_white*(price_black + price_sub)
elif price_white + price_sub < price_black:
... |
#! usr/bin/env/python
sent = raw_input("")
final = ""
for idx, char in enumerate(sent):
if idx == 0:
final += (char.upper())
elif sent[idx - 1] == " ":
final += (char.upper())
else:
final += (char)
print final
|
#! /usr/bin/env python3
""" Given random 9 letters (possibly with repititions) and a dictionary
return the longest possible word """
with open('/usr/share/dict/words') as f:
dictionary = [x.lower() for x in f.read.splitlines()]
|
#! usr/bin/env python
# https://www.hackerrank.com/contests/zenhacks/challenges/candy-shop
import sys
def solve():
""" Requests input, creates a cache array and returns the answer,
using the method defined internally """
value = int(raw_input().strip())
coin_values = [1, 2, 5, 10, 20, 50, 100]
c... |
#importando as bibliotecas necessárias
import pandas as pd
import xlrd
#abrindo o arquivo
with open(r"C:\Users\maias\Documents\GitHub\CFB017-SAINT\exercicio_1\WHOPOPTB.xls") as WHOPOPTB:
#variável com o arquivo já lido pelo pandas
WHOTBDATA = pd.read_excel("WHOPOPTB.xls")
#pandas já reconhece que queremos a col... |
import sys
from operacoesCompra import *
class compraDeProdutos():
def __init__(self, estoque):
self._estoque = estoque
self._produtos = imprimeProdutos(self._estoque)
self._quantidade = imprimeQuantidades(self._estoque)
#self._total = calculaTotalCompra(self._estoque)
def __str__(self):
return f'[Estoq... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: omarkawach
"""
# Import packages
import geopandas as gpd
import matplotlib.pyplot as plt
# Load data
neighbourhoods = gpd.read_file("../../shapefiles/ONS/ons.shp")
hospitals = gpd.read_file("../../shapefiles/OttawaHospitals/Hospitals.shp")
# Plot data
fig, a... |
input = "abacabade"
#input = "abadabac"
def find_not_repeating_character(string):
occur_list = [0] * 26
for x in string:
if x.isalpha():
occur_list[ord(x) - ord('a')] += 1
min_occur_char_list = []
for i, occur in enumerate(occur_list, start = 0):
if occur == 1:
... |
#https://leetcode.com/problems/search-insert-position/description/
#binary search algortihm
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if target not in nums:
nums.append(target)
#sort values for binary search prepration
nums = sorted(nums)
... |
#!/usr/bin/env python
# coding: utf-8
# In[7]:
def naive_bayes(dataset_location):
import pandas as pd
import numpy as np
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, accuracy_score
# In[8]:
... |
n2=int(input("enter n"))
l=[]
c=0
for i in range(n2):
a=int(input())
l.append(a)
s=set(l)
print(list(s))
|
a=int(input("enter a number"))
l=[]
for i in range(0,a):
b=int(input("enter a number"))
l.append(b)
l.sort()
print(l)
|
MARS_WEIGHT_MULTIPLIER = 0.38
JUPITER_WEIGHT_MULTIPLIER = 2.34 # used to calculate weights on other planets
def weight_on_planets():
weightOnEarth = float(input("What do you weigh on earth? ")) # get user input then convert to float before calculations
weightOnMars = weightOnEarth * MARS_WEIGHT_MULTIPLIER
weightOnJ... |
# Write the code that:
# Prompts the user to enter a letter in the alphabet: Please enter a letter from the alphabet (a-z or A-Z):
# Write the code that determines whether the letter entered is a vowel
# Print one of following messages (substituting the letter for x):
# The letter x is a vowel
# The letter x is a cons... |
# -*-coding:Utf-8 -*
from data import *
from functions import *
# gettinf scores
scores = get_scores()
# getting words to be used
words = get_words()
# printing scores
print("Scores: ", scores)
#print("list of words: ", words)
# getting userName :
user = get_userName()
#if user doesn't exist, then getting added
if ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 9 12:52:07 2020
@author: tamanna
"""
#https://www.hackerrank.com/challenges/np-transpose-and-flatten/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
import numpy
r, c= input().split()
b=[]
for i in range(int(r)):
p=list(map(int, input().spl... |
# Create a array and find out the sum of the elements
import numpy as np
a = np.array([1, 2, 3])
print(np.sum(a)) |
'''
Python Program to display the Fibonacci sequence up to nth term using recursive function
'''
def fibonacci(num):
"""
Recursive function to print fibonacci sequence
"""
return num if num <= 1 else fibonacci(num-1) + fibonacci(num-2)
# Number of terms required
nterms = 10
print("Fibonacci sequenc... |
def hello_func():
pass
print(hello_func())
def hello_func():
return "Hello"
print(hello_func())
print(hello_func().upper())
def hell_fun(greet, name='Abhishek'):
return f'{greet}, {name} Function'
print(hell_fun('Hi'))
# *args allow arbitrary number of positional argumants
# may return a tuple
# ... |
lista = []
n = int(input("numero: "))
i = 1
while i <= n:
num = int(input("numero: "))
lista.append(num)
i += 1
print(lista)
numMayor = lista[0]
i = 1
while i < len(lista):
if(lista[i] > numMayor):
numMayor = lista[i]
i += 1
print("El numero mas alto es: ",numMayor) |
n = int(input("N Numero: "))
j = 1
x=1
while j <= n:
num = x
i = 2
cont = 0
while i < num:
if(num % i == 0):
cont += 1
i += 1
if(cont == 0):
print(num)
j += 1
x += 1 |
# Author: Adam Jeffries
# Date: 2/9/2021
# Description: A recursive function named is_subsequence that takes two string parameters
# and returns True if the first string is a subsequence of the second string, but returns False otherwise.
def is_subsequence(string1, string2):
if string1 == "":
return True
... |
"""
A simplistic ASCII-art generator that maps pixel brightness values to a set of
ASCII characters.
"""
from PIL import Image
palette = ['#', 'O', 'o', '.', ' ']
# Note: we could alternatively invert the image color scheme
# before converting to text using PIL.ImageOps.invert()
inverted_palette = list(reversed(palet... |
## below is the question
"""
A Narcissistic Number is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).
For example, take 153 (3 digits), which is narcisstic:
1^3 + 5^3 + 3^3 = 1 + ... |
#1.0 Introduction
"""
Welcome to Introduction for Health Data Analytics. In this first training task we will get familiarized with Python. Please if you haven't done so already download Anaconda from: https://www.anaconda.com/products/individual.
Anaconda comes with a bunch of data science packages already instal... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
x = [1,2,3]
y = [3,4,5]
x1 = [11,22,33]
y1 = [33,44,55]
plt.plot(x, y, label="First")
plt.plot(x1, y1, label="Second")
plt.xlabel('X-axis')
plt.ylabel("Y-axis")
plt.title("First graph")
plt.legend()
plt.show() |
"""
eng_base.py
Care English functionality.
"""
from utils import *
vowels = "aieou"
consonants = "bcdfghjklmnpqrstvwxyz"
def table_match(table, search):
for entry in table:
if all(
(search[i] == entry[i] or search[i] == "any" or entry[i] == "any")
for i in range(len(search))
):
return en... |
"""
eng_base.py
Core English functionality.
"""
from utils import *
vowels = "aieou"
consonants = "bcdfghjklmnpqrstvwxyz"
GR_CASES = {
"tense": (
"present",
"past",
"infinitive",
"imperative",
"present participle",
"past participle"
),
"number": ("singular", "plural"),
"person": ("fir... |
##
# Report the name of a shape from its number of sides
#
# Read the number of sides from the user
nsides = int(input("Enter the number of sides: "))
# Determine the name, leaving it empty if an unsupported number of sides was entered
name = ""
if nsides == 3:
name = "triangle"
elif nsides == 4:
... |
def TowerOfHanoi(n, start, middle, end):
if n==1:
print("move disk 1 from rod",start,"to rod", middle)
else:
TowerOfHanoi(n-1,start,end,middle)
print("Move disk",str(n),"from rod",start,"to rod",middle)
TowerOfHanoi(n-1, end, middle, start)
n=4
TowerOfHanoi(n, "A", "... |
"""
Dictionary Comprehension
Pense no seguinte:
Se quisermos criar uma lista, fazemos:
lista = [1, 2, 3 , 4]
tupla = (1, 2, 3 , 4) # 1, 2, 3, 4
conjunto = {1, 2, 3 , 4}
Se quisermos criar um dicionário
dicionario = {'a': 1,'b2': 2,'c': 3 ,'d': 4}
# SINTAXE
{chave: valor for valor in iterável}
- lista[valor for ... |
filename = input('Type the filename, please: ')
action = int(input('What do you want to do? If you want to read the file, type "0". If you want to write numbers into file, type "1" '))
if action == 0:
try:
reading = open(filename, 'r')
for line in reading:
print(line, end = '')
exce... |
a = 1
print(type(a))
print(type(1))
print(type(int))
print("----------------------")
s = "ann"
print(type(s))
print(type(str))
print(type(type))
print('-------------------')
class Hello():
pass
hello = Hello()
print(type(hello))
print(type(Hello))
"""
class类是由type这个类生成的对象 ,平常熟悉的对象是由类对象创建的对象,类又是由type创建的
object是所... |
import unittest
from CarRental import Car, ElectricCar, PetrolCar, DieselCar, HybridCar, CarFleet
# test the car functionality
class TestCar(unittest.TestCase):
def test_car_fleet(self):
car_fleet = CarFleet()
self.assertEqual(40, car_fleet.getNumAvailable())
car_fleet.rentCar(5)... |
from enum import Enum, unique
@unique
class CheckStatus(Enum):
"""
Used to identify the status of a security check
"""
OK = 'OK'
"""No anomalies detected; everything secure"""
WARN = 'WARN'
"""Anomalies have been detected; not clearly a threat, needs suspicion"""
ALERT = 'ALERT'
... |
"""
simple program to match to a given string from a given state space
"""
state_space = [
{'y': 1, 'Y': 1},
{'a': 2, 'A': 2},
{'s': 3, 'S': 3},
{'i': 4, 'I': 4},
{'r': 5, 'R': 5}
]
def match_space(str_to_match, state_space):
curr_index = 0
for x in str_to_match:
if curr_index < le... |
a = 7
for i in range(1, a-1):
if a % i == 0 :
print ("The given number ", i, "is not prime")
else:
print ("The given number ", i, "is prime")
|
#*********************************** Python 2 **************************************
def calculabonus( salario, montante):
return salario + ((montante * 15)/100)
nome = raw_input()
salario = float(input())
montante = float(input())
total = calculabonus(salario, montante)
print "TOTAL = R$ {0:.2f}".format... |
def areadocirculo (raio):
return 3.14159 * raio * raio
raio = float(input())
area = areadocirculo(raio)
print ("A={0:.4f}".format(area) ) |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# in place linear algorithm
# O(n) time, O(1) space
class Solution:
# @param A : root node of tree
# @return the root node in the tree
def flatte... |
#Función: Multiplicar dos numeros sin usar el signo de multiplicación
#Entradas: dos numeros que serviran como factores de la multiplicación
#Salidas: El valor resultante de la multiplicación
#Restriciones
def MultiplicarRecursivo(num, factor):
if(isinstance(num,int) and (isinstance(factor,int))):
... |
#!/usr/bin/python
'''
Control USB Missile Launcher using basic GUI. The GUI allows the
elevation and azmith angle of the launcher to be set by clicking the
directional up, down, left and right buttons. The user clicks the
center fire button to launch a missile.
10/29/2020
'''
from tkinter ... |
# Solicite a un usuario que ingrese sus 8 alimentos favoritos y sus precios
# luego realice un gráfico de barras con la información ingresada (recuerde poner título al
# gráfico y a sus ejes también recuerde guardar el resultado en un archivo png)
import matplotlib.pyplot as plt
listaC = []
listaP = []
for i in range ... |
# Pida a un usuario que ingrese sus 5
# snacks favoritos y sus precios luego realice un gráfico de
# barras con la información ingresada, recuerde poner titulo al
# gráfico y a sus ejes también recuerde guardar el resultado en
# un archivo png
import matplotlib.pyplot as plt
lista1 = []
lista2 = []
for i in range (5):... |
#-----primer punto----#
class Torta ():
def __init__ (self, formaentrada, saborentrada, alturaentrada):
self.forma = formaentrada
self.sabor = saborentrada
self.altura = alturaentrada
def mostraratributos (self):
print (f"""hola, estoy vemdiendo una torta muy
linda y deli... |
# Se sabe que un Dólar son 0.82 euros, indique a un usuario que ingrese su
# dinero en dólares y su nombre, luego muestre en pantalla el nombre del usuario y cuanto
# dinero tiene en dólares (recuerde validar que todos los datos ingresados por el usuario sean
# del formato correcto)
def conversionEuros ():
iscorre... |
# Problem 3
def convert_to_mandarin(us_num):
'''
us_num: a string representing a US number 0 to 99
returns the string mandarin representation of us_num
'''
if len(us_num) == 1 or us_num == '10':
return trans[us_num]
teens = ['11', '12', '13', '14', '15', '16', '17', '18', '... |
# secretWord =
global lettersGuessed
def isWordGuess(secretWord, lettersGuessed):
for i in secretWord:
if i in lettersGuessed:
pass
else:
return False
return True
def isLetter(secretWord, lettersGuessed):
if guess in lettersGuessed:
return (... |
from turtle import *
def draw_square(l, c):
pencolor(c)
for i in range(4):
forward(l)
left(90)
draw_square(50, 'red')
mainloop()
|
# ------------------------------------------------------------------
# Lecture Code
# ------------------------------------------------------------------
def merge(A,B):
k = len(A)
m = len(B)
i, j = 0,0
C = []
while i < k and j < m:
if A[i] <= B[j]:
C.append(A[i])
i... |
age = int(input('How old are you?: '))
retirement = abs(age - 65)
if retirement < 10:
print("You get to retire soon.")
else:
print("You have a long time until you can retire!") |
from tkinter import *
ventana = Tk()
# ventana.geometry("500x500")
texto = Label(ventana, text="Bienvenido a mi programa")
texto.config(
fg="white", # color de la letra
bg="black", # color background
padx=120, # padding x
pady=40, # padding Y
font=("Arial", 30)
)
texto.pack(side=TOP)
########... |
import sys
def maxProduct(arr, n):
if n < 3:
return -1
max_product = -(sys.maxsize - 1)
for i in range (0, n - 2):
for j in range (i + 1, n - 1):
for k in range (j + 1, n):
max_product = max (
max_product, arr[i]* arr[j] * arr[k])
return ma... |
def printArr(arr, n):
for i in range (n):
print (arr[i], end=" ")
def sortArr(arr, n):
cnt0 = 0
cnt1 = 0
for i in range (n):
if arr[i] == 0:
cnt0 += 1
elif arr[i] == 1:
cnt1 += 1
i = 0
while (cnt0 > 0):
arr[i] = 0
i += 1
cn... |
def two_way_sort (arr, arr_len):
l, r = 0, arr_len - 1
k = 0
while (l < r):
while (arr[l] % 2 != 0):
l += 1
k += 1
while (arr[r] % 2 == 0 and l < r):
r -= 1
if (l < r):
arr[l], arr[r] = arr[r], arr[l]
odd=arr[:k]
even = ... |
player1=int(input("enter the score of player 1"))
player2=int(input("enter the score of player 2"))
player3=int(input("enter the score of player 3"))
strike_player1=player1*100/60
strike_player2=player2*100/60
strike_player3=player3*100/60
print("the strike rate of player1",strike_player1)
print("the strike rate of pla... |
#while25
N = int(input('Введите число,большее 1:'))
F1 = F2 = 1
while F2 <= N:
F1,F2 = F2, F1+F2
print(F2, end='; ')
print()
print('Первое число Фибоначчи,большее N:', F2)
|
#if4
a = int(input('Введите первое число:'))
b = int(input('Введите второе число:'))
c = int(input('Введите третье число:'))
x = 0
if a > 0:
x+=1
if b > 0:
x+=1
if c > 0:
x+=1
print('Количество положительных чисел:',x)
|
'''
Created on Sep 8, 2015
@author: ggomarr
'''
import nltk
# 1 Read up on one of the language technologies mentioned in this section, such as word sense disambiguation, semantic role labeling, question answering, machine translation, named entity detection. Find out what type and quantity of annotated data is requi... |
#This code shows how if you continue to sum the halves it never hits 1 but rather .99....
n=0
x=.5
n+=.5
print(n)
import time
while n<1:
time.sleep(.5);
n*=0.5
print(n , 'half of previous')
if n<1:
x+=n
print(x , "Is the Total Sum")
continue
if n>=1.0:
... |
you = "today"
if you == "":
robot_brain = "I can't hear you, try again"
elif you == "hello":
robot_brain = "hello ted"
elif you == "today":
robot_brain = "chu nhat"
else:
robot_brain = "I'm fine thank you, and you"
print(robot_brain) |
################
# Sebastian Scheel - @sebastianscheel
# Plantilla de ejercicio
# UNRN Andina - Introducción a la Ingenieria en Computación
################
from soporte import minimo,maximo
lista=[]
cantidad_valores=int(input("cantidad de valores de la lista: "))
for i in range (cantidad_valores):
lista.append(in... |
# The 'continue' keyword, used within a loop, skips the remaining code in the loop block, instead proceeding on to the next iteration. In the following example, 'continue' is leveraged to print only the positive numbers stored in a list.
big_number_list = [1, 2, -1, 4, -5, 5, 2, -9]
for i in big_number_list:
if i < ... |
'''
Review 1:
Create a string object that stores an integer as its value, then convert that string into an actual integer object using int() ; test that your new object is really a number by multiplying it by another number and displaying the result.
'''
number = "12"
real_number = int(number)
print(real_number*3)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.