text stringlengths 37 1.41M |
|---|
import matplotlib.pyplot as plt
Year=[2010,2011,2012,2013,2014,2015]
rice=[10,20,40,60,70,40]
plt.xlabel("Years")
plt.ylabel("Rice Production")
plt.title("Rice Production over time")
plt.plot(Year,rice)
plt.show() |
file_read=open("data.txt","r")
file_write=open("data21.txt","w")
for line in file_read:
for ch in line:
if ch=="a":
print ("**",end="")
if ch=="m":
print ("*",end="")
else:
print (ch,end="")
|
# 다형성
# Developer 부모 클래스 선언
class Developer:
def __init__(self, name):
self.name = name
def coding(self):
print(self.name, 'is developer!!')
# Python Developer 자식 클래스 선언
class PythonDev(Developer):
def coding(self):
print(self.name, 'is Python Dev!!')
# JAVA Dev 자식 클래스 선언
class Ja... |
# break문 예시
signals='blue','yellow','red'
# for x in range(len(signals)):
# print(x, signals[x],'루프시작!!')
# if signals[x] == 'yellow':
# break
# print(x, signals[x],'루프종료!')
#
# print('프로그램 종료')
for x in range(len(signals)):
print(x, signals[x], '루프시작!!')
if signals[x] == 'yellow':
... |
#print("오늘의 온도를 입력하세요.")
temp = 10
if temp > 20 :
print("얇은 옷을 입으세염!")
else :
print("두꺼운 옷을 입으세염!")
sign = "stop"
while sign == "stop" :
sign = input("현재 신호를 입력하시오: ")
print("OK! 진행합니다.") |
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("Hello World!")
root.geometry("400x400")
root.iconbitmap('c:/guis/codemy.ico')
# Create Popup function
def popup():
response = messagebox.showinfo("Popup Title", "Look at my popup message!!")
my_label = Label(root, text=response).pack(pady=... |
def get_user_int_input(question):
# Get input from user called int_input as int based on str question. If input is not int reppet until it is an int.
while True:
try:
int_input = int(input(question))
break
except ValueError:
print('You have to chose a integer'... |
# author: KaiZhang
# date: 2021/8/8 14:44
"""
List Comprehensions :列表生成式
"""
range_ = [x * x for x in range(1, 11)]
print(range_)
x_ = [x for x in range(1, 11) if x % 2 == 0] # 不能在最后的if加上else,因为跟在for后面的if是一个筛选条件,不能带else,否则无法筛选
x_ = [x if x % 2 == 0 else -x for x in range(1, 11)] # if写在for前面必须加else,因为for前面的部分是一个表达式,... |
# author: KaiZhang
# date: 2021/8/7 17:01
"""
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
要创建一个set,需要提供一个list作为输入集合
"""
s = set([1, 2, 3])
print(s)
# 重复元素在set中自动被过滤
s = set([1, 1, 2, 2, 3, 3])
print(s)
# 通过add(key)方法可以添加元素到set中,可以重复添加,但不会有效果
s.add(5)
print(s)
# 通过remove(key)方法可以删除元素
s.remove(5)
print... |
def linearsearch (arr, x):
for i in range(len(arr)):
if arr[i] == x:
print ("Index is ",i)
break
else:
print("Not present")
print("welcome to my linear search program.")
arr = [45, 78, 66, 52, 28, 36]
print("This is my array. Enter any number to search its index.... |
a = int(input("Enter the starting number : "))
b = int(input("Enter the Ending number : " ))
print ("Prime number in between the given range are")
for i in range (a, b+1):
if i>1:
for j in range (2,i):
if (i%j == 0):
break
else:
print (i, end=" ")
|
pes=12
jardas=3*pes
milhas=1760*jardas
conv=float(input("Digite o valor em pes"))
print("O valor em jardas e:"+str())
print("O valor em milhas e:"+str()) |
class FeeType(object):
FLOAT = 0
FIXED = 1
class Fee(object):
def __init__(self, fee_dict):
# type: (int, float, float, float) -> None
self.__fee_type = fee_dict['fee_type']
self.__amount = fee_dict['amount']
self.__min_fee = fee_dict['min_fee']
self.__ma... |
# A Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
# Create tuple
fruits=('Apples','Oranges','Grapes')
#fruits2=tuple(('Apples','Oranges','Grapes'))
# Single value needs trailing comma
fruits2=('Apples',)
# Get value
print(fruits[2])
# Can't change alue
# fruits[0]=... |
import math
def rotate(xy, radians):
x, y = xy
xx = round(x * math.cos(radians) + y * math.sin(radians))
yy = round(-x * math.sin(radians) + y * math.cos(radians))
return xx, yy
def move_direction_part1(coordinates, action, direction):
movement = int(action[1:])
if action[0] == "N":
... |
# python3
import sys
NODES = {} # Dict of graph nodes.
class GraphNodeUndirected(object):
"""A basic representation of an undirected graph node.
"""
def __init__(self):
self.visited = False
self.pre_visit = None
self.post_visit = None
self.edges = []
def __repr__(s... |
# Uses python3
import sys
"""
The algorithm begins by splitting the array in half repeatedly and calling itself
on each half.
When we get down to single elements, that single element is returned as the majority of
its (1-element) array. At every other level, it will get return values from its two
recursive calls.
The k... |
# python3
import sys
def lcm_naive(a, b):
'''Dumb (slow) example solution.
'''
for l in range(1, a*b + 1):
if l % a == 0 and l % b == 0:
return l
return a*b
def gcd(x, y):
'''Recycled GCD solution.
'''
return gcd(y, x % y) if y else abs(x)
def lcm(a, b):
'''Retu... |
import math
def f1(x):
return math.cos(x)/(1+math.cos(x)*math.cos(x))
def f2(x):
return 1/(5+4*math.cos(x))
def f3(x):
return math.exp(-x*x)
def midpoint(f,a,b):
return (b-a)*f((a+b)/2)
def trapezoidal(f,a,b):
return ((b-a)/2)*(f(a)+f(b))
def simpsons(f,a,b):
return (1/3)... |
n = input("Enter your desired Fibonacci sequence length: ")
n = int(n)
print(n)
|
while True:
def triples():
a = input("Enter first side: ")
b = input("Enter second side: ")
c = input("Enter third side: ")
if (int(a)**2 + int(b)**2 = int(c)**2) or (int(a)**2 + int(c)**2 = int(b)**2) or (int(b)**2 + int(c)**2 = int(a)**2):
print("It is a Pythagorean Triples!")
else:
print("It is NO... |
# Lieu de travail de Samir Abou Serhal pour le travail de liste
# La date est le 17 décembre 2020
# Pour me contacter, envoyer moi un couriel à abosam30@ecolecatholique.ca
""""
print("")
print("Bonjour, je suis un menu interactif.")
print("Voici les options que je vous présente:")
print("")
print("Pèse 0 pour dire bo... |
from itertools import cycle
from collections import deque
class Marbles(deque):
def moveclock(self, n=1):
self.rotate(-n)
def movecounter(self, n=1):
self.rotate(n)
def insertright(self, val):
self.moveclock()
self.appendleft(val)
def remove(self):
sel... |
'''
Created on 2018. 3. 11.
@author: kfx20
'''
# 이분 탐색과 재귀 호출
# 리스트 a, 찾는 값 x
# 특정 숫자를 찾으면 그 값의 위치, 찾지 못하면 -1
# 리스트 범위를 정하여 찾은 후
# 그 범위 안에서 x를 찾는 재귀 함수
def binary_search_sub(a, x, start, end):
# 종료 조건 : 남은 탐색 범위가 비었으면 종료
if start > end :
return -1
mid = (start + end) // 2 # 탐색 범위의 중간 위치
... |
'''
Created on 2018. 3. 6.
@author: kfx20
'''
# 쉬운 퀵 정렬
def quick_sort(a):
n = len(a)
if n <= 1:
return a
pivot = a[-1]
g1 = []
g2 = []
for i in range(0, n - 1):
if a[i] < pivot:
g1.append(a[i])
else:
g2.append(a[i])
print("pivo... |
'''
Created on 2018. 3. 3.
@author: kfx20
'''
# 연속한 숫자의 곱을 구하는 알고리즘
def fact(n):
print("n : ", n)
if n <= 1:
return 1
return n * fact(n - 1)
print(fact(1))
print(fact(5))
print(fact(10)) |
'''
Created on 2018. 3. 3.
@author: kfx20
'''
# 최대공약수 구하기
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
print(gcd(1, 5))
print(gcd(3, 6))
print(gcd(60, 24))
print(gcd(81, 27)) |
class Aluno:
def __init__(self, nome: str, nota: float):
self.__nome = nome
self.__nota = nota
self.__prox = None
def __repr__(self):
return f'{self.__nome}:{self.__nota}'
@property
def prox(self):
return self.__prox
@prox.setter
def prox(self, prox... |
# Load LinearSVC class from Scikit Learn library
# LinearSVC is similar to SVC with parameter kernel='linear'
# LinearSVC performs classification
# LinearSVC finds the linear separator that maximizes the distance between itself and the closest/nearest data point point
from sklearn.svm import LinearSVC
# load RFE (Rec... |
def findThreeLargestNumbers(array):
new_arr = [None] * 3
for n in array:
if new_arr[-1] == None or n > new_arr[-1]:
new_arr[-3] = new_arr[-2]
new_arr[-2] = new_arr[-1]
new_arr[-1] = n
elif new_arr[-2] == None or n > new_arr[-2]:
new_arr[-3] = new_arr[-2]
new_arr[-2] = n
el... |
def shortestDistance(words, word1, word2):
i = None
j = None
res = len(words)
for n in range(len(words)):
word = words[n]
if word == word1:
i = n
if word == word2:
j = n
if i != None and j!= None:
res = min(abs(i-j),res)
return res if i != None and j != None else 0
asser... |
def numIslands(grid):
def dfs(i, j):
if not (0 <= i < len(grid)) or not (0 <= j < len(grid[0])) or grid[i][j] == "0":
return
grid[i][j] = "0"
dfs(i, j+1)
dfs(i, j-1)
dfs(i+1,j)
dfs(i-1, j)
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] ==... |
# the first thing is the root node of 10
# I want to build a binary search tree on another computer
# I will traverse through DFS and this will first lead to the path that has the lowest number
# How do i form the string as I traverse through the tree on my computer
'''
10
/ \
8 12
/ \ / \
... |
import math
def findMin(nums):
if len(nums) == 1 or nums[0] < nums[-1]:
return nums[0]
# left = 0
# right = len(nums) - 1
# while left < right:
# mid = int(math.floor((left / 2) + (right / 2)))
# prev = mid - 1
# nextt = mid + 1
# if prev >= 0:
# if nums[prev] > nums[mid]:
# ... |
# Write a method, reverse_string(str), that takes in a string.
# The method should return the string with it's characters in reverse order.
#
# Solve this recursively!
#
# Examples:
#
# reverse_string("") # => ""
# reverse_string("c") # => "c"
# reverse_string("internet") # => "tenretni"
# rever... |
def shuffle(nums, n):
ans = []
for i in range(0, n):
ans.append(nums[i])
ans.append(nums[n+i])
return ans
print(shuffle([2, 5, 1, 3, 4, 7], 3))
# [2,3,5,4,1,7]
print(shuffle([1, 2, 3, 4, 4, 3, 2, 1], 4))
# [1,4,2,3,3,2,4,1]
print(shuffle([1, 1, 2, 2], 2))
# [1,2,1,2]
|
from collections import Counter
def minSetSize(arr):
count = Counter(arr)
items = list(count.items())
items.sort(reverse=True,key = lambda x: x[1])
n = len(arr)
num_count = 0
count = 0
print(items)
for item in items:
if num_count < (n/2):
num_count += item[1]
count += 1
print(nu... |
'''
binary search
KNOW my exit condition
How do you know you have found the pivot???
if the number after is smaller
no dups
arr is sorted
arr is sorted, but pivots at a certain point
given arr, target
time complexity to target is still log n
return index of the target
Not in there, return -1
[5,6,0,1,2,3,4], 2
[6... |
from collections import Counter, deque
def number_of_nodes(graph, level):
"""
Calculates the number of nodes at given level
:param graph: The graph
:return: Total number of nodes at given level
"""
# Write your code here!
visited = Counter()
root = 0
visited[root] = 1
q = dequ... |
# // returns the first index where any permutation of needle begins as an exact substring of haystack, -1 if it can't find it
# // permutation("abc") = > "abc", "acb", "bac", "bca", "cab", "cba"
# // strstrp("hello there", "hello") returns 0
# // strstrp("hello there", "elloh") returns 0
# // strstrp("hello there", "o ... |
'''
Some digits are formed with closed paths. The digits 0,4,6 and 9 each have 1 closed path, and 8 has 2.
None of the other numbers is formed with a closed path.
Given a number, determine the total number of closed paths in all of its digits combined.
number = 649578
The digits with closed paths are 6,4,9 and 8. Th... |
import GRT
import sys
import numpy as np
import math
def main():
"""GRT DoubleMovingAverageFilter Example
This example demonstrates how to create and use the GRT DoubleMovingAverageFilter PreProcessing Module.
The DoubleMovingAverageFilter implements a low pass double moving average filter.
... |
import GRT
import sys
import argparse
def main():
'''GRT Class Label Filter Example
This examples demonstrates how to use the Class Label Filter to filter the predicted class label of any classification module
using the gesture recognition pipeline.
The Class Label Filter is a useful post-processin... |
import GRT
import sys
import argparse
def main():
'''
GRT HMM Continuous Example
This examples demonstrates how to initialize, train, and use the Continuous HMM algorithm for classification.
Hidden Markov Models (HMM) are powerful classifiers that work well on temporal classification problems ... |
from random import randint
resultados = {
"1": "Você não chegou na sala 9\nGAME OVER!!",
"2": "Você não chegou na sala 9\nGAME OVER!!",
"3": "Você não chegou na sala 9\nGAME OVER!!",
"4": "Você não chegou na sala 9\nGAME OVER!!",
"5": "Você não chegou na sala 9\nGAME OVER!!",
"6": "Você não che... |
"""Module providing the Lemma class."""
from typing import Dict
from typing import Optional
from typing import Tuple
from banone.sound import SoundSequence
def remove_last_syllable(phon: str) -> str:
"""Remove the last syllable boundary in a phonetic string.
Example: Turn `fa:-n` (stem of `fa:-n@`) into `fa... |
from sys import exit
def combination(n,r): #combination calculate
try:
if r == 0:
return 1
elif r == n:
return 1
else:
return combination(n-1,r-1) + combination(n-1,r)
except RecursionError as e: #재귀 한계 초과 에러 처리
print(e, "so kill ... |
# Author: Cameron Jones
# Description:
import urllib2
from pprint import pprint
from json import loads
import Tkinter as tk
from PIL import Image, ImageTk
class Weather:
temp_cur = 0
temp_max = 0
temp_min = 0
weather = ""
API_URL = "http://api.openweathermap.org/data/2.1/find/name?q="
# initi... |
#whatever monster kills you takes your gear and exp just like a player would xp gain for kills is a % of opponents xp not 100% if you return and kill them you will get everything back but xp will be lost in transfer
#Nothing will ever despawn if you die you respawn with nothing lvl 1 so do the mobs when they die they... |
single_string = input().split(", ")
new_string = []
for el in single_string:
if int(el) != 0:
new_string.append(int(el))
number_of_zero = len(single_string) - len(new_string)
for _ in range(number_of_zero):
new_string.append(0)
print(new_string) |
numbers = [int(num) for num in input().split()]
command_data = input()
multiply_element = 0
while not command_data == "end":
command_data = command_data.split()
if len(command_data) > 1:
command = command_data[0]
num1 = int(command_data[1])
num2 = int(command_data[2])
... |
def add_and_subtract():
all_numbers = []
for number in range(3):
single_number = input()
all_numbers.append(single_number)
first_number = int(all_numbers[0])
second_number = int(all_numbers[1])
third_number = int(all_numbers[2])
def sum_numbers():
return first_... |
text = input()
for index in range(len(text)):
if text[index] == ":":
print(f"{text[index]}{text[index + 1]}") |
n = int(input())
for letter_1 in range(97, 97 + n):
for letter_2 in range(97, 97 + n):
for letter_3 in range(97, 97 + n):
print(f"{chr(letter_1)}{chr(letter_2)}{chr(letter_3)}") |
n = int(input())
positives_numbers = []
negatives_numbers = []
for i in range(n):
number = int(input())
if number >= 0:
positives_numbers.append(number)
else:
negatives_numbers.append(number)
print(positives_numbers)
print(negatives_numbers)
print(f"Count of positives: {len(posi... |
trip_days = int(input())
budget = float(input())
number_of_people = int(input())
fuel_price_per_km = float(input())
food_expenses = float(input())
night_pppn = float(input())
total_food_expenses = trip_days * number_of_people * food_expenses
total_cost_hotel = number_of_people * night_pppn * trip_days
if numb... |
def chek_if_palindrome(el):
if el == el[::-1]:
return True
return False
nums_as_string = input().split(", ")
for num_as_str in nums_as_string:
print(chek_if_palindrome(num_as_str)) |
def chek_password_valid(pword):
is_valid = True
consist_only_of_letters_and_digits = True
count_digits = 0
if len(pword) < 6 or len(pword) > 10:
print("Password must be between 6 and 10 characters")
is_valid = False
for el in pword:
if el.isdigit():
c... |
text = input()
data = input()
while not data == "End":
data = data.split()
command = data[0]
if command == "Translate":
replace = data[1]
replace_with = data[2]
text = text.replace(replace, replace_with)
print(text)
elif command == "Includes":
text_... |
key = int(input())
n = int(input())
word = ""
for letter in range(1, n + 1):
symbol = input()
word += chr(ord(symbol) + key)
print(word) |
import pygame
import GraphicsLib as GLib
from Util import *
# a great example of an object that can move on the screen
class Hero:
def __init__(self):
# ------------------------
# [REQUIRED PART] for any class that will be drawn on the screen
# Grab the surface that Graphics people worked v... |
#encoding: UTF-8
#Autor: Neftalí Rodríguez Martínez.
#Se incluye una función para contador de insectos y otra función que encuentra el mayor de un grupo de números.
def contarInsectos(): #cuenta el total de insectos atrapados.
print("Bienvenido al programa que registra los insectos que recolectas")
pri... |
import random
from SearchNode import SearchNode
from game import get_possible_moves
from game import do_move
#==============================================================================
# GRAPH_SEARCH
#
# The fringe and closed list must be drawn while the thinking takes place.
# - Draw the closed list blue (255, 0, ... |
def fast_power(x,n):
if(n==0):
return 1
if(n==1):
return x
flag = 0
if(n%2==1):
flag=1
ans=x
while(n>1):
ans*=ans
n//=2
if(flag==1):
ans*=x
return ans
x, n = list(map(int, input("Enter base and power: ").split(' ')))
print("Answer:",fast_power(x,n))
'''OUTPUT:
Enter base and power: 3 0
Answer: 1
... |
def partition(arr, low, high):
#sort bolts using nuts
i = low
j = low
pivot = arr[high]
while(j < high):
if arr[j] < pivot:
arr[i], arr[j] = arr[j], arr[i]
i+=1
j+=1
arr[i], arr[high] = arr[high], arr[i]
return i
def quicksort(a, low, high):
if low>=high:
return
pivot = partition(a, low, high)
qu... |
def prefixSum(arr):
psum = [0 for i in range(0,len(arr))]
psum[0] = arr[0]
for i in range(1, len(arr)):
psum[i] = psum[i-1]+arr[i]
return psum
def max_subarray_sum_quadratic(arr):
n = len(arr)
max_l = 0
max_r = 0
maxSum = -10000
subSum = 0
psum = prefixSum(arr)
for i in range(0,n):
for j in range(i,n):... |
def match(nuts, bolts):
for nut in nuts:
for bolt in bolts:
if nut == bolt:
print(nut, "matched with", bolt)
nuts = list(map(int, input("Enter nuts: ").split(' ')))
bolts = list(map(int, input("Enter bolts: ").split(' ')))
match(nuts, bolts)
'''OUTPUT:
Enter nuts: 2 1 7 4 5 6
Enter bolts: 6 5 1 4 7 2
2 matc... |
# -*- coding: utf-8 -*-
"""
Generates a random number between 1 and 9 (including 1 and 9).
Asks the user to guess the number,
then tells them whether they guessed too low, too high, or exactly right.
Keeps the game going until the user types “exit”.
Keeps track of how many guesses the user has taken, and when the game... |
first_text = input('Enter first string: ')
second_text = input('Enter second string: ')
find_text = first_text.find(second_text)
if find_text == -1:
print(first_text)
else:
print(first_text[find_text + len(second_text):])
|
start = 1
end = 10
print('Counting from 1 to 10')
while start <= 10:
print(start)
start += 1
print('Counting from 10 to 1')
start = 10
end = 1
while start >= end:
print(start)
start -= 1
|
all_prices =[]
while True:
price = input("Please enter a price: ")
if price == 'stop':
break
all_prices.append(float(price))
print('All prices: ')
print(all_prices)
sum_prices = sum(all_prices)
min_price = min(all_prices)
max_price = max(all_prices)
all_prices.sort()
lower_price = all_prices[0]
... |
n = input('Enter number: ')
n = int(n)
c = n % 10
n = n // 10
b = n % 10
n = n // 10
a = n % 10
n = n // 10
print('reverced number is: ' + str(c) + str(b) + str(a)) |
"""
1.计算求2+4+6+8+...+100的和
2.统计不同英雄的成绩
3.车型抱怨的数据统计
"""
print('homework 1:')
ret = 0
for i in range(2, 102, 2):
ret += i
print('2+4+6+8+...+100的和是:{0}'.format(ret))
# 作业2
print('\nhomework 2:')
import pandas as pd
data = {
'语文': [68, 95, 98, 90, 80],
'数学': [65, 76, 86, 88, 90],
'英语': [30, 98, 88, 77, ... |
def modus(angka):
nol=0
terbesar=angka[0]
for a in angka:
jumlah=angka.count(a)
if jumlah>=nol:
nol=jumlah
terbesar=a
return(terbesar)
while True:
a=input("masukkan list angka: ")
angka=a.split()
print(modus(angka))
print("")
#F... |
n=int(input('masukkan bilangan bulat'))
bilangan= n/2
if bilangan%2==0:
print("Ya")
else:
print("Bukan")
|
name = raw_input("What is your name? ")
for x in range(1,201):
y = raw_input('Enter somethin')
if y == 'hi':
print 'bye'
elif y== 'Charlie' or y == 'charlie':
print 'is ded meme'
elif y == 'Brad' or y == 'brad':
print 'is better than charlie'
elif y== 'why':
print ... |
"""
change-making problem
"""
#Using the greedy approach
#time complexity is O(n)
#Dont always give the optimal solution
def greedy(coins, value):
sol = []
for i in range(len(coins)-1, -1, -1):
while value >= coins[i]:
#Take the most from the current biggest coin
#or you can just substract
temp =... |
import random
print 'Welcome to the rock,paper,scissors game '
print 'press 1 for single player and press 2 for double player'
a = input('give the input: ')
if a==1:
print "Welcome I am the computer player."
input1=input("Enter your choise as 1, 2 or 3 . 1.rock 2.paper 3.scissors ")
comp = random.choice([1, 2, 3... |
class Node(object):
def __init__(self,val):
self.val = val
def __eq__(self,other):
return self.val == other.val
def __hash__(self):
return hash(self.val)
s = set()
n1 = Node(val = 1)
n2 = Node(val = 2)
n3 = Node(val = 1)
n4 = Node(val = 2)
s.add(n1)
s.add(n2)
s.add(n3)
pri... |
def selectionSort(data):
for fidx, focus in enumerate(data):
min = focus # set focus
midx = fidx
for idx, i in enumerate(data): # find minimum
if min > i and idx >= fidx: # idx must bigger than fidx
min = i
midx = idx
data[fidx], data[m... |
from random import random
from IPython.core.debugger import Tracer
def main():
printIntro()
probA, probB = getInputs()
# I force 1000 games to make result usable because if let user enter very close
# prob like A=0.7, B=0.69 then you can not compare anything it just too random
games = 1000
wi... |
""" Heating and cooling degree-days are measures used by utility companies to estimate energy requirements. If the average temperature for a day is below 60, then the number of degrees below 60 is added to the heating degree-days. If the temperature is above 80, the amount over 80 is added to the cooling degree-days. W... |
def AE():
print("Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!")
def BCD(animal, sound):
print("And on that farm he had a {}, Ee-igh, Ee-igh, Oh!".format(animal))
#print("With a", sound "," sound, "here and a", sound ",", sound, "there.")
print("With a {0}, {0} here and a {0}, {0} there.".format(sound)... |
def main():
print()
print("This will add up numbers you provide!")
print()
l = list(eval(input("Enter your numbers separated by commas: ")))
Sum = 0
print()
for num in l:
Sum = Sum + num
print("The sum of those numbers is", Sum)
print()
main()
|
# True/False
# 1. False, could also be in single quotes
# 2. True
# 3. False, can contain any sequence of characters
# 4. True
# 5. True
# 6. True
# 7. True
# 8. False, that's far too easy to break
# 9. False, use "append". Add is for sets
# 10. False, use "open"
# Multiple Choice
# 1. d) indexing
# 2. c) s[:len(s)-... |
# cube.py
# Class definition for a cube
class Cube:
def __init__(self, side_length):
self.side_length = side_length
def getSideLength(self):
return self.side_length
def surfaceArea(self):
return 6 * self.side_length ** 2
def volume(self):
return self.side_length ... |
# gpa.py
# Program to find student with highest GPA
class Student:
def __init__(self):
self.name = ""
self.hours = float(0)
self.qpoints = float(0)
self.credits = self.hours
self.gradePoint = float(0)
self.letterGrade = ""
def getName(self):
return s... |
from random import choice, randint
# card.py
# Class that represents playing cards
class Card:
def __init__(self, rank, suit):
self.rank = int(rank)
self.suit = str(suit)
def getRank(self):
return self.rank
def getSuit(self):
return self.suit
def BJValue(self):
... |
# File: chaos2: Electric Boogaloo
# A simple program illustrating chaotic behavior.
def main():
print("This program illustrates a chaotic fuction")
x = float(input("Enter a number between 0 and 1: "))
y = float(input("Enter another number between 0 and 1: "))
n = int(input("How many numbers should I pr... |
from random import random
def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB, ralWinsA, ralWinsB = simNGames(n, probA, probB)
printSummary(winsA, winsB, ralWinsA, ralWinsB)
def printIntro():
print("This program simulates a game of tennis between two")
print('players called "A"... |
from random import randrange
def main():
printIntro()
n = getInput()
position = randomWalk(n)
printOutro(n, position)
def printIntro():
print("\nThis app simulates 1D random walks with coin flips.")
def getInput():
n = int(input("\nHow many coin flips? "))
return n
def randomWalk(n):
... |
def acronym(phrase):
Sphrase = phrase.split()
ac = ""
for w in Sphrase:
ac = ac + w[0]
return ac
def main():
phrase = input("Enter a phrase you want an acronym for: ")
print("The acronym is {0}".format(acronym(phrase).upper()))
main()
|
def count(myList, x):
total = 0
for item in myList:
if item == x:
total += 1
return total
def isin(myList, x):
for item in myList:
if item == x:
return True
return False
def index(myList, x):
for index, item in enumerate(myList):
if item == x:
... |
def sumN(n):
Sum = 0
for i in range(1, n + 1):
Sum = Sum + i
return Sum
def sumNCubes(n):
Sum = 0
for i in range(1, n + 1):
Sum = Sum + i ** 3
return Sum
def main():
n = int(input("Enter an integer n: "))
print("The the sum of first n natural numbers is {}".format(sumN(... |
def babysitterBill(start, end):
HS, MS = int(start[:2]), int(start[-2:])
HE, ME = int(end[:2]), int(end[-2:])
hours = HE - HS
minutes = (ME - MS)/60
print("minutes", minutes)
Thours = hours + minutes
m = int((Thours - Thours//1)*60)
print("m", m)
h = int(Thours//1)
print("h", h)
... |
def main():
print()
print("This will average numbers you provide!")
print()
n = int(input("How many nummbers will you be averaging?: "))
avg = 0
print()
for num in range(n):
number = int(input("Enter number: "))
avg = avg + number
avg = avg / n
print("The ave... |
import requests
import json
my_api_key = "3wafa48C2dr0qASN28zcHCfqvwixdVL6BiJKNiEz"
class APOD:
def getAPODToday():
query = "https://api.nasa.gov/planetary/apod?api_key={}".format(
my_api_key
)
response = requests.get(
query,
headers = {
... |
# For computations and plotting
import numpy as np
import matplotlib.pyplot as plt
from numpy import cos, sin
# Orthogonal transformations
# Theory: https://mathworld.wolfram.com/EulerAngles.html
# According to Euler's rotation theorem, any rotation may be described using three angles.
# If the rotations are written ... |
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
x = np.linspace(-6, 6, 25)
y = np.linspace(-6, 6, 25)
# General equation for an ellipsis
# x^2/a^2 + y^2/b^2 = 1
# or
# x^2/a^2 + y^2/b^2 - 1 = 0
#
# If our center has an offset:
# (x-x0)^2/a^2 + (y-y0)^2/b^2 = 1
# Creating cartesian coordin... |
'''
En este ejercicio deberás crear un script llamado contador.py que realice varias tareas
sobre un fichero llamado contador.txt que almacenará un contador de visitas (será un número):
Nuestro script trabajará sobre el fichero contador.txt.
Si el fichero no existe o está vacío lo crearemos con el número 0.
Si exis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.