text stringlengths 37 1.41M |
|---|
from tkinter import *
import csv
weight = []
numquestions = 0
num = 0
y = 0
question = 0
choise = 0
numchoice = 0
arr = []
responses = []
trash = []
n = 0
j = 0
root = Tk()
root.withdraw()
# Responses: These are the responses to the question. Stored as a location in memory
v = IntVar()
curre... |
__author__ = 'brianlawney'
class Reaction(object):
"""
This class holds all the components of a reaction- the constitutive species, rate constants, the direction
of reaction
"""
def __init__(self,
reactants,
products,
fwd_k,
rev_k... |
from sys import argv, exit
import csv
if len(argv) != 3:
print("missing command-line argument")
exit(1)
#open file
datafile = open(argv[1], "r")
checkfile = open(argv[2], "r")
#read database into dict
database = csv.DictReader(datafile)
dna_sequence = checkfile.readline()
#store keys
keys = database.fieldna... |
#!/usr/bin/env python
def parseSize(text):
prefixes = {
'b': 1,
'k': 1024, 'ki': 1024, 'kb': 1024,
'm': 1024 * 1024, 'mb': 1024 * 1024,
'g': 1024 * 1024 * 1024, 'gb': 1024 * 1024 * 1024
}
num = ""
text = str(text).strip()
while text and text[0:1].isdigit() or tex... |
from math import sqrt
suma = 0
def fibonacci(a):
ans = int(1/sqrt(5)*((1+sqrt(5))/2)**a-1/sqrt(5)*((1-sqrt(5))/2)**a)
return ans
i=0
while fibonacci(i)<4000000:
if fibonacci(i)%2==0:
suma = suma + fibonacci(i)
i += 1
print(suma)
|
# Write a function that asks the user for a string containing multiple words. Print back
# to the user the same string, except with the words in backwards order.
def reverseV1(w):
return ' '.join(w.split()[::-1])
def reverseV2(x):
y = x.split()
result = []
for word in y:
result.insert(0,word)
... |
# Find an element in a list using binary search.
def find(orderedList, elementToFind):
startIndex = 0
endIndex = len(orderedList) - 1
found = False
while startIndex <= endIndex and not found:
middleIndex = (startIndex + endIndex) // 2
if orderedList[middleIndex] == elementToFind:
... |
import plotly.express as px
import pandas as pd
class Plot():
def __init__(self, dfResult, a, b, gridInfo):
self.modelDf = dfResult
self.a = a
self.b = b
self.gridInfo = gridInfo
def print_title(self):
start = str(self.gridInfo[0])
end = str(self.gridInfo[1])
... |
# 11.6 Write a test program that prompts the user to enter two 3 by 3 matrices and displays their product
# Sample Input [1 2 3 4 5 6 7 8 9] [0 2 4 1 4.5 2.2 1.1 4.3 5.2]
# Multiply two matrices
def multiplyMatrix(a, b):
n = len(a)
c = [[0] * n for i in range(n)]
for row in range(n):
for column in ... |
# 10.2 Write a program that reads a list of integers and displays them in the reverse order
# in which they were read.
# Sample Input [2 5 6 4 3 23 43]
# Create a list of integers
def createList():
# Read numbers as a string from the console
s = input("Enter integers: ")
items = s.split() # Extract items... |
# 2.22 Write a program to prompt the user to enter the number of years and
# displays the population after that many years
# Prompt the user to enter the number of years
numberOfYears = eval(input("Enter the number of years: "))
# Constants
CURRENT_POPULATION = 312032486
BIRTH_RATE = 7
DEATH_RATE = 13
NEW_IMMIGRANT... |
# 2.7 Write a program that prompts the user to enter the minutes (e.g., 1 billion),
# and displays the number of years and days for the minutes
# Sample Input[1000000000]
# Prompt the user to enter minutes
totalMinutes = eval(input("Enter the number of minutes: "))
# Compute minutes per day
minutesPerDay = 24 * 60
... |
# 3.6 Write a program that draws a triangle, square, pentagon, hexagon, and octagon
import turtle # Import turtle module
# Draw a triangle with bottom side parallel to x-axis
turtle.setheading(60) # Set the turtle’s heading to 60 degrees
turtle.pensize(3) # Set pen thickness to 3 pixels
turtle.penup()
turtle.goto(-2... |
# 5.36 Revise the Rock Scissor Paper program to let the user play continuously until either the user
# or the computer wins more than two times.
import random # Import random module
# Initialize the number of user and computer wins
userWins = 0
computerWins = 0
# Check condition and proceed
while userWins <= 2 and ... |
# 10.26 Write a test program that prompts the user to enter two sorted lists and
# displays the merged list
# Sample Inputs [1 5 16 61 111], [2 4 5 6]
def merge(list1, list2):
list3 = []
while len(list1) and len(list2):
if list1[0] > list2[0]:
list3.append(list2.pop(0))
else:
... |
# 5.30 Write a program that prompts the user to enter the year and first day of the year,
# and displays the first day of each month in the year on the console
# Prompt the user for inputs
year, firstDayOfYear = eval(input("Enter the year and first day of the year(e.g 2016, 3): "))
# Check if the given year is a leap... |
# 5.35 Write a program to find four perfect numbers less than 10,000.
# Compute the perfect numbers less than 10000 and display result
print("The four perfect integers less than 10000 are: ", end = "")
for i in range(1, 10000):
sumOfDivisors = 0
n = i // 2
for j in range(1, n + 1):
if i % j == 0:
... |
# 8.3 Write a program that prompts the user to enter a password and displays valid password
# if the rules are followed or invalid password otherwise.
# Sample Inputs [43GRfdf], [dR#t3dT#], [dRt3dT210], [dkTw3dsP]
# Check if password is valid
def checkPassword(p):
if isLengthValid(p) and isCharValid(p) and isNumb... |
# 6.5 Write a test program that prompts the user to enter three numbers
# and invokes the function to display them in increasing order
# Sorts the numbers in increasing order and displays result
def displaySortedNumbers(num1, num2, num3):
for i in range(1, 3):
if num1 > num2:
num1, num2 =... |
class Vertex:
def __init__(self, vNum):
self.mVertices = {}
for i in range(vNum):
self.mVertices[i+1] = list()
def AddEdge(self, u, v):
self.mVertices[u].append(v)
self.mVertices[v].append(u)
def neighbors(self, u):
return [neighbour for neighbour in sel... |
class Queue:
def __init__(self):
self.mItems = []
def empty(self):
return len(self.mItems) == 0
def push(self, item):
self.mItems.append(item)
print('ok')
def pop(self):
return self.mItems.pop(0)
def front(self):
return self.mItems[0]
def __le... |
"""
Реалізуйте підпрограми сортування масиву.
"""
N = 10000 # Кількість елементів масиву.
# Використовується у головній програмі для генерування
# масиву з випадкових чисел
def bubble_sort(array):
""" Сортування "Бульбашкою"
:param array: Масив (список однотипових елементів)... |
#-------------------------------------------------------------------------------
# Name: Exercise 7
# Purpose: Convert degrees minutes to decimal degrees
# Decimal Degrees = degrees + (minutes/60) + (seconds/3600)
# add 0 after number
# Author: chengjiaqi sun
#
# Created: 10... |
import csv
def writeCSV(FN):
with open(FN,mode='a',encoding='utf-8',newline="") as fn:
fw=csv.writer(fn,delimiter=',',quoting=csv.QUOTE_NONNUMERIC)
data=['aaa',40,60]
fw.writerow(data)
data1=[['bbb',3,5],['ccc',55,333]]
fw.writerows(data1)
def readCSV(FN):
with o... |
#The Fibonacci sequence is defined by the recurrence relation:
#Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
#The 12th term, F12, is the first term to contain three digits.
#What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
def FibonacciNumber(n):
#n number of digits
a = 1
... |
#Nombre: Iago Brian Lorenzana Reyes
#Carrera: Informática
#Materia: Desarrollo de Aplicaciones Web
#Ejercicio o práctica: 2.2 - practicando condicionales complejas python
fecha=input("Fecha (formato'dia, DD/MM') :") #Declaramos variables con sus diferentes propiedades y formatos como en el caso de diasemana, dianro... |
def invest(amount, rate, time):
print("principle amount: ${}".format(amount))
print("annual rate of return: {}".format(rate))
for n in range(1,time+1):
amount= amount*(1+rate)
print("year {}: ${}".format(n,amount))
print("")
invest(100,.05, 8)
invest(2000, .025, 5)
|
"""
picture.py
Author: John Warhold
Credit: dan
Assignment:
Use the ggame library to "paint" a graphical picture of something (e.g. a house, a face or landscape).
Use at least:
1. Three different Color objects.
2. Ten different Sprite objects.
3. One (or more) RectangleAsset objects.
4. One (or more) CircleAsset obj... |
# -*- coding: utf-8 -*-
import math
def cifrar():
mensajeACifrar = input('Ingresa tu mensaje a cifrar')
llave = input('Ingresa un numero entero para la llave')
lallave = int(llave)
if len(mensajeACifrar)>lallave:
mensajeCifrado = encriptando(lallave, mensajeACifrar... |
'''
Rusty DeGarmo
Professor Payne
Intro to Programming with Python
7 May 2021
'''
#The purpose of this program is to utilize file management techniques
#import the OS library
import os
#Ask the user for their desired directory with a prompt variable
promptDir = "\nWhat is the path of the directory that you want to go... |
import numpy, matplotlib.pyplot as plt
from neuralNetwork import neuralNetwork
# nodes and learning rate
input_layer = 784
hidden_layer = 100 # Optimal is 200, but it takes considerably longer to train and the % difference is about 1%
output_layer = 10
learning_rate = 0.1
# Instance of neural network
nn = neuralNetwo... |
"""
一般进行接口测试时,每个接口的传参都不止一种情况,一般会考虑正向、逆向等多种组合。所以在测试一个接口时通常会编写多条case,而这些case除了传参不同外,其实并没什么区别。
这个时候就可以利用ddt来管理测试数据,提高代码复用率。
※但要注意:正向和逆向的要分开写※
安装:pip install ddt
四种模式:第一步引入的装饰器 @ ddt;导入数据的 @ data;拆分数据的 @ unpack;导入外部数据的 @ file_data
"""
# 一、读取元组数据
# 一定要和单元测试框架一起用
import unittest, os
from ddt import ddt, data, unpack, file_d... |
# Debug all errrors found in this program so that the output result is displayed correctly to the user
import random
user = input("choose your weapon!")
comp = random.choice(['rock','paper','scissors'])
print('user (you) chose:', user)
print('comp (me) chose:', comp)
if (user == 'rock' and comp == 'pape... |
# -*-coding:utf-8-*-
# created by HolyKwok 201610414206
# practice1-4
# rooster -> 5, hen -> 3, 3chicks -> 1
# ¥100 -> 100
sum_ = 100 # the sum of hens, roosters and chicks
cost = 100
price_rooster = 5 # each rooster costs 5
price_hen = 3 # eaach hen costs 3
one4chick = 3 # 3 chicks costs 1
for rooster in range(sum... |
def Sorte(T):
return T[0]
def Mini(A,p):
R=[]
for i in range(len(A)):
a=abs(p-A[i])
t=[a,A[i]]
R.append(t)
R.sort(key=Sorte)
return R[0][1]
Request=[98, 67, 78, 30, 10, 45, 180, 20, 150, 35]
position=60
movef=0
c=position
l=len(Request)
for i in range(l):
movef=movef+abs(c-Request[i])
c=Request[i]
print("... |
#esse ("inf")O primeiro cria um número infinito, o segundo cria um número que não é um número "Not a Number"
#aqui declaramos variaveis para o funcionamento como continuar, maior, menor, a quantidade de numeros que digitei.
maior = -float("inf")
menor = float("inf")
continuar ="sim"
quantos_numeros = 0
#esse while... |
# This python script reads a 28x22 PNG image representing a game level
# and outputs a sequence of data that represents the game map
# NOTE: white = background, black = wall
# other colors are ignored (might be used to mark objects)
from PIL import Image
img = Image.open("map.png")
level_map = [[0x80 for i in range(... |
#The main goal of the program is to convert NPR to AUD or AUD TO NPR.
Aud = 12345678
ConvertedAud= Aud*80.61
Npr= 12345678
ConvertedNpr = Npr/80.61
print "The AUD converted is : %f" %ConvertedAud # %f is a formatter for FLOAT hence the ConvertedToNpr will not show
print "The NPR converted is :%d " %ConvertedNpr |
for a in range(1, 400):
for b in range(1, 400):
c = (1000 - a - b) #condition (iii)
if a < b < c:
if a * a + b * b == c * c:
product_abc = a * b * c
print("the product abc is,",product_abc)
|
# https://docs.python.org/3/howto/sockets.html
# https://stackoverflow.com/questions/8627986/how-to-keep-a-socket-open-until-client-closes-it
# https://stackoverflow.com/questions/10091271/how-can-i-implement-a-simple-web-server-using-python-without-using-any-libraries
import socket
def create_server():
server_so... |
import time
import random
def print_pause(message_to_print, pause=2):
print(message_to_print)
time.sleep(2)
def valid_input(prompt, options):
while True:
response = input(prompt).lower()
for option in options:
if option == response:
return respon... |
# Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.
# The binary number returned should be a string.
def add_binary(a,b):
#your code here
binarySum = a + b
binaryResult = bin(binarySum)
binaryLast1 = binaryRes... |
def factorial(n):
if n==1:
return n
else:
return n*factorial(n-1)
f=factorial(5)
print(f)
|
# program to calculate area of basic geometrical shapes
print("Launching Area Calculator")
shape = raw_input("Enter one of the options listed: \n 1.S for square \n 2.R for Rectangle \n 3.C for circle \n 4.T for triangle \n")
if shape.upper() == "S":
sideSquare = float(raw_input("Enter the value of side of the square:"... |
import collections
def reverse_json(obj=None):
"""
Given a dict, reverse the order of the elements inside the dict
:param obj: a dict, e.g. “{A:1, B:1, C:1, D:1, E:1}”
:return: the dict with the elements reversed
"""
if obj is None:
return {}
# extract the keys from the dict
r... |
import smtplib
host="smtp.gmail.com"
port=587
username="username@gmail.com"
password="password"
from_email = username
to_list=[ "zhongturtle@gmail.com"]
email_conn=smtplib.SMTP(host,port) #make connect
email_conn.ehlo() #test whether the connect is ready
email_conn.starttls() #enables upgrading otherwise plaintext ... |
# Python code to demonstrate working of iskeyword()
# In programming, a keyword is a "reserved word" by the language which convey a special meaning to the interpreter.
# It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet.
# Keywords in Python: Python language also ... |
from sklearn.datasets import load_iris
from sklearn import tree
from sklearn.naive_bayes import GaussianNB
irisData = load_iris()
print("==IRIS DATASET==")
print(irisData)
print("Type of irisData is:", type(irisData))
print()
# Explore Features in DataSet
print("===IRIS DATA FEATURES===")
print(irisData.data)
print... |
l = int(input("enter of low:"))
u = int(input('enter of high:'))
for num in range(l,u+1):
if num>1:
for i in range(2,num):
if(num%i)==0:
break
else:
print(num)
|
sum = -1
for x in range(0, 9**5*6):
x_str = str(x)
temp_sum = 0
for i in x_str:
temp_sum += int(i)**5
if temp_sum == x:
sum += x
print(sum)
|
from tkinter import *
class Gui(Tk):
def __init__(self):
super().__init__()
# set window attributes
self.title("Tickets")
# add components
self.__add_heading_label()
self.__add_instruction_label()
self.__add_tickets_entry()
self... |
def under(msg):
"""
This function creates a message and underneath converts it to *
input: msg-string
output: metin-string
"""
metin = ""
metin = metin + msg
metin = metin + "\n"
metin = metin + len(msg)*"*"
return metin
def over(msg):
metin2 = ""
metin2 = metin2 + len(m... |
print("What type of adventure you like")
user_answer = input()
if ((user_answer == "scary") or (user_answer == "short")):
print("Entering the dark forest")
elif ((user_answer == "safe") or (user_answer == "long")):
print("Taking the safe route!")
else:
print("Not sure which route to take.")
|
def abc(x):
if x==0:
return 0
return x+abc(x-1)
while True:
n=int(input("n: "))
print("suma primelor n cifre este : ",abc(n)) |
import sys, re
import csv, json
def main():
if len(sys.argv) != 3:
print 'python course_csv_to_json.py <csv_file> <out_json_file>'
return 0
fname = sys.argv[1]
f = open(fname)
data_arr = []
courseReader = csv.reader(f, delimiter=',', quotechar='"')
for split_line in courseR... |
a=[float(i) for i in input().split()]
area_tri=0.5*a[0]*a[2]
area_circle=(3.14159*a[2]*a[2])
area_trip=0.5*a[2]*(abs(a[1]+a[0]))
area_sq=a[1]*a[1]
area_rec=a[0]*a[1]
print("TRIANGULO:",format(area_tri,'0.3f'))
print("CIRCULO:",format(area_circle,'0.3f'))
print("TRAPEZIO:",format(area_trip,'0.3f'))
print("QUADRADO:",for... |
# -*- coding: utf-8 -*-
import math
import os
## Question1 : aire d'un rectangle (longueur x largeur)
def rectangle(longueur,largeur):
return (longueur*largeur)
print("Aire du rectangle : " + str(rectangle(25,5)))
## Question 2 : aire d'un cylindre (2 x π x rayon x hauteur)
def cylindre(rayon, hauteur... |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
bilateral = pd.read_csv('data/bilateralmigrationmatrix20130.csv', index_col='From country', thousands=',')
# histogram of migrants
nonzero_values = bilateral.values.flatten()
nonzero_values = nonzero_values[nonzero_values !=... |
#! /usr/bin/python3.7
# Map It
# this program searches for the address given as a bash argument.
# if no arguments given, it will copy from the clipboard.
# this is an example for the "webbrowser" module.
import webbrowser
import pyperclip
import sys
address = 'https://www.google.com/maps/place/'
if len(sys.argv) ==... |
import collections
# Named Tuples
color = collections.namedtuple('Color', ['hue', 'saturation', 'luminosity'])
p = color(170, 0.1, 0.6)
if p.saturation >= 0.5:
print('Whew, that is bright!')
if p.luminosity >= 0.5:
print('Wow, that is light!')
|
#! /usr/bin/python3.7
import logging
'''
instead of using print() for logging, we can use this module.
when deleting logging print() calls we can accidentally remove a valid print() call.
instead, we use logging and we can disable all logs with this function:
'''
# logging.disable(level=logging.DEBUG)
logging.basi... |
import logging
from abc import abstractmethod
from . import Input
class DelayedSwitch(Input):
"""A class for using a switch with a delay
"""
async def _on_input(self, command, seat):
"""DelayedSwitch input functionality
:param command: Command from game engine
:type command: dict... |
"""
kruskal_mst.py
Compute a minimum spanning forest using Kruskal's algorithm.
The KruskalMST class represents a data type for computing a
* minimum spanning tree in an edge-weighted graph.
* The edge weights can be positive, zero, or negative and need not
* be distinct. If the graph is not connected, it compute... |
# Bubble sort
# O(n**2)
def bubble_sort(array):
is_sorted = False
n = len(array) - 1
while not is_sorted:
is_sorted = True
for i in range(n):
j = i + 1
if array[i] > array[j]:
swap(array, i, j)
is_sorted = False
n -= 1
... |
"""
allow_filter.py
The AllowFilter class provides a client for reading in an allow_list
* of words from a file; then, reading in a sequence of words from standard input,
* printing out each word that appears in the file
"""
from search.p_set import SET
class AllowFilter:
@staticmethod
def run(*args):
... |
"""
suffix_array.py
A data type that computes the suffix array of a string.
The SuffixArray class represents a suffix array of a string of
* length n.
* It supports the selecting the ith smallest suffix,
* getting the index of the ith smallest suffix,
* computing the length of the longest common prefix between ... |
"""
/******************************************************************************
* Performs a series of computational experiments.
* Execution: -
* Dependencies: -
******************************************************************************/
"""
from Percolation import Percolation
import random
impor... |
"""
flow_edge.py
Capacitated edge with a flow in a flow network.
The FlowEdge class represents a capacitated edge with a
* flow in a FlowNetwork. Each edge consists of two integers
* (naming the two vertices), a real-valued capacity, and a real-valued
* flow. The data type provides methods for accessing the two e... |
# Bruteforce substring search
# Time complexity
# Worst case Theta(N * M)
def str_search(pattern, text):
"""
if pattern exists in text, return index where pattern starts.
:param pattern: string pattern
:param text: string text
:returns: index of where pattern starts
"""
N, M = len(text)... |
"""
digraph.py
The Digraph class represents a directed graph of vertices
* named 0 through V - 1.
* It supports the following two primary operations: add an edge to the digraph,
* iterate over all of the vertices adjacent from a given vertex.
* It also provides
* methods for returning the indegree or outdegre... |
"""
doubling_ratio.py
* The DoublingRatio class provides a client for measuring
* the running time of a method using a doubling ratio test.
"""
import random as r
from fundamentals.stopwatch import StopWatch
from fundamentals.three_sum import ThreeSum
class DoublingRatio:
MAXIMUM_INTEGER = 1000000
@stati... |
"""
hash_table.py.
@description The hash_table.py module defines a class, HashTable.
@author Vincent Porta.
#-------------------------------------------------
Time complexity in big O notation.
# Algorithm Average Worst case
# Space O(n) O(n)
# Search O(1) O(n)... |
"""
pqueues.py
A generic queue.
* The pqueues class represents a first-in-first-out (FIFO)
* queue of generic items.
* It supports the usual enqueue and dequeue
* operations, along with methods for peeking at the first item,
* testing if the queue is empty, and iterating through the items in FIFO order.
* ... |
"""
doubling_test.py
* The DoublingTest class provides a client for measuring
* the running time of a method using a doubling test.
"""
import random as r
from fundamentals.stopwatch import StopWatch
from fundamentals.three_sum import ThreeSum
class DoublingTest:
MAXIMUM_INTEGER = 1000000
@staticmethod
... |
"""
directed_cycle_x.py
Find a directed cycle in a digraph, using a nonrecursive, queue-based
* algorithm. Runs in O(E + V) time.
"""
from collections import deque
from graphs.digraph import Digraph
class DirectedCycleX:
_cycle = None
def __init__(self, g):
self._g = g
self._marked = [Fals... |
# Binary Search Trees
# Height: the height of a BST - avg: O(log n) - worst: O(n)
# Operation on BST
# S. No. Operation Average Case Worst Case
# 1 Contains/Search O(log n) O(n)
# 2 Minimum O(log n) O(n)
# 3 Maximum O(log n) O(n)
# 4 Predecessor O(log n) O(... |
"""
red_black_bst.py
A symbol table implemented using a left-leaning red-black BST.
Invariants:
1. No node has two red links connected to it.
2. Every path from root to null/None link has the same number of BLACK links
3. RED links lean left.
The put, get, contains, remove, minimum, maximum operations each ... |
"""
dijkstra_all_pairs_sp.py
Dijkstra's algorithm run from each vertex.
* Takes time proportional to E V log V and space proportional to EV.
The DijkstraAllPairsSP class represents a data type for solving the
* all-pairs shortest paths problem in edge-weighted digraphs
* where the edge weights are non-negative.
... |
"""
three_sum.py
* A program with cubic running time. Reads n integers
* and counts the number of triples that sum to exactly 0
* (ignoring integer overflow).
* The ThreeSum class provides static methods for counting
* and printing the number of triples in an array of integers that sum to 0
* (ignoring inte... |
"""
average.py
$ python fundamentals/average.py 10.0 5.0 6.0
"""
import sys
class Average:
@staticmethod
def main(*args):
count, _sum = 0, 0.0
a = list(*args)
while count < len(a):
value = float(a[count])
_sum += value
count += 1
average = _... |
def solution(heights):
answer = []
stack = []
for idx, val in enumerate(heights):
if idx == 0:
#print(0,end=' ')
answer.append(0)
stack.append((idx+1,val))
else:
while 1:
try:
if stack[-1][1] > val:
... |
def check(x) :
if x in ['*', '/']:
return 3
elif x in ['+', '-']:
return 2
elif x in ["(", ")"]:
return 1
return 0
s = input()
answer = ''
stack = []
for cha in s:
pri = check(cha)
if cha in ['+', '-', '*', '/']:
#스택의 top보다 비교 대상 연산자의 연산자가 낮거나 같을 경우 = pop
... |
import random
def create(matrix):
i = 0
while i < 3 :
print(3*(" ---"))
print("|",end = '')
if matrix[i][0] == 1 :
print(" X ",end = '')
elif matrix[i][0] == 2 :
print(" O ",end = '')
else :
print(" ",end = '')
print("|"... |
import re
def ignore_articles(string):
""" Takes a string and returns it with initial articles excluded.
Useful for alphabetical sorting. """
str_low = string.lower()
if str_low.startswith("the "):
return string[4:]
elif str_low.startswith("an "):
return string[3:]
elif str_lo... |
import time
start_time = time.time()
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
duplicates = []
# for name_1 in names_1:
# for name_2 in names_2:
# ... |
"""
This codes purpose is to give me the latest story
listing from a specific website. Website not mentioned for reasons.
"""
import requests
from bs4 import BeautifulSoup
# get input from user
url = input("Enter the URL: ")
finalUrl = ""
# check if user input www
if "www." in url:
# replace www with h... |
def transHeight(x):
if x == '5 feet 10 inch' or x == '5′ 10″' or x == "5'10''" or x == '5\'10"':
return 1.778
elif x == '5\'3"' or x == "5'3''" or x == '5.3':
return 1.6002
elif x == "5'8''" or x == "5'8" or x == '5.8' or x == '5\'8"' or x == '5 feet 8 inch' or x == '172.72 cm':
... |
toplam=0
for i in range(3,1000):
if(i%3==0):
toplam=toplam+i
elif(i%5==0):
toplam=toplam+i
else:
continue
print(toplam)
|
import turtle
t=turtle.Turtle()
for i in range(0,12):
t.left(5)
t.forward(10)
t.left(50)
for i in range(0,12):
t.left(5)
t.forward(10)
t.left(135)
for i in range(0,14):
t.right(5)
t.forward(10)
t.penup()
for i in range(0,5):
t.left(3.3)
t.backward(10)
t.pendown()
t.... |
class Pelicula:
def __init__(self,nombre,actor):
self.nombre= nombre
self.actor=actor
class Pila:
def __init__(self):
self.items=[]
def apilar(self,dato):
self.items.append(dato)
def desapilar(self):
return self.items.pop()
def pil... |
import random
def shuffle(string):
temp_list = list(string)
random.shuffle(temp_list)
return ''.join(temp_list)
uppercaseLetter1=chr(random.randint(65,90))
uppercaseLetter2=chr(random.randint(65,90))
lowercaseLetter1=chr(random.randint(65,90))
lowercaseLetter2=chr(random.randint(65,90))
random_di... |
# вводятся какое определенное колво чисел n, и среди них необходимо найти
# среднее ариф число
# 3
# 4
# 5
# 6
#
# 5
n = int(input())
i = 0
arr = []
while i < n:
num = int(input())
arr.append(num)
i += 1
i = 0
sumi = 0
while i < n:
sumi = sumi + arr[i]
i += 1
print(sumi/n)
|
# вам необходимо создать переменную a = 100, присвоить
# второй переменной
# значение первой, а третьей переменной значение первой
# но увеличнной на 90
# и четвертая это сумма второй и третьей переменной
a = 100
b = a
c = a+90
d = a + a + 90
print(a, b, c, d) |
numbers = [
["футболка", 2],
["шорты", 4],
["кофта", 6],
]
i = 0
n = len(numbers)
while i < n:
arr = numbers[i]
j = 0
k = len(arr)
print(arr)
while j < k:
print(arr[j])
j += 1
i += 1
# i j 0 1
# 0 ["футболка", 2],
# 1 ["шорты", 4],
# 2 ["кофта"... |
def printData(arr123213):
for i in arr123213:
marks = i["marks"]
avg = 0
for j in marks:
avg = avg + j
print(i["name"], avg / len(marks))
user1 = {
"name": "user1",
"marks": [1, 2, 3, 4, 5]
}
user2 = {
"name": "user2",
"marks": [4, 2, 3, 3, 5]
}
user3 = ... |
i = 0
n = 5
while i < n:
print("External loop")
j = 0
k = 9
while j < k:
print("Inner loop")
j += 1
i += 1
|
# 10 30
# 10 + 13 + 16 + 19 + 21 + 24....
# 10 11 12 13
a = int(input())
b = int(input())
sumi = 0
while a <= b:
sumi = sumi + a
a += 3
# sumi=10+3
# sumo=13+11+3
print(sumi)
|
# !=,==,>,<,<=,>=
# c = 10 % 3
# # 13 % 3 = 1
# # 13 - 12 = 1
a = int(input("введите первое число"))
b = int(input("введите второе число"))
#a/b без остатка
if a%b == 0:
print("YES")
else:
print("NO") |
# 1)
# ВВОД:
#
# первое число:3
# второе число:4
# третье число:5
#
# ВЫВОД:
# Максимальное число:5
# Минимальное число:3
a = int(input())
b = int(input())
c = int(input())
maxi = 0
mini = 0
#find maximum
if a > b and a > c:
maxi = a
if b > a and b > c:
maxi = b
if c > a and c > b:
maxi = c
#find minimum
... |
n = int(input())
arr = []
# range(n)->[0..n]
# range(1,n) -> [1
# ..n]
for i in range(n):
num = int(input())
arr.append(num)
print(arr)
# 5
# 123
# 123
# 12
# 23
# 23
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.