text stringlengths 37 1.41M |
|---|
class Arbol:
def __init__(self,arbol,dato):
self.derecha =None
self.izquierda = None
self.info = dato
def agregar (self, arbol,dato):
if arbol.info > dato:
self.agregaIzquierda(arbol,dato)
elif arbol.info < dato:
self.agregaDerecha(arbol,dato)
... |
class Kedi:
tur = "Ev Kedisi" # class attribute # Sınıf özelliği
def __init__(self,adi,yas): #constructor # Yapıcı
self.adi = adi # instance attribute # ornek özellik
self.yas = yas
def miyavla(self): # instance method # ornek metod
print(self.adi,Kedi.tur,"Miyavladı")
... |
"""
lab2.py
Andry Bintoro
1/30/2018
"""
def squared_nums(num_list):
"""
squares numbers in num_list
num_list: list of numbers
Returns: list of these numbers squared
"""
new_list = [ ] #initialize list to hold results
#iterate through num_list and square each element
for num in num_list... |
# # 习题15-1 立方 指定颜色
# import matplotlib.pyplot as plt
#
# x_values = list(range(1, 5001))
# y_values = [x**3 for x in x_values]
# plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Paired, edgecolors='none', s=40)
#
#
# plt.title("Square Numbers", fontsize=24)
# plt.xlabel("Value", fontsize=14)
# plt.ylab... |
# # 15.2 简单的折线图
# import matplotlib.pyplot as plt
# ## 导入pyplot命名为plt
#
# squares = [1, 4, 9, 16, 25]
# ## 建个列表储存平方数,纵坐标值
# plt.plot(squares)
# ## 传递给函数plot,横坐标默认 0,1,2,3,4
# plt.show()
# ## 将图像显示出来,查看器可以缩放,可以保存
# # 15.2.1 题目横纵坐标字体格式
# import matplotlib.pyplot as plt
# ## 导入pyplot命名为plt
#
# squares = [1... |
# Task 7
# Write a program to reverse a linked list.
class Stack:
def __init__(self):
self.stack = []
def push(self,data): # Inserting Elements to stack
self.stack.append(data)
def pop(self): # Delete Element from s... |
# !/usr/bin/evn python3
# -*- config: utf-8 -*-
# Дан список X из n вещественных чисел. Найти минимальный элемент списка,, используя
# вспомогательную рекурсивную функцию, находящую минимум среди последних элементов
# списка , начиная с n-гo.
def min_el_from(i, mini, lis):
if i == len(lis):
return mini
... |
"""
Program: chapter7_lab5.py
Author: Michael Rouse
Date: 11/12/13
Description: Modify chapter 7 lab 4 to be able to enter in multiple customers then save it in a dictionary in a shelf file
"""
import pickle, shelve
def customer_info():
""" Gets information about customer """
# List to hav... |
"""
Program: rectangle_area.py
Author: Michael Rouse
Date: 9/3/13
Description: Calculates area of rectangle
"""
print("Rectangle Area Problem")
rectangleLength = int(input("What is the length of the rectangle? "))
rectangleWidth = int(input("What is the width of the rectangle? "))
# Calculates the ar... |
"""
Program: lab7_4.py
Author: Michael Rouse
Date: 9/27/13
Description: Picks a random car for each staff member and displays that car they drove to work
"""
import random
# Staff directory tuple
STAFF = ('Xavier', 'Matt', 'Joey', 'Jordon', 'Nick', 'Cole', 'Brad')
# Possible cars for each staff membe... |
"""
Program: file_fun.py
Author: Michael Rouse
Date: 10/29/13
Description: Practice with files
"""
print("Practice writing to a file.\n")
# Variable for the file
my_file = open("my_file.txt", "w")
# Write four lines of text
my_file.write("Program by Michael Rouse!\n")
my_file.write("How are you?\n")
... |
"""
Program: Record.py
Author: Michael Rouse
Date: 1/15/14
Description: Create a class called "Record" that will be used to create a simple
database program
"""
class Record(object):
""" Record Class """
def __init__(self):
""" Initialize the class """
# Ask for... |
"""
Program: lab4_08.py
Author: Michael Rouse
Date: 9/12/13
Description: Has the user input three numbers and the program will print which number is the middle number.
"""
print("Tell me three numbers and I can tell you which is the mide number!\n\n")
firstNumber = int(input("First number: "))
secondNu... |
"""
Program: repeat_it_code.py
Author: Michael Rouse
Date: 10/24/13
Description: Daily Design Exercise, create a function called repeat it that repeats a message
multiple times.
"""
def repeat_it(message = "\n", multiplier = 1):
""" Repeats message the amount of times as the multi... |
"""
Program: GEOHELP.py
Author: Michael Rouse
Date: 10/21/13
Description: Assists users with various geometry functions
"""
import my_math
"""
my_math functions:
circleArea(radius)
circleDiameter(radius)
circlePerimeter(radius)
cylinderArea(radius, height)
... |
"""
Program:
Author: Michael Rouse
Date: 10/18/13
Description: Menu for math problems
"""
def menu(id=0):
"""Display a menu. 0=Main, 1=Circle, 2=Cylinder, 3=Prism, 4=Rectangle, 5=Triangle"""
if id == 0:
# Show main menu
print("""
GEOMETRY HELPER
Choos... |
# Name: dd32.py
# Date: 12/13/2013
# Author: Thorin Schmidt
from Rectangle import *
print("Welcome to the Rectangle Module Tester!")
print("First, I'm going to make two rectangles,")
print("one with no parameters, and the second")
print("with values 6 and 9. Let's see what happens!")
input("\nPress a key to see the ... |
"""
Program: cylinder_volume.py
Author: Michael Rouse
Date: 9/3/13
Description: caclulates the volume of a cylinder
"""
print("Cylinder Volume Problem")
radius = int(input("What is the radius? "))
height = int(input("What is the height? "))
# Calculates volume V = Pi * r^2 * h
volume = 3.14 * (radius ... |
"""
Program: chapter7_lab4.py
Author: Michael Rouse
Date: 11/8/13
Description: functions called store_it(list) to save to .dat file and program should get info from .dat file
"""
import pickle
def customer_info():
""" Gets information about customer """
# List of customer information
custo... |
def returnAsTuple (name, age):
# Returns two variables as a tuple
tupleToReturn = (name, age)
return tupleToReturn
def returnAsVars (tupleReceived):
# Returns a tuple as two separate variables
name = tupleReceived[0]
age = tupleReceived[1]
return name, age
tupleReturned = returnAsTupl... |
"""
Program: challenge2_3.py
Author: Michael Rouse
Date: 8/29/13
Description: Program that calulates a 15% and a 20% tip
"""
billTotal = float(input("What is the total bill amount? "))
tip15 = billTotal * .15
tip20 = billTotal * .20
print("\nA 15% tip would be: ", tip15)
print("\nA 20% tip would be:... |
"""
Program: circle_diameter.py
Author: Michael Rouse
Date: 9/3/13
Description: Finds the diameter of a circle
"""
print("Circle Diameter Problem")
circleRadius = int(input("What is the radius? "))
# Calculates the diameter D = r + r
circleDiameter = circleRadius + circleRadius
print("The diameter of... |
"""
Program: challenge6_1.py
Author: Michael Rouse
Date: 10/14/13
Description: Improves the ask_number() function so the function can be called with a step value.
Make default step value equal to 1
"""
def ask_number(question, low, high, step=1):
"""Ask for a number within a range."... |
import math
import copy
import operator
#f = (path length) + (estimated distance)
#计算两点之间的距离(path cost)
def path_length_between_2_points(point1, point2):
return math.sqrt(math.pow(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1], 2))
#所有的点到目标点的预测距离(estimated distance to goal)
def estimated_distances_... |
#(5) キーボードから入力した数に 25000 を足したものが,3500*9 と等しいかどうかを判定するプログラムを作ります.
# 以下の順で命令を実行しなさい.
# 1. 変数 x に数値を入力する
# 2. if で x+25000 と 3500*9 が等しいかどうか判定する.
# 3. 等しいなら OK を,そうでなければ Boo を表示する.
x = int(input())
if x+25000 == 3500*9:
print('OK')
else:
print('Boo') |
#数を 10個入力してその合計を表示するプログラムを作りなさい
#2
print('10個の数値を入力してください')
num = [int(input())for i in range(10)] #list
print('合計値:',end="")
print(sum(num))
|
#5
# 配列の最後に新しい数字(11)を追加する.サンプル配列:[1,3,5,7,9]出力配列:[1,3,5,7,9,11]
list_num = [1,3,5,7,9]
print(list_num)
list_num.append(11)
print(list_num) |
data = [sorted(map(int, x.split("x"))) for x in open("input.txt")]
print(sum(3 * a * b + 2 * b * c + 2 * a * c for a, b, c in data))
print(sum(2 * (a + b) + a * b * c for a, b, c in data))
|
import numpy as np
def count(a):
return np.sum(np.sum(a, axis=1) > 2 * np.max(a, axis=1))
a = np.loadtxt("input.txt")
print(count(a))
print(count(np.vstack([a[i::3].flatten() for i in range(3)]).T))
|
def drawline(l,lab=''):
line='-'*l
if lab:
line+=' '+lab
print(line)
def interval(dist):
if dist>0:
drawline(dist-1)
drawline(dist)
drawline(dist-1)
def ruler(inches,maxtickl):
drawline(maxtickl,'0')
for i in range(1,inches+1):
interval(maxtickl-1)
... |
# coding=utf-8
import asyncio
import ccxt
import time
import _thread
import datetime
#Basic math and String creation
x = sum([1, 0])
if x == 1:
print("0 + 1 = %s" % (x))
y = 2
if sum([x, y]) == 3:
z = sum([x, y])
print("This should count up: %s, %s, %s" % (x, y, z))
#Opens or creates a file named "abc"... |
import random
import locale
def main():
#csv with mortality rates for ages 0-119. No labels.
#format: "Male prob, Female prob \n"
file = "mortalityrates.csv"
prob_file = open(file, "r")
prob = prob_file.readlines()
locale.setlocale(locale.LC_ALL, '')
print("Welcome to the annual p... |
'''
문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/42578
'''
def solution(clothes):
clothes_dict = {}
for clothing, part in clothes:
if part not in clothes_dict:
clothes_dict[part] = [clothing] # key : 옷종류 / value : [옷이름]
else:
clothes_dict[part].append(cloth... |
'''
문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/12925
'''
def solution(s):
answer = int(s)
return answer
print(solution('1234') == 1234)
print(solution('-1234') == -1234) |
'''
문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/12915
'''
def solution(strings, n):
return sorted(sorted(strings), key=lambda x: x[n])
print(solution( ["sun", "bed", "car"], 1) == ["car", "bed", "sun"])
print(solution( ["abce", "abcd", "cdx"], 2) == ["abcd", "abce", "cdx"]) |
import sys, os
from socket import *
# Establece el nombre y el puerto del servidor (serán dos parámetros
# pasados por la línea de comandos).
if(len(sys.argv) > 2):
server_name=sys.argv[1]
server_port = int(sys.argv[2])
else:
print ("Uso: python cliente_interactivo server_name server_port")
sys... |
#!/usr/bin/env python
import sys
# input comes from STDIN (standard input)
for line in sys.stdin:
try:
custID = "-1"
name = "-1"
countrycode = "-1"
transID = "-1"#default sorted as first
# remove leading and trailing whitespace
line = line.strip()
# split... |
import numpy as np
X_array = np.array([0.43, 0.48, 0.55, 0.62, 0.70, 0.65, 0.67, 0.69, 0.71, 0.74], dtype=float)
Y_array = np.array([1.63597, 1.73234, 1.87686, 2.03345, 2.22846, 2.35973, 2.52168, 2.80467, 2.98146, 3.14629],
dtype=float)
def lagrange(x, y, p):
result = 0
for j in range(len(... |
import os
import csv
# define read path (run from Python-Challenge folder)
csvpath = os.path.join("Pypoll", "Resources/election_data.csv")
# define write path for output (run from Python-Challenge folder)
output_path = os.path.join("PyPoll", "Output/PyPoll.txt")
# C:\Users\westl\Desktop\Python-Challenge\Python-Chal... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 16 15:31:07 2020
@author: Manika
"""
import pandas as pd
df1 = pd.read_csv("glassdoor_jobs.csv")
#-----SALARY COLUMN------------------------------------------------------------
#Remove negative salary from the salary Estimate
df1 = df1.loc[df1["Salary Estimate"]!="-1"... |
import tkinter as tk
from tkinter import ttk
def convert_meters_to_feet():
m_str = input_value.get() or '0'
try:
m = float(m_str)
feet = 3.28084 * m
msg = f'{feet:.2f}'
except ValueError:
msg = 'Invalid input'
output_value.set(msg)
root = tk.Tk()
root.title("Unit Conv... |
""""
Calculate the hourglass sum for every hourglass in 2D array, then print the maximum hourglass sum.
"""
import sys
arr = []
for arr_i in xrange(6):
arr_temp = map(int,raw_input().strip().split(' '))
arr.append(arr_temp)
max = -100
for i in range(4):
for j in range(4):
sum = arr[i][j] + arr[i][j... |
#Lathika and Calvin
#Oct.15 2020
#Random Quotes Program
#1 Import tkinter and random (modules)
#2 create a function that runs when the button is pressed
#2.1 Store the quotes with number variables because they are easy to read
#2.2 Get a random number from the random module to get what quote will be printed
# Print the... |
#Escribe un programa que pida por teclado el radio de una circunferencia, y que a
#continuación calcule y escriba en pantalla la longitud de la circunferencia y del área del círculo.
import math
valor = int(input("Introduzca el radio de una circunferencia: "))
def longitud(radio):
longitudCircunferencia = math.pi ... |
# - Trabalho - Estacionamento
# Versão Aula05
# Autor: Ivonei Marques
vagas = [True]*20 # True significa vaga livre
# False significa vaga ocupada
# as listas abaixo estão inicializadas apenas para testes.
l_hEntrada = ["11:11","10:10","13:13"]
l_hSaida = [" :... |
def testargs(*args):
return sum(args)
print(testargs(1,2,1,5,4,56,4,6,4,6,4,5))
def testkwargs(**kwargs): ## Key word arguments
if 'fruit' in kwargs:
print('my fruit of choice is {}'.format(kwargs['fruit']))
else:
print("i did not find any fruites here")
def myfunc(*args,**kwargs):
p... |
"""
一次性读全部
"""
import os
def readfile_original():
try:
f = open('D:\\python_workspace\\test.txt', 'r', encoding='UTF-8')
print(f.read())
except FileNotFoundError:
print("文件不存在")
# finally:
# if f:
# f.close()
def readfile_new():
"""
默认关闭文件流形式
:return:
... |
"""
变量定义学习
"""
def test():
val = 100
for i in range(val):
print(i)
cal(i, 1)
def cal(va11, val2):
print(va11 + val2)
class HelloWorld(object):
def __init__(self):
self.name = "hello,luoyq"
def sayhello(self):
print(self.name)
|
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import random
def fun(x, y):
"""
Computes the function f(x) = x^2 + xy + y^2 at position (x, y)
:param x: The value of x to evaluate f() at
:param y: The value of y to evaluate f() at
:return: the value f(x,... |
import os
txt_file = os.path.join(".", "Homework_Python_Word_Counter.txt")
alpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
... |
class Node:
def __init__(self, value=None, next_node=None):
self.next_node = next_node
self.value = value
def __str__(self):
return str(self.value)
class SortedList:
"""
Сортированный связный список.
Хорошо работает при редких добавлениях новых элементов.
"""
def ... |
def selection_sort(values):
"""
Сортировка выбором.
"""
# Перебираем все элементы.
for i in range(len(values) - 1):
min_idx = i
# Перебираем оставшиеся элементы.
for j in range(i + 1, len(values)):
# Ищем минимальное значение.
if values[min_idx] > valu... |
def binary_search(array, value):
"""
Возвращает индекс искомого элемента (value) в отсортированном массиве.
Если в массиве более одного искомого элемента,
то функция не гарантирует, что найденный будет первым.
Возвращает -1 если элемент не найден.
"""
min_index = 0
max_index = len(array... |
class Cell:
"""
Ячейка для сортированного связного списка.
"""
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def bucketsort(array, num_buckets):
"""
Блочная сортировка массива array.
"""
# Создаем блоки, в которые помещае... |
import pandas as pd
from pathlib import Path
from .Recommender import recommend_movies
from fuzzywuzzy import fuzz, process
base_path = Path('data/')
file_movies = base_path / 'movies.csv'
movies = pd.read_csv(file_movies)
my_movies = []
def list_of_movies():
"""Take an input string from a user and return a list... |
#!/bin/python3
import os
import sys
#
# Complete the gradingStudents function below.
#
def gradingStudents(grades):
return [g+(5-g%5) if g+(5-g%5)-g<3 and g>=38 else g for g in grades]
if __name__ == '__main__':
f = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
grades = []
for _ in rang... |
# Define a sript reads a matrix from a file and solves the linear matrix equation Ax=b
# Where b is the last column of the input-matrix and A is the other columns.
# import the numpy package and solve function
import numpy as np
from numpy.linalg import solve
# Save the file name to a variable
file = "mat.txt"
A = []
b... |
#!/usr/bin/env python3
"""
Purpose:
Generate Tree for testing and traversal
"""
# Python Library Imports
import logging
import random
from anytree import Node, RenderTree
def generate_tree(node_count, max_depth, max_children):
"""
Purpose:
Generate A Random Tree
Args:
node_cou... |
def print_grid(arr):
for i in range(9):
for j in range(9):
print(arr[i][j]),
print('\n')
print('\n')
def check_rule_row(grid,row,col,i):
for j in grid[row]:
if j==i:
return False
return True
def check_rule_col(grid,row,col,i):
for j in range(0,len(grid)):
... |
class PartyAnimal:
x = 0
name = ""
def __init__(self, x):
print("I am constructed with " + str(x))
self.name = x
def party(self):
self.x += 1
print("So far " + str(self.x))
def __del__(self):
print("I am destructed at " + str(self.x))
class FootballFan(P... |
# Write a program that is able to send an email from the terminal to a given email address.
# Solution 1
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg['Subject'] = str(input('Enter subject of the email : '))
msg.set_content(str(input('Enter body of the email : ')))
msg['From'] = "Wri... |
# Ask User to enter a number
number = eval(input("Enter a number: "))
# Display the square of the number that user entered
print("The square of ", number, " is ", number*number, ".", sep='') |
# Display a triangle by astrisks.
# Not use any loops just by print function.
print('*' * 1)
print('*' * 2)
print('*' * 3)
print('*' * 4) |
# Ask the user for his name.
name = input("Enter your name: ")
# Ask the user how many times he want to print his name.
times = eval(input("How many times you want to print your name: "))
# Ask the user if he want to print his name vertical or horizontal
VorH = input("If you want to print it vertical enter v. IF y... |
count = 1
sum = 1
quantity = input('How many triangular numbers do you want? ')
quantity = int(quantity)
while count <= quantity:
print(sum, end=" ")
count += 1
sum = sum + count
|
year=int(input('Enter a year:'))
a = year % 4
b = year % 7
c = year % 19
d = (19 * c + 15) % 30
e = ( 2 * a + 4 * b - d + 34) % 7
month = (((d + e + 114) // 31))
day = ((( d + e + 114) % 31) + 1) + 13
if day >= 31:
day -= 30
month += 1
print("Year:",year)
print("Day:", day,end=" ")
print("Month:", month)
|
#
# starting examples for cs35, week1 "Web as Input"
#
import requests
import string
import json
"""
Examples to run for problem 1:
Web scraping, the basic command (Thanks, Prof. Medero!)
#
# basic use of requests:
#
url = "https://www.cs.hmc.edu/~dodds/demo.html" # try it + source
result = requests.get(url)
tex... |
# IST341, hw3pr2
# Filename: hw3pr2.py
# Name: Will Wagner
# Problem description: Sleepwalking student
import sys
sys.setrecursionlimit(50000) # extra stack room
import time
from random import *
# example "random" code from class
# def guess(hidden):
# """A number-guessing example
# to highlight using t... |
#
# hw6pr1.py ~ recipe analysis
#
# Name(s):
#
import os
import os.path
import shutil
top_dir_sub_count = 0
top_dir_file_count = 0
top_dir_files_of_type = 0
# Filetype Search
def count_any_files( L , file_type, print_subdir_info):
""" count_txt_files takes in a list, L, and file type
and 0,1,2 for level... |
string = ''
final = ''
ascii = input('Enter sentence: ')
for x in ascii:
string += oct(ord(x))
instring = string
string = list(string.split("0o"))
for x in range(0, len(string)):
string[x] = "0o" + string [x]
string.pop(0)
cipher = "áéíóúüñ¿¡"
digits = "12345670o"
word = ""
Final_code = ""
answer = instring
lengt... |
#encoding: UTF-8
#Autor: Diego Perez aka DiegoCodes
#MEZCLADOR_DE_COLORES
def mezclador(c1,c2): # COMBINA LOS COLORES PREVIAMENTE EVALUADOS COMO VALIDOS
if (c1.lower() == "rojo"):
if (c2.lower() == "azul"):
col = "morado"
if (c2.lower() == "amarillo"):
col = "naranj... |
CURRENT_YEAR = 2021
print("Ten cua ban: ")
ten = input()
print("Ho cua ban: ")
ho = input()
print("ban sinh nam : ")
namsinh = int(input())
tuoi = CURRENT_YEAR - namsinh
#print("tuoi cua ban la {0} nam {1}".format(tuoi,CURRENT_YEAR)
print("chieu cao (meter) : ")
chieu_cao = float(input())
pri... |
m = int(input("Nhap m = "))
n = int(input("Nhap n = "))
print("Nhap ma tran A ",m," dong ",n," cot")
A = [[int(input()) for i in range(n)] for j in range(m)]
AT=[]
for i in range(n):
row=[]
for j in range(m):
row.append(0)
AT.append(row)
for i in range(n):
for j in range(m):
AT[i][j] = A[j][i... |
number=int(input())
sum_num=0
for i in range(number):
i+=1
sum_num+=i
print (sum_num)
|
number=input()
if any(a.isalpha() for a in number):
print("No")
elif any(a.isdigit() for a in number):
print("yes")
|
number1=int(input())
if number1>0:
if(number1%2==0):
print("yes")
else:
print("no")
|
str1,num=input().split()
num1=int(num)
if num1>0:
for i in range(num1):
print (str1)
|
numb,numb1=map(int,input().split())
fact=1
fac=1
if numb==0 or numb==1 or numb1==0 or numb1==1:
print(1)
else:
for i in range(1,numb+1):
fact=fact*i
for j in range(1,numb1+1):
fac=fac*j
ans=int(fact/fac)
print(ans)
|
def gcd(no1,no2):
if no1==0:
return no2
if no2==0:
return no1
else:
return gcd(no2,no1%no2)
no1,no2=map(int,input().split())
ans=gcd(no1,no2)
print(ans)
|
number=list(input())
lis=[]
for i in number:
if int(i)%2!=0:
lis.append(i)
for i in lis:
print(i,end=" ")
|
import math
epsilon = float(input("Введіть з якою точністю: "))
while epsilon >= 1:
print("Введіть правильну точність <1")
epsilon = float(input("Введіть з якою точністю: "))
x = float(input("Введіть чисельник: "))
s = 1
b = 1
c = 1
a = 1
while math.fabs(a/(b*c)) > epsilon:
s += (a/(b*c))
a = a*(-x**2)
... |
arr = [float(x) for x in input("Введіть список: ").split()]
min_arr = arr[0]
for i in arr:
if i > 0 and i < min_arr:
min_arr = i
print(min_arr) |
n = int(input("Введіть число: "))
x0 = 0
x1 = x2 = 9
if n == 0:
print("x= 0")
elif n == 1 or n == 2:
print("x= 9")
else:
for i in range(n-2):
xn = x2+4*x0
x0 = x1
x1 = x2
x2 = xn
print("x(n)= {0}".format(xn)) |
# CIS 240 Introduction to Programming
# Assignment 6.1
# Write a program that uses a function to convert miles to kilometers.
# Your program should prompt the user for the number of miles driven then call a function which converts miles to kilometers.
# Check and validate all user input and incorporate Try/Except block... |
import csv
with open('height-weight.csv',newline='')as f:
reader=csv.reader(f)
file_data=list(reader)
file_data.pop(0)
#sorting data to get the height of people
new_data=[]
for i in range(len(file_data)):
n_num=file_data[i][1]
new_data.append(float(n_num))
#getting the mean
n= len(new_data)
... |
# learnBoosting.py - Functional Gradient Boosting
# AIFCA Python3 code Version 0.8.6 Documentation at http://aipython.org
# Artificial Intelligence: Foundations of Computational Agents
# http://artint.info
# Copyright David L Poole and Alan K Mackworth 2017-2020.
# This work is licensed under a Creative Commons
# Attr... |
# rlFeatures.py - Feature-based Reinforcement Learner
# AIFCA Python3 code Version 0.8.6 Documentation at http://aipython.org
# Artificial Intelligence: Foundations of Computational Agents
# http://artint.info
# Copyright David L Poole and Alan K Mackworth 2017-2020.
# This work is licensed under a Creative Commons
# ... |
# Display unique words
st = input("Enter string :")
for w in set(st.split(" ")):
print(w)
|
class SavingsAccount:
# class attributes
minbal = 5000
def __init__(self,acno,ahname, balance = 0):
# object attribute
self.acno = acno
self.ahname = ahname
self.balance = balance
def deposit(self,amount):
self.balance += amount
def withdraw(self,amount):
... |
# request document from word pil is to import picture.
import requests,docx,PIL
# web site for the taco recipe.
taco_url = 'https://taco-1150.herokuapp.com/random/?full_taco=true'
# json file request for web site.
response = requests.get(taco_url).json()
# document for word to enter data.
document = docx.Document()
... |
def prime_number():
a = 2
pn = []
while True:
yield a
pn.append(a)
while True:
prime = 1
a += 1
for i in pn:
if a % i == 0:
prime = 0
break
if prime:
break
p = pr... |
#!/usr/bin/python
"""Sorting n students into m classes with x slots per class and 3 ordered selections per students"""
import argparse
import copy
import csv
import os.path
import pprint
import random
import sys
from session import Session
from student import Student
def define_sessions(filename):
"""
Returns ses... |
# Создание файла типа tuple. Он похож на лист, за исключением пары моментов.
# Первое: он записывается в круглых скобках.
# Второе: элементы в нём нельзя изменить, удалить, добавить.
a = (1, 2, 1, 100, 'hi', {'example': 'hello'})
# Выводим на экран кол-во элементов эквивалентных 1.
print(a.count(1)) |
# scoresGrades.py
'''
Assignment: Scores and Grades
05 July 2017
Vinney
Write a function that generates ten scores between 60 and 100. Each time a
score is generated, your function should display what the grade is for a
particular score. Here is the grade table:
Score: 60 - 69; Grade -... |
""" Assignment: OOP | Math Dojo
06 July 2017
Vinney
You're creating a program for a call center. Every time a call comes in
you need a way to track that call. One of your program's requirements is
to store calls in a queue while callers wait to speak with a call center
employee.
You will c... |
""" Assignment: OOP | Hospital
07 July 2017
Vinney
You're going to build a hospital with patients in it! Create a hospital
class.
Before looking at the requirements below, think about the potential
characteristics of each patient and hospital. How would you design each?
Patient:
A... |
all_colors = [
{"label": 'Red', "sexy": True},
{"label": 'Pink', "sexy": False},
{"label": 'Orange', "sexy": True},
{"label": 'Brown', "sexy": False},
{"label": 'Pink', "sexy": True},
{"label": 'Violet', "sexy": True},
{"label": 'Purple', "sexy": False},
]
#Your code go here:
color = []
for x in all_colors:
... |
n = int(input("Enter a binary number: "))
sum = 0
i = 0
while n != 0:
rem = n % 10
sum = sum + rem * pow(2,i)
n = int(n/10)
i = i + 1
print("Decimal number %.2f" % sum) |
#!/usr/bin/python3
def main():
choices = dict(
one = '1',
two = '2',
three = '3',
four = '4',
five = '5',
)
v = 'three'
print( choices.get(v, 'other'))
if __name__ == "__main__": main()
|
#!/usr/bin/python3
def main():
a, b = 1, 0
v = 'This is true ' if a > b else 'This is not true'
print(v)
if __name__ == "__main__": main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.