text stringlengths 37 1.41M |
|---|
def is_number_perfect(num):
sum = 0
for i in range(1, num):
if num % i == 0:
sum += i
return sum == num
number = int(input())
if is_number_perfect(number):
print("We have a perfect number!")
else:
print("It's not so perfect.") |
cards = input().split()
shuffles_count = int(input())
middle_index = len(cards) // 2
first_deck = []
second_deck = []
final_list = []
for card in range(0, middle_index):
first_deck.append(cards[card])
for card in range(middle_index, len(cards)):
second_deck.append(cards[card])
for card in range(len(cards)):
... |
import math
daily_per_worker = int(input())
count_workers = int(input())
others_factory_amound = int(input())
daily_amound = daily_per_worker * count_workers
montly_amound = 0
for i in range(1, 31):
if i % 3 == 0:
new = daily_amound * 0.75
montly_amound += math.floor(new)
else:
montly_am... |
n = int(input())
total_free = 0
has_enough = True
for i in range(1, n + 1):
room_data = input().split()
chars_count = len(room_data[0])
number_ppl = int(room_data[1])
if chars_count >= number_ppl:
total_free += chars_count - number_ppl
else:
has_enough = False
print(f"{number... |
import re
sentence = input().lower()
searched = input().lower()
pattern = searched
matched = re.findall(pattern, sentence)
print(len(matched)) |
"""
#구구단
num = input("몇 단을 출력 하시겠습니까?")
for i in range(9):
result = int(num)*(i+1)
print(str(num) + " * " + str(i+1) + " = " + str(result))
"""
dan = int(input("몇 단을 출력 하시겠습니까?"))
for num in range(1,10):
result = dan * num
print("{} * {} = {}".format(dan, num, result))
|
file_r = "hightemp.txt"
col_list = []
with open(file_r) as f_r:
for line in f_r:
line_split = line.split("\t")
col_list.append(line_split)
col_list_sorted = sorted(col_list, key=lambda x: (x[2]), reverse=True)
for col in col_list_sorted:
print(col)
|
from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(500, 400)
user_bet = screen.textinput("Make your bet", "Which turtle will win the race? red, blue, yellow, green or orange: ")
colors = ["red", "blue", "green", "yellow", "orange"]
y_position = [0, 50, -50, 100, -100]
al... |
"""transposition_cipher_encryption.py - Encrypt text messages via Transposition
Cipher.
Use via ./python transposition_cipher_encryption.py KEY MESSAGE.
KEY = int that gives the key for transposition Cipher encryption or decryption
MESSAGE = str of message to encrypt/decrypt via transposition Cipher, enclosed
with qu... |
"""
EXERCÍCIO 043: Índice de Massa Corporal
Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu IMC
e mostre seu status, de acordo com a tabela abaixo:
- Abaixo de 18.5: Abaixo do Peso
- Entre 18.5 e 25: Peso Ideal
- 25 até 30: Sobrepeso
- 30 até 40: Obesidade
- Acima de 40: Obesidade Mórbida
""... |
"""
EXERCÍCIO 035: Analisando Triângulo v1.0
Desenvolva um programa que leia o comprimento de três retas
e diga ao usuário se elas podem ou não formar um triângulo.
"""
#Cabeçalho
print('-='*20)
print('Analisador de Triângulos')
print('-='*20)
#Coleta de dados
r1 = float(input('Digite o primeiro segmento: '))
r2 = fl... |
"""
EXERCÍCIO 054: Grupo de Maioridade
Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre
quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.
"""
#Importações
from datetime import date
#Variáveis
ano = date.today().year
me = 0
ma = 0
#Resolução
for pess in range( 1... |
"""
EXERCÍCIO 042: Analisando Triângulos v2.0
Refaça o EXERCÍCIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado:
- Equilátero: todos os lados iguais
- Isósceles: dois lados iguais
- Escaleno: todos os lados diferentes
"""
#Cabeçalho
print('\33[1;33m-='*20)
print(' Analisad... |
"""
EXERCÍCIO 041: Classificando Atletas
A Confederação Nacional de Natação precisa de um programa que leia o ano
de nascimento de um atleta e mostre sua categoria, de acordo com a idade:
- Até 9 anos: MIRIM
- Até 14 anos: INFANTIL
- Até 19 anos: JUNIOR
- Até 25 anos: SÊNIOR
- Acima: MASTER
"""
from datetime import da... |
"""
EXERCÍCIO 011: Pintando Parede
Faça um programa que leia a largura e a altura de uma parede em metros,
calcule a sua área e a quantidade de tinta necessária para pintá-la,
sabendo que cada litro de tinta, pinta uma área de 2 m².
"""
a = float(input('Digite a altura da parede: '))
l = float(input('Digite a largura ... |
"""
EXERCÍCIO 005: Antecessor e Sucessor
Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e seu antecessor.
"""
n1=float(input('Digite um valor: '))
#ant=n1-1
#suc=n1+1
print('Seu numero escolhido foi {}, seu antecessor é {} e seu sucessor é {}'.format(n1,(n1-1),(n1+1))) |
"""
EXERCÍCIO 008: Conversor de Medidas
Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros.
"""
m = float(input('Digite um valor em metros: '))
print('O valor de {}M em centímetros é de {}cm \n O valor de {}M em milímetros é de {}mm'.format(m,(m*100),m,(m*1000))) |
# Below code works fine only if list have positive numbers
# No duplicate elements
# And has only one set of numbers which equals to sum
def sumOfTwoNumbers(lst,sumOfTwo):
if len(lst) <= 0:
return 0
else:
for element in lst:
difference = abs(sumOfTwo - element)
if differ... |
# any element of array 1 present in array 2 return true else return false
arr1 = [1,2,45,78,45]
arr2 = [2,4,6,876,345,876]
def check(arr1,arr2):
for i in arr1:
if i in arr2:
return True
return False
print(check(arr1,arr2))
|
def Combsort(arr):
if len(arr) <=1:
return arr
else:
n = len(arr)
gap = n
swapped = True
while gap != 1 or swapped:
gap = int(gap *10 // 13)
if gap < 1:
gap = 1
swapped = False
for i in range(0,n-gap):
... |
def substring(num):
count = 0
n = len(num)
for i in range(n):
for j in range(i,n):
if(num[i] == '1' and num[j]== '1'):
count +=1
print(count)
substring("10001")
|
def arrayRotation(arr):
start = 0
end = len(arr)-1
while(start<end):
arr[start],arr[end] = arr[end],arr[start]
start += start
end -= end
arr = [1, 2, 3, 4, 5, 6, 7]
#arrayRotation(arr)
arrayRotation(arr[:2])
arrayRotation(arr[2:])
arrayRotation(arr)
print(arr)
|
max = 10
def create():
stack = []
return stack
def push(stack,ele):
if len(stack)>=10:
print("Stack is full")
else:
stack.append(ele)
def pop(stack):
if len(stack) == 0:
print("Stack is empty")
else:
stack.pop()
def display(stack):
if len(stack) == 0:
print("No elements in stack")
... |
import random
def gen_rand_question(muscle_dict):
muscles = random.sample(muscle_dict.keys(),3)
options = muscle_dict[muscles[0]], muscle_dict[muscles[1]], muscle_dict[muscles[2]]
question = random.choice(muscles)
while question in already_asked:
muscles = random.sample(muscle_dict.keys(), 3)
... |
# Code by Aron Talai
# Pick random A to test your code
#################
A=1041 #
#################
# Convert to Binary
Binary_num="{0:b}".format(A)
Indexs_of_ones=[]
Dist_between_ones=[]
print(Binary_num)
# Find index for all the 1's in given binary sequence
for i in range(0,len(Binary_num)):
if int(Binary_num... |
import random
def level(numb, guess, random_num):
count = 0
while count < guess:
y = True
while y == True:
try:
guessed_number = int(input('MAKE A GUESS: '))
y = False
except ValueError:
print('Enter an integer or a number... |
"""
def main():
my_name = input("Name:")
print("Az sam", my_name)
def display(x):
print(x)
def test_condition():
var = input("Number:")
if (var == "5"):
int(var)
print("fire")
elif (var == "7"):
print("ne raboti")
else:
p... |
#Interpolation Search function
#Takes two input parameters - a text file and a int value
#Searches for the value within the text file using an interpolation search algorithm
#Returns the numbers of comparisons done and the index position of the value
#(or -1 if not found)
def interSearch(file, value):
nList ... |
#!C:\Users\Mehedi Hasan Akash\Anaconda3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 5 11:08:05 2019
@author: Mehedi Hasan Akash
"""
a, b = 0, 1
if a < b:
print('a ({}) is less than b ({})'.format(a, b))
else:
print('a ({}) is not less than b ({})'.format(a, b))
print("foo" if a < b else "ba... |
#!C:\Users\Mehedi Hasan Akash\Anaconda3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 8 13:17:39 2019
@author: Mehedi Hasan Akash
"""
def main():
choice = dict(
one = "first",
two = "second",
three = "third",
four = "forth",
five = "fifth... |
#!C:\Users\Mehedi Hasan Akash\Anaconda3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 15 12:10:33 2019
@author: Mehedi Hasan Akash
"""
# in the case of multi-level inheritances, a Python super() will always refer the immediate superclass.
class Animal:
def talk(self): print('I have something to say!')
def walk(sel... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 6 15:13:29 2019
@author: Mehedi Hasan Akash
Github: https://github.com/MehediMehi
"""
# sqlite3 comes with python, (can use other databases)
# always commit() after any change in the database
import sqlite3 # python library for sqlite3
def main():... |
#!C:\Users\Mehedi Hasan Akash\Anaconda3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 17:45:40 2019
@author: Mehedi Hasan Akash
"""
class Duck:
def __init__(self, **kwargs): # constructor, keyword arguments to store any number of inputs
self.variables = kwargs # _variableName makes the variable local, using di... |
#!C:\Users\Mehedi Hasan Akash\Anaconda3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 7 11:35:17 2019
@author: Mehedi Hasan Akash
"""
def main():
# conditional executions
a, b = 1, 1
if a < b:
print("a is less than b")
elif a > b:
print("a is grater than b")
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 23 11:17:40 2019
@author: Mehedi Hasan Akash
Github: https://github.com/MehediMehi
"""
'''The unittest package's main() will actually open up this file and parse it and
find the classes that import unittest (here TestSaytime), and it will go ahead... |
# Criando a lista sem nenhum valor
cubos = []
# Criando o laço para inserir os valores na lista
for value in range(1, 11):
# Criando a lógica para calcular o cubo de 1 a 10
cubos.append(value**3)
# Printando o resultado dos cubos
print(cubos) |
# Criando a lógica de cálculo de cubos via list comprehension
cubos = [value**3 for value in range(1, 11)]
# Printando o valor dos cubos
print(cubos) |
'''
MLP network for MNIST digits classification
Test accuracy: 95.2%
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# numpy package
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.datasets im... |
users = []
posts = []
class User():
def __init__(self, name, email, password, friends_list=[]):
self.name = name
self.email = email
self.password = password
self.friends_list=[]
def add_friend(self, email):
self.friends_list.append(email)
print(self.name + " has added " + email + " as a friend")
def rem... |
"""
Author - Torstein Gombos
Created: 06.09.2018
Solving the travelling salesman problem
"""
import time
import csv
import random
from oblig1 import routes as r
from oblig1 import simple_search_algorithms as search
def read_CSV(file) -> list:
"""
Reads the content of a CSV file and store it to a data variable... |
import unittest
from algorithm import reduce_elements, is_prime
class IsPrimeTest(unittest.TestCase):
def test_is_prime_false(self):
test_numbers = [6, 33, 69, 48, 98, 121]
for number in test_numbers:
self.assertFalse(is_prime(number), number)
def test_is_prime_true(self):
... |
from typing import List
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
if not grid:
return 0
path = [grid[0][0]]
rows, columns = len(grid), len(grid[0])
for i in range(1, columns):
path.append(path[i - 1] + grid[0][i])
for i in ra... |
"""
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
"""
class Solution:
def romanToInt(self, s: str) -> int:
conv = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
num, prev = 0, None
for ch in s:
valu... |
"""
You are given K eggs, and you have access to a building with N floors from 1 to N.
Each egg is identical in function, and if an egg breaks, you cannot drop it again.
You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break,
and any egg dropped at or below f... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
dummy = ListNode(0)
dummy.next, node, ... |
import os
import time
class Node(object):
def __init__(self, initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):... |
#!/usr/bin/python3
import random
n = 200
scores = []
# calculate separate means of both items in the score tuple
def mean(scores):
sumReal = 0
sumPercieved = 0
for (real, percieved) in scores:
sumReal += real
sumPercieved += percieved
return (sumReal / len(scores), sumPercieved / len(... |
myStr = input("Enter phrase to check Pangram: ")
if len(myStr) < 26:
print("It is not Pangram.")
else:
for b in range(65,91):
isFound = False
if chr(b) in myStr.upper():
isFound = True
if isFound == False:
print("It is not Pangram.")
break
if isFound ... |
S2 = input("Enter a statement: ")
S2F = S2[:1]
print(S2F, end="")
for COUNT in range(len(S2)-1):
myChar = S2[COUNT+1:COUNT+2]
if myChar == S2F:
myChar = "*"
print(myChar, end="") |
#Initialisation
outString = ""
X = input("Enter String: ")
C = input("Enter character to remove: ")
for Counter in range(len(X)):
myChar = X[Counter:Counter+1]
if myChar != C:
outString = outString + myChar
print("Result:", outString) |
class Book:
def __init__(self, id, name, description, isbn, page_count, issued, author, year):
self.id = id
self.name = name
self.description = description
self.isbn = isbn
self.page_count = page_count
self.issued = issued
self.author = author
self.yea... |
# concept of classes comes from object oritented programming which we will not touch in this course as it is
# an advanced topic
# we saw what functions did...
# they just take some data and return output,
# its a process oriented property
# with classes we can also keep data as well as process
# lets see a class
class... |
"""
创建 Twisted Reactor TCP 客户端 :Twisted Reactor 时间戳 TCP客户端
"""
from twisted.internet import protocol, reactor
HOST = 'localhost'
PORT = 21567
class TSClntProtocol(protocol.Protocol):
def sendData(self):
data = input('>')
if data:
print('...sending %s...' % data)
self.tran... |
def hanoi(n, x, y, z): # n层从x经过y移动到z
if n == 1:
print(x + '——>' + z) # 递归初始条件
else:
hanoi(n-1, x, z, y) # 先将n-1层从x经过z移动到y,这里直接回调就行
print(x + '——>' + z) # 将最底下的最后一个盘子从x移动到z上
hanoi(n-1, y, x, z) # 再将n-1层从现在的y位置经过x移动到z,同理,这里直接回调就行
num = int(input('请输入汉诺塔层数:'))
hanoi... |
#1. We do not want to destroy the world
destroy_world = False
if 'destroy_world':
print("True? Great now destroy the world!")
#2
go_to_store = True
if go_to_stroe:
print('I am ready to go to the store!')
#3
if True:
print('I like this a lot!')
print("It is going to be a good day!")
print("Yup i... |
#1 I need to add something to protect the program
number = input("Give me a number between 1 and 10")
number = int(number)
print("Great Job on giving me the NUMBER %s" % num)
|
"""algorithm to print the names and the count of the same name in the same order which they occur as u ask them"""
def StudentNameCount(Name):
Count={}
for Student in Name: #complexity of for loop is O(n)
if Student not in Count: #Dictionary uses a hash lookup i.e its complexity s... |
# -*- coding: utf-8 -*-
from fractions import Fraction
from decimal import Decimal
from decimal import localcontext
import cmath
import numpy as np
import random
'''
python3内置数值类型(Numeric):
整数(int):python3中的整型只有一种 long 类型
浮点数(float):
定点数(decimal.Decimal):固定的小数点位置,固定位数的整数部分和小数部分,更精确。
复数(complex):用指数达到了... |
# encoding: utf-8
import time
def task_1():
while True:
print("task 1 is runing...")
time.sleep(0.1)
yield
def task_2():
while True:
print("task 2 is runing...")
time.sleep(0.1)
yield
def main():
t1 = task_1() # 生成器(可迭代对象),调用next()时,遇到yeild返回
t2 = ... |
"""We want to replace all instances of:
alpha, beta, gamma, delta, epsilon, kappa, theta
and their capitalized versions with the corresponding unicode
character, and add en entry to the grounding map for each of these
if they aren't already in there"""
import os
import csv
from indra.resources.greek_alphabet import gr... |
class Node:
def __init__(self, value=None, next_node=None):
# the value at this linked list node
self.value = value
# reference to the next node in the list
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.nex... |
"""
FROGGEH
cyoa frogger vs frogtesting, frog testing was used to test making smaller functions and linking them
"""
from random import randint
#
def display_intro():
print """ Welcome to the frog lands, you guessed it, you're a frog! Your name is Froggggeeeh \n and your great great great great greeaaat uncle ... |
'''mood = False
if mood :
print('go left')
print('go back')
account = 'qiyue'
password = '123456'
print('please input account')
user_account = input()
print('please input password')
user_password = input()
if account == user_account and password == user_password:
print('success')
else:
print('fail')
'''... |
import random
class Car:
top_acceleration = 5
top_speed = 10
current_acceleration = 0
current_speed = 0
position = 1
force = 0
def __init__(self):
print("car created")
def sense(self):
sensor_input = self.position + (random.randrange(-20, 20) / 1000)
return ... |
#q1
import csv
def read_data(data):
with open(data, 'r') as f:
data =[row for row in csv.reader(f.read().splitlines())]
return data
data = Desktop/faculty.csv
fac = read_data(data)
degrees = [x[1] for x in fac]
no_periods= [x.replace('.','') for x in degrees]
no_space= [x.replace(' ','') for x in no_period... |
class Employee:
no_of_employee= 0
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
Employee.no_of_employee +=1
@property
def fullname(self):
return '{} {}'.format(self.first,self.last)
@property
... |
import datetime
class Employee:
no_of_employee= 0
raise_amt = 1.04;
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
# self.email = first + '.' + last + '@Company'
Employee.no_of_employee +=1
def araise(self... |
import threading
import Queue
# A simple in memory message bus
class Subscriber(object):
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
def notify(self, message):
print("{} got notified for {}".format(self._name, message))
class Bus... |
class Lunch():
def __init__(self, menu):
self.menu=menu
def menu_price(self):
if self.menu == "menu 1" :
print("Your choice:"+ self.menu +" Price 12.00")
elif self.menu =="menu 2" :
print("Your choice:"+self.menu+"Price 13.40")
else :
... |
import numpy as np
'''
Bounds is the object that handles and contains the upper a lower color bounds to keep in the image
'''
class Bounds:
__pathToFiles = ""
__listOfColors = []
__bounds = [None,None]
__lastBounds = [None, None]
__precision = 10
def __init__(self):
pass
# addCo... |
'''
input: one single object of interest
step1: chose a height (360-1080)
step2: chose an aspect ratio [1.33, 1.66, 1.78, 1.85, 2.39]
step3: finds a background image
step4: fits the background image to the canvas size
step5: define the number of objects to insert
step6: create the objects
step7: add the objects onto t... |
# RyanWaltersDev May 27 2021 -- Messin' with Nestin'!
# Define dictionaries
alien_0 = {'color': 'green', 'points': '5'}
alien_1 = {'color': 'yellow', 'points': '10'}
alien_2 = {'color': 'red', 'points': '15'}
# Define nested list and print
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
# ... |
# RyanWaltersDev May 27 2021 -- TIY 6-4 Glossary Upgrade
# Define Dictionary
programming_words = {
'dictionary': 'a list of key-value pairs',
'variable': 'contains a value',
'print()': 'prints your message to the terminal',
'for loop': 'loops through a list and performs a function for each item',
'... |
# from string import punctuation
# s=input("enter a string:")
# for c in punctuation:
# s=s.replace(c,'')
#
# s=s.lower()
# l=s.split()
#
# word=input("enter a word")
# print(word,'appears',l.count(word),'times.')
#
# from random import shuffle
# word=input('enter a word :')
# letter_list=list(word)
# shuffle(lette... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Carlos Gómez del Fierro
"""
import argparse
from sequences import linear_fib as F
def main():
"""Calculate the n-th value of the Fibonacci sequence"""
parser = argparse.ArgumentParser(
prog='fibo',
description='Calculate the n-th valu... |
# -*- coding: utf-8 -*-
"""
In this example we are going to build an application that reads the most popular names
in the US, taken from the Social Security Administration's site:
https://www.ssa.gov/oact/babynames/
This application will have the following functionalities:
- It will accept a name as an argument
- It... |
import string
def divmod_excel(n):
a, b = divmod(n, 26)
if b == 0:
return a - 1, b + 26
return a, b
def alphabet_decode(value, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
value.isalpha()
value = value.upper()[::-1]
number = 0
for i in range(len(value)):
x = (len(... |
# %%
# -*- encoding:utf-8 -*-
# 习题二
def compare(op1, op2):
return op1 in ["*", "/"] and op2 in ["+", "-"]
def getvalue(num1, num2, operator):
if operator == "+":
return num1 + num2
elif operator == "-":
return num1 - num2
elif operator == "*":
return num1 * num2
else:
... |
import threading
import time
cnt = 0
class Timer(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.index = 0
def run(self):
global cnt
while True:
cnt += 1
time.sleep(1)
def subblock(self):
input("thread is... |
"""
HW14_1. 编写一个按照固定句子结构造句的程序: 输入整数n, 输出n个句子.
固定的句子结构 The adj noun verb .
举例 The crazed elephant danced a jig .
说明 固定部分 形容词(adj) 名词(noun) 动词短语(verb) 固定部分
要求:
1) 用户输入创建的句子数目,如果输入的不是整数,提示用户重新输入. 要求: 使用try…except…结构.
2) 从adj.txt 下载 adj.txt , noun.txt 下载 noun.txt , verb.txt 下载 verb.txt 三个文件读入可供选择的形容词、名词和动词短语, 构成一个spe... |
import string
import time
board = [] # 棋盘
n = 0 # 棋盘的行数/列数,棋盘大小=n*n
# 方向偏移量
direction = ((-1, -1), (-1, 0), (-1, 1), # NW, N, NE
(0, -1), (0, 1), # W, E
(1, -1), (1, 0), (1, 1)) # SW, S, SE
def main():
start = time.time()
global n
compcolor = ''
... |
#задача 5
def permutation(a, value):
max_value = max(a)
if value > max_value:
a.insert(0, value)
elif value in a:
a.insert(a.index(value), value)
else:
a.append(value)
my_list = [7, 5, 3, 3, 2]
print(my_list)
permutation(my_list, 3)
print(my_list)
permutation(my_li... |
import random
# To be honest, I've been trying to move this dictionary to an external file...
# ...but I've been failing to reformat everything to be properly deliminated,
# since the dictionary list is so massive (270,000+ words).
# I've reduced the list to a much more maneagable portion
dictionary_primary = ["a", "... |
import tweepy
import csv
import pandas as pd
#Twitter API credentials
access_token = "3854934923-V2mzUpyTHgpbzEUwaVh2sEIn0QpsLwGIOhUDZBu"
access_token_secret = "qzaGkfmDG2VJweZ1zekdUUhDleIjFdpfY9aF89QNCEzcH"
consumer_key = "YKFwh5ZKl3ZdzLQ26bGJ4yJqi"
consumer_secret = "1I0rigWuuwfdwKL4uVTgC2sAyWa36Fhv0FCeJIIEd5TFd1Uqg... |
#!/usr/bin/python
#/*
#
# Print all permutatiations of a string S.
#
# For example:
#
# S = "a"
#
# a
#
# S = "ab"
#
# ab
# ba
#
# S = "abc"
#
# abc
#
# acb
#
# bac
#
# bca
#
# cab
#
# cba
#
# */
def perm(str):
return perm2(str, 0, [])
def perm2(str, i, l):
if i == len(str):
return l... |
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def palindromic(n):
nstring = str(n)
pstring = ""
for i in range(0, len(nstring)):
... |
"""
return maximum sum that can be obtained by summing up all
the numbers in a non-empty subarray of the input array
sample input: [3,5,-9,1,3,-2,3,4,7,2,-9,6,3,1,-5,4]
output : 19 ([1, 3,-2,3,4,7,2,-9,6,3,1])
"""
# O(n) time | O(1) space - where n is the length of the array
def kadanesAlgo(array):
maxEndingHere... |
"""链表的实现"""
class UnorderHead(): # 链表头
def __init__(self):
self.head = None
class Node(): # 结点
def __init__(self):
self.data = 0
self.next = None
def setData(self, Newnum):
self.data = Newnum
def setNext(self, Newnext):
self.next = Newnext
def getData... |
class BinaryPositiveInteger:
def __init__(self,num):
nbin=[]
nbin2=''
while num>0:
value=int(num%2)
num=int(num/2)
nbin.append(value)
for i in nbin:
nbin2=str(i)+nbin2
self.num=nbin2
def __add__(self, other):
if len... |
def find_mean(lst):
return sum(lst)/len(lst);
def remove_below_avg(lst):
mean=find_mean(lst);
for i in range(len(lst)-1,-1,-1):
if lst[i]<mean:
lst.pop(i);
return lst;
def main():
lst=[2,3,5,1,-4,8,0,-1];
print(remove_below_avg(lst));
main()
|
s=input("Please enter a string s: ")
sub1=""
sub2=""
count=0
sub=s[0]
x=0
if len(s)<4:
print ("There are no repeating substrings in aba")
else:
while x<int(len(s)):
if s[x] != s[0]:
sub += s[x]
else:
print (str(sub))
x += 1
print ("The substring " + sub + " ... |
def internal_str(a, b):
for char in a:
if b.find(char):
return False;
else:
b=b[:i]+b[i+1:];
return True
print(internal_str('abcdefg', "gfedcba")) |
s=input("Enter a character: ");
if s.isdigit():
print(s," is a digit");
elif s.islower():
print(s," is a lowercase letter")
elif s.isupper():
print(s," is an upper case letter")
else:
print(s," is a non-alphanumeric character") |
line= input("Pleases enter a line of text: ")
ch = input("Please enter a character you want to remove: ")
print(line.replace(ch,""))
|
n=int(input("Enter a number: "));
for i in range(1, n+1):
even = 0;
odd = 0;
temp = i;
while(temp>0):
n1=temp%10;
if(n1%2==0):
even+=1;
else:
odd+=1;
temp=temp//10
if (even>odd):
print(i);
|
def add_entry(phonebook, name, phonenum):
if name in phonebook:
print(name, " already exists")
elif not phonenum.isdigit() and len(phonenum) != 10:
print("Not a valid phone number")
else:
phonebook[name]=phonenum
def lookup(phonebook, name):
if name in phonebook:
retur... |
n=int(input("Enter a number: "));
for i in range (1,n+1):
for j in range(1,n+1):
if(j==i):
print("o", end=" ");
else:
print("x", end =" ");
print(); |
import os
class Employee:
def __init__(self,idnum=0,name="",payrate=0):
self.idnum=idnum
self.name=name
self.payrate=payrate
self.hoursworked=0
def addHours(self,hours):
self.hoursworked+=hours
def resetHours(self):
self.hoursworked=0
def getPay(self):
... |
pword=input("Enter a password: ");
up=0;
low=0;
length=0;
special=0;
temp=0;
for i in range(len(pword)):
temp=ord(pword[i])
if (temp>=65 and temp<=90):
up+=1;
elif (temp>=95 and temp<=122):
low+=1;
else:
special+=1;
length=len(pword)
if up>=2 and low>=2 and special>=1 and len... |
import argparse
class Board:
def __init__(self):
self.rows = []
def add_row(self, line):
self.rows.append(list(line.strip()))
def count_seats(self):
count = 0
for row in self.rows:
for space in row:
if space == '#':
count += ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.