text stringlengths 37 1.41M |
|---|
def arraySum(numbers):
# Write your code here
length = len(numbers)
sum = 0
if(isinstance(numbers,list)):
for number in numbers:
sum = sum + number
return sum
else:
return
#TEST CASE ONE
numbers = [1,2,3,4,5]
print(arraySum(numbers)) |
#Indra Ratna
#CS-UY 1114
#05 Oct 2018
#Lab 5
#Problem 4
terms = int(input("Enter a positive integer: "))
v1 = 1
v2 = 1
count = 0
while(count<terms):
print(v1,end=" ")
new = v1+v2
v1=v2
v2=new
count+=1
|
from input_functions import validate, convert_to_rpn, find_minterms
from Quine_McCluskey import minimize
def main():
while True:
print("\nOperators:\n and: &\n or: |\n xor: ^\n not: ~\n implication: >\n equivalence: =\n")
print("Use: ( x | y ) > ( ~ a ) & b\nor: Me&You > You&(~Him)|(Him^You)\n")
... |
import matplotlib.pyplot as plt
import numpy as np
def Bisection(f,a,b,tol,max_iteration):
iter = 0
while True:
c = (a+b)/2
x = f(c)
y = f(a)
if x == 0:
return(c)
elif (x * y) <0:
b = c
else:
a = c
iter = iter + 1
... |
def add1():
x = 1
return lambda y: x+y
a = add1()
b = add1()
print a(9)
print b(99)
def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def hello():
return "hello"
hello = makebold(hello)
print(hello())
|
n1 = int(input('Valor:'))
n2 = int(input('Valor_:'))
s = n1 + n2
m = n1 * n2
d = n1 / n2
di = n1 //n2
e = n1 ** n2
print('A Soma É {} \n A multiplicação é:{} \n Divisão é {:.3f} ' .format(s, m, d))
print('Divisão Inteira é: {} \n A Potencia é: {}' .format(di, e)) |
'''
from math import factorial
n = int(input("Digite Um Numero Para Fatorial: "))
f = factorial(n)
print("O Fatorial de {} é {}".format(n,f))
'''
n = int(input("Digite Numero: "))
c = n
f = 1
print("Calculando {}!= ".format(n), end="") # Esclamação Significa Fatorial
while c > 0:
print("{} ".format(c... |
n1 = int(input('Nota_1'))
n2 = int(input('Nota_2'))
n3 = int(input('Nota_3'))
n4 = int(input('Nota_4'))
n5 = int(input('Nota_5'))
R = (n5+ n4+ n3 + n2 + n1) / 5
print ('A media é igual a:{}'.format(R))
|
Sal = float(input('Qual Seu Salário?? R$: '))
R_ = (Sal / 100 * 15) + Sal
print ('Almento Salarial de 15% {:.2f}R$ Para -> Novo Salário: {:.2f}R$'.format(Sal, R_))
|
print('Gerador de PA')
print(78*"=*=")
primeiro = int(input('Primeiro Termo: ')) #VAI SER SOMADO AO SEGUNDO
razão = int(input("Razão PA: ")) #SEGUNDO TERMO VAI SENDO SOMADO A ELE MESMO+ O PRIMEIRO TERMO
termo = primeiro
cont = 1
tot = 0
mais = 10 #A quantidade de termos\numeros que é mostrada quando o usuario ... |
from datetime import date
ano = int(input('Que Ano Quer Analizar? Coloque 0 para Analisar o Ano Atual: '))
if ano == 0:
ano = date.today().year
if ano % 4 == 0 and ano % 100 !=0 or ano % 400 ==0:
'''O Sinal de ! na linha acima significa:
Que se o que estiver antes dele(!) for falso,
então execu... |
# 09-01-19
from collections import OrderedDict
#Nesta nova vdersão Tuplas podem ser usadas SEM Parenteses:
lanche = ("Burg","Suco",'pizza','Pudim')
#__________________
for La in lanche[0:4]: #Se eu Especificar O Fatiamento na Tupla\Lista etc,
#..Ele Omite\ Mostra Itens da Tupla.
#Se eu usar o fatiament... |
from math import hypot
#import math
co = float(input('Comprimento do Cateto Oposto:'))
ca = float(input('Comprimento do Cateto Adjacente:'))
'''hi = (co ** 2 +ca ** 2 ) ** (1/2)
print('A Hipotenusa Vai Medir {:.3f}'.format(hi))'''
hi = hypot(co,ca)
#hi = math.hypot(co,ca)
print('A Hipotenusa Vai Medir {:... |
#22-07-2020
"""
#Minha Tentativa :/
qtd = 6
store = []
for qtd in range(0, 6):
entrada = int(input("Digite Um numero: "))
store.append(entrada)
print(store)
for x in store:
print("Maior Valor =", max(x))
print("Menor Valor = ", min(x))
"""
#https://youtu.be/q8Z1cRdJnfk?list=PLHz_AreHm4dksnH2jV... |
frase = str(input('Digite Uma Frase: ')).strip().upper() #Colocou o UPPER Aqui Para não ter problemas com tamanho de letras
palavras = frase.split()
junto = ''.join(palavras) #Este comando junta todas as palavras com o simbolo que estiver (ou não) entre as Aspas
print('Você digitou a frase {} '.format(frase))
print... |
'''
Coded triangle numbers
Problem 42
The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding to its alphabetical position and adding these values w... |
'''
Cyclical figurate numbers
Problem 61
Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated by the following formulae:
Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ...
Square P4,n=n2 1, 4, 9, 16, 25, ...
Pentagonal P5,n=n(3n−1)... |
class Solution:
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
_size = len(nums)
#print(_size)
lastReachable = _size - 1;
for i in range(_size-1, -1, -1):
if(i + nums[i] >= lastReachable):
... |
def a():
print('a() starts')
b()
d()
print('a() returns')
def b():
print('b() starts')
c()
print('b() returns')
def c():
print('c() starts')
print('c() returns')
def d():
print('d() starts')
print('d() returns')
a()
# Python will remember which line of code called the f... |
# isX() Methods return True or False depending on the contents of the string
''' isapha() returns True if the string consists of letters ONLY and isn't blank ; is alphabet
isalnum() returns True if the string consists only of letters and #s and is not blank ; is alphabet and numbers
isdecimal() returns True fi the str... |
#1. Which of the following are operators, and which are values?
# * is an operator
# 'hello' is a string value
# -88.8 is a floating point number value
# - is an operator
# / is an operator
# + is an operator
# 5 is an integer value
#2. Which of the following is a variable, and which is a string?
# spam is a variable a... |
# Multiline string is used for hash comments that are really long!
"""This is a test Python program.
Written by Anna Ween @me.com
This program was designed for Python 3, not Python 2.
"""
def spam():
"""This is a multiline comment to help
explain what the spam() function does."""
print('Hello!')
# Inde... |
def addToInventory(inventory, addedItems):
total = 0
for i in range(len(dragonLoot)): # check dragonLoot to see if there is a match
for k in inv.keys(): # add 1 to the value if it is found in inv
if inv.keys() in dragonLoot:
return (inv.values() + 1)
else:
... |
# import random
# numberOfStreaks = 0
# H = 'heads'
# T = 'tails'
#
# for experimentNumber in range(10000): # Code that creates a list of 100 'heads' or 'tails' values
# if random.randint(0, 1) == 0:
# print(list('H'))
# elif random.randint(0, 1) == 1:
# print(list('T'))
#
# if H or T == 6:
# ... |
#!/usr/bin/env python3
# Mark Pasquantonio
# Senior Design and Dev COMP490
# Project 1 JobsAssignment Sprint 2
# Filename: get_git_database.py
import sqlite3
from sqlite3 import Error
global connection
def create_connection():
global connection
db_file = "git_jobs.sqlite"
""" create a database connecti... |
# Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters - each taken only once - coming from s1 or s2.
def longest(a1, a2):
new="" # make a string
lst=[] # make a list
lst2=[] # make a list
final="" # make a string
new+=a1 # ... |
def validate_pin(pin):
pin="".join(num for num in pin if num.isnumeric())
print(pin)
for num in pin:
if num
if len(pin)<4:
return False
elif len(pin)>6:
return False
elif len(pin)==4:
return True
elif len(pin)==6:
return True
elif len(pin)==5:
... |
# def gimme(input_array):
# print(input_array.sort(key=len))
# if input_array==[]:
# return[]
# dup_arr=input_array
# l=sorted(dup_arr)
# mid=l[1]
# for num in input_array:
# if num==mid:
# print(num)
# num_i=input_array.index(num)
# return num_i
# pri... |
# Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms.
# If you want to know more http://en.wikipedia.org/wiki/DNA
# In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". You have fu... |
def mxdiflg(a1, a2):
short_a1, short_a2="",""
i=0
while i<len(a1):
if len(a1[i])>len(short_a1):
short_a1+=(a1[i])
i+=1
print(short_a1)
i=0
while i<len(a2):
if len(a2[i])>len(short_a2):
short_a2+=(a2[i])
i+=1
answer= max(len(short_a1... |
def solution(number):
if number<0:
return 0
list=[]
i=1
while 0<=i<number:
list.append(i)
i+=1
sum=0
for num in list:
if (num%5==0) or (num%3==0):
sum+=num
return sum
print(solution(20)) |
def alphabet_position(text):
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']
strng=""
for let in text:
let=let.lower()
if let in alpha:
x= alpha.index(let)+1
x=str(x)
strng+=x
strn... |
def is_valid_walk(walk):
vertical=0
horizontal=0
starting_point=0
num_n=walk.count('n')
num_e=walk.count('e')
num_s=walk.count('s')
num_w=walk.count('w')
for movement in walk:
if movement== "n":
vertical+=1
starting_point+=1
if movement== "e":
horizontal+=1
starting_po... |
# This program is showing content based recommender system based on movie description
import pandas as pd
from ast import literal_eval
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
class ContentBaseRecomender:
"""
this is content base recommende... |
import re
file_name = input()
reg = input()
input_file = open(file_name, mode="r")
fileLines = input_file.readlines()
for line in fileLines:
if re.search(reg, line):
print(line)
|
import math
r = 2
area = math.pi * pow(r,2)
print("{:.10f}".format(area))
|
def _odd_iter():
n=1
while True:
n = n+2
yield n
def _not_divisible(n):
return lambda x: x%n>0
def primes():
yield 2
it = _odd_iter()
while True:
n = next(it)
yield n
it = filter(_not_divisible(n),it)
for i in primes():
if i < 1000:
print(i... |
#!/usr/bin/python3
import math
class Unit(object):
def __init__(self, value, gradient):
self.value = value
self.gradient = gradient
class MultiplyGate(object):
def forward(self, u0, u1):
self.u0 = u0
self.u1 = u1
self.utop = Unit(self.u0.value * self.u1.value, 0.0)... |
# Corey Caskey
# Section C3
# GT ID: 903120273
# ccaskey6@gatech.edu
# I worked on the homework assignment alone, using only this semester's course materials.
# cocaCola
# parksAndRec
# iLoveFrozen
# oscars
# springBreakCalc
# breakfastPlatters
def cocaCola():
bottles = int(input("How many cans of Coke have you bo... |
#https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/magical-word/
prime_numbers = []
def is_prime(number):
if number == 1:
return True
if number > 1:
for _ in range(2, number):
if (number % _) == 0:
... |
data = open("dataAnalysis1.txt","r");
dataString = data.read()
dataList = dataString.split("\n")
for i in range(0, len(dataList), 1):
dataList[i] = dataList[i].replace(",","")
dataList[i] = float(dataList[i])
minimum = min(dataList)
print(minimum)
maximum = max(dataList)
print(maximum)
diff = maximum - minimum
... |
import tkinter as tk
print("Start Program")
root = tk.Tk() #Builds main window
#Step 1: Construct the widget
btn1=tk.Button(root, width = 10, height = 5)
#Step 2: Configure the widget
btn1.config(text = "I am a button")
#Step 3: Place the widget - pack(), grid()
btn1.pack()
output = tk.Text(root, width=100, height=... |
#### K nearest neighbor ####
from math import sqrt
# calculate the Euclidean distance between two vectors
def euclidean_distance(row1, row2):
distance = 0.0
for i in range(len(row1)-1):
distance += (row1[i] - row2[i])**2
return sqrt(distance)
# Locate the most similar neighbors
def get_neighbors(t... |
# # Scooter sharing in Austin, Texas
# In many cities around the world, micromobility in the form of
# electric scooters has recently become very popular. The city of
# Austin, Texas has made available trip-level data from all scooter
# companies operating within the city limits.
# This is the first notebook that we... |
"""
Board class used in the m, n, k game.
"""
class Board:
def __init__(self, m, n, k):
self.m = m
self.n = n
self.k = k
# used to keep track of who has won or if the game is finished
self.scores = [0 for i in range(m + n + 2*(m+n-1))]
self.positions_occcupied = ... |
# -*- coding: utf-8 -*-
import re
seq1 = input("escreva a sequência 1:")
seq2 = input("escreva a sequência 2:")
check = re.match(seq1, seq2)
if (check == None):
print("sequências distintas!")
else:
print("sequências identicas!") |
## -*- coding: utf-8 -*-
idade = int(input("qual a sua idade?"))
while(idade < 0):
print("número invalido!!")
idade = int(input("qual a sua idade?"))
if (idade > 18 or idade == 18):
print("você é maior de idade.")
elif (idade > 0 and idade < 18):
print("você é menor de idade")
|
## -*- coding: utf-8 -*-
import re
string = "me namora pois quando eu saio eu sei que vc chora e fica em casa so contando as horas"
## método search print somente o primeiro resultado
busca = re.search("[^ ]*[r|R][^ |\.]*", string)
if busca:
print(busca.group())
## método findall printa todos os resultados
bu... |
tu = 43.85, 5, False, "plijy"
print(tu)
print(tu[1])
f3 = tu[:3]
print(f3)
l3 = tu[2:]
print(l3)
m2 = tu[1:3]
print(m2)
wis = ("Bohr", "Leibniz", "Einstein")
wis1 = []
wis2 = [9, 8 , 7, 6, 5, 4, 3, 2, 1, 0]
for vis in wis :
print(vis)
for dig in wis2 :
wis1.append(dig)
print(wis1) |
class Animal:
# we can also inherte the attributes of the base class
def __init__(self):
self.age = 1
def eat(self):
print("Eat")
# Animal is Parent, Base Class
# Mammal is a Child, Sub Class
class Mammal(Animal):
#Method overloading : means replacing or extendig the method d... |
#!/usr/local/bin/python3
# Josh Klaus
# CS131A
# Python
# A CGI program which serves up all the words from the dictionary which start with a given stem.
# The stem was passed as an HTTP parameter called “stem”.
import cgi, cgitb, codecs
cgitb.enable()
# Create instance of FieldStorage
form = cgi.FieldStorage()
# ... |
from functools import reduce
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
print('squared: {}'.format(squared))
new_squared = list(map(lambda x: x**2, items))
print('new_squared: {}'.format(new_squared))
def multiply(x):
return x*x
def add(x):
return x+x
f... |
m1=int(input("mark of s1:"))
m2=int(input("mark of s2:"))
m3=int(input("mark of s3:"))
total=m1+m2+m3
print("total is",total)
if(total>145):
print("A+")
elif((total>=140)&(total<=145)):
print("A")
elif((total>=135) & (total<=140)):
print("B+")
elif((total>=130) & (total<=135)):
print("B")
else:
prin... |
'''
Este juego es una implementacion del juego clasico de memorias en Python 3.3.2, donde se tiene que encontrar
todos los pares de cartas con el mismo numero para ganar el juego.
MEMORY GAME
Created by: Jassael Ruiz
Version: 1.0
'''
import sys
sys.path.append("..")
import simplegui
import random as rand
WIDTH = 800... |
t = (3, 30, 2019, 9, 25)
dic = {
'hour': t[0],
'minute': t[1],
'year': t[2],
'month': t[3],
'day': t[4]
}
print('%02d'%dic["month"], end = '/')
print('%02d'%dic["day"], end = '/')
print('%04d'%dic["year"], end = ' ')
print('%02d'%dic["hour"], end = ':')
print('%02d'%dic["minute"]) |
#!/usr/bin/env python
def convert_from_strarray(str_array):
"""
string 配列を文字列に変換
:param str_array: 文字列が格納された配列
:return: html用配列文字列
"""
return u"[\'" + u"\',\'".join(str_array) + u"\']"
def convert_from_intarray(int_array):
"""
integer配列を文字列に変換
:param int_array: integerが格納された配列
... |
def DisplayFile():
try:
fd = open('Demo.txt','r', encoding ='utf-8')
except IOError as io:
print('File dose not exists:')
#data = fd.read()
else:
print('File exists:')
print(fd)
data = fd.read()
print('File Data is:',data)
fd.close()
DisplayFile() |
def chknum(no):
if(no > 0):
print("number is positive");
elif(no < 0):
print("number is nigative");
else:
print("number is Zero");
chknum(10);
chknum(-8);
chknum(0); |
arr = list()
def listdemo():
sum = 0;
no = int(input("how many number u print: "));
for i in range(0,no):
n =int(input("number:"));
sum = sum + n;
arr.append(int(n));
return sum;
ret = listdemo();
print("your Elements is ", arr);
print("Addition of list", ret);
|
def fact(no):
factorial = 1;
if no < 0:
print("number is negative");
elif no == 0:
print("number is zero");
else:
for i in range(1,no+1):
factorial = factorial * i;
print("factorial is",factorial);
fact(5); |
# Enoncé : Créez une fonction qui va dire bonjour à quelqu'un. Elle a un paramètre, le nom de la personne
# que le programme salue.
# Essayez d'appeler la fonction de 4 manières différentes
# et une fois avec un input
# stocké dans une variable.
def bonjour (_name):
print (f"Bonjour à toi {_name}")
#1er
bo... |
# On peut voir le "while" comme un "if". Sauf qu'à la différence du if, le code se trouvant dans un while
# est executé en boucle le temps que l'expression booléenne passe à false. On a donc un code comme ceci
# while (condition):
# CodeSExecutantEnBoucle()
# Le problème de ce code, c'est qu'il n'y a rien qui permet de... |
#Ici vous trouverez la fonction que j'ai faite (jessie) en classe pour calculer l'année de naissance en fonction de l'âge entré par l'utilisateur
def CalculateBitdate(_age):
_currentYear = 2021
print("Vous avez" + str(age) + "ans et vous êtes né en "+ str(_currentYear -int(_age)))
age = input("Quel est votre ... |
"""
A game is a dictionary with the following structure:
{
board: [['X', '', ''], ['', 'O', ''], ['X', '', '']]
players: [player_foo, player_bar]
turn: player_foo
}
"""
GAMES = []
def get_game(player_id):
"""Find the game in which player_id is playing."""
for game in GAMES:
if player_id in... |
from array import *
arr = array('i', ())
n = int(input("enter the length of array"))
for i in range(n):
x = int(input("enter the length of array"))
arr.append(x)
print(arr)
val = int(input("enter the value"))
for k in range(n):
if (val == arr[k]):
print(" value is at :" ,k )
# else:
# print("n... |
from array import *
vals = array( 'i' ,[1,2,3,4,5,6,7,8])
print(vals)
# for i in range(3):
# while(i<7):
# f = i+1
# print(vals[f] , end = " ")
# i = i+1;
# print("\n")
# m = number of shift
# n = size of array
# e = incremental integer
g=0
while(g<4):
for e in range (8):
... |
from datetime import datetime, date
date_of_birth = datetime.strptime(input("Enter date of birth in the format dd mm yyyy: "), "%d %m %Y")
future_day = datetime.strptime(
input("Enter the date when you want to find the age, in the format dd mm yyyy: "), "%d %m %Y")
def calculate_age(sDate, eDate):
#TODO: try... |
# move Zero
# 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
# 双指针
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
# length = len(nums)
# i = j = 0
# while j < length:
# if nums[j] != 0:
# nums[i], nums[j] = nums[j], nums[i]
# i += ... |
# 64. 最小路径和
# 给定一个包含非负整数的 m x n 网格 grid ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
# dp
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
dp = grid
m = len(dp)
n = len(dp[0])
for i in range(m):
for j in range(n):
if i == 0 and j == 0: continue
... |
##
# displayinfo.py
# DisplayInfo class. Pop up window with radio buttons to select an option
# name: Gregory Marvin
##
import tkinter as tk
import tkinter.messagebox as tkmb
from PIL import ImageTk, Image
import requests
import textwrap
from movieData import MovieData
from playtrivia import PlayTrivia
class DisplayI... |
#!/usr/bin/env python
# ocw05_funtions.py
var1 = 10
var2 = 5
def function():
var1 = 20
print 'Inside of this function, var1 is:', var1
return 'Hello world!'
print function()
def funct(var1, var2):
print 'inside this ideration of the function, var1 is:', var1
print 'and var2 is:', var2
return var1**var2
print fun... |
#!/usr/bin/env python
x = raw_input("Input number: ")
x = int(x)
#print(type(x))
if x < 100:
print("Too Bad")
elif x == 100:
print("Not Bad")
else:
print("meh.")
|
#!/usr/bin/env python
# Spencer Harper's Split Calculator
def addI(person, item):
People[person] = People[person] + item
return
def choose(selection):
if selection == 'end':
person = 'end'
return person
else:
person = raw_input('Input person: ')
if person == 'Mel' or person == 'Dyl'\
or p... |
#!/usr/bin/env python3
import re
result = re.search("Spencer", "My name is Spencer, dude.")
print(result)
|
#!/usr/bin/env python
# ocw15-palindromes.py
from string import *
def flip(string):
string3 = []
x = 1
y = len(string)
while len(string3) < y:
string3.append(string[-x])
x += 1
return join(string3, '')
def palindrome(string):
x = len(string) / 2
string1 = string[:x]
string2 = string[-x:]
string3 = fli... |
from tkinter import Frame, Label, Entry, Button, W,E, FLAT
from frames.Home import Home
from classes.User import User
#Ventana de inicio de sesion
class Login(Frame):
def __init__(self, parent):
self.parent = parent
super(Login,self).__init__(parent, pady=100)
self.label_title = La... |
#coding=utf-8
class Gragh():
def __init__(self,nodes,sides):
'''
nodes 表示点
sides 表示边
'''
self.sequense = {}
self.side=[]
for node in nodes:
for side in sides:
u,v=side
if node ==u:
self.side.app... |
"""Module to work with geocoding-related stuff."""
from typing import Tuple
import httpx
from settings import settings
YANDEX_GEOCODER_API_URL = 'https://geocode-maps.yandex.ru/1.x'
class UnknownAddressError(Exception):
"""Raised when address is not recognized."""
def fetch_coordinates(address: str) -> Tuple... |
import numpy as np
import random
class Network:
def __init__(self,sizes,weights= None, biases= None) -> None:
if biases!=None or weights!=None:
print("Network loaded")
self.layers= len(sizes)
self.sizes= sizes
self.weights= weights
self.... |
import matplotlib.pyplot as plt
plt.plot([1,2,3,4]) #给ploy()一个列表数据[1,2,3,4],matplotlib假设它是y轴的数值序列,
# 然后会自动产生x轴的值,因为python是从0作为起始的,所以这里x轴的序列对应为[0,1,2,3]。
plt.ylabel('some numbers') #为y轴加注释
plt.show()
import matplotlib.pyplot as plt
plt.plot([1,2,3,4],[1,4,9,16],'ro')
plt.axis([0,6,0,20]) #axis()... |
# -*- coding:utf-8 -*-
# @Author :kobe
# @time :13/4/2019 上午 9:41
# @File :get_time.py
# @Software : PyCharm
import time
class GetTime(object):
def getCurrentDate(self):
date = time.strftime('%Y-%m-%d') # 当前日期格式为:2019-4-13
return date
def getCurrentTime(self):
now = time.s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 11 17:31:58 2018
@author: virajdeshwal
"""
import matplotlib.pyplot as plt
import pandas as pd
import random
file = pd.read_csv('Ads_CTR_Optimisation.csv')
'''We are dealing with the different version of the same advertisement for the user'''
''... |
#!/usr/bin/env python
# encoding: utf-8
"""
@version: v1.0
@author: XF
@site: https://www.cnblogs.com/c-x-a
@software: PyCharm
@file: Queues.py
@time: 2020/2/14 21:40
"""
class ArrayQueue:
Default_Capacity = 10
def __init__(self):
"""
Create a empty queue.
"""
self.data = [[]... |
import os
import csv
import numpy as np
# Path to collect data
csvpath = os.path.join('budget_data.csv')
with open(csvpath, newline='') as budget_csv:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(budget_csv, delimiter=',')
# Read the header row first (skip thi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 22:46:35 2020
@author: AktorEvan
"""
import pandas as pd
doc = input("Please input the file name: ")
colName = input ("Please input the column name: ")
print("Loading the file, please wait..", "\n")
file = pd.ExcelFile(doc+".xlsx")
sheet_list... |
if __name__ == '__main__':
y, x = int(input()), int(input())
count = 0
print("All step: ")
while(y != x):
if x * 2 - y <= x - y // 2:
x *= 2
print("x * 2")
else:
x -= 1
print("x - 1")
count += 1
print(x)
print("Total ste... |
'''
You're given the three angles a, b, and c respectively.
Now check if these three angles can form a valid triangle with an area greater than 0 or not.
Print "YES"(without quotes) if it can form a valid triangle with an area greater than 0, otherwise print "NO".
'''
a,b,c=map(int,input().split(" "))
if (a+b+c)==180... |
#1.anaconda环境配置和解释器
将anaconda安装目录下的scripts文件的全路径添加到系统变量path中,python的默认解释器就是anaconda了
#2. print和input
#1)print(*objects, sep=' ', end='\n', file=sys.stdout),无论什么类型,数值,布尔,列表,元组、字典...都可以直接输出,格式化输出中%字符是标记转换说明符的开始
1.输出字符串和数字
print("felix") # 输出字符串
print(100) # 输出数字
str = 'felix'
print(str) # 输出变量
L =... |
import random
def random_value():
value = random.randint(0,9);
return value;
def get_odd_start_position():
string_position = '';
names1 = [1,1,2,2,2,1,1,2,2,2];
names2 = ['k','q','r','n','b','K','Q','R','N','B'];
for i in range(8):
value = random_value();
while (names1[value] ... |
pi=3.141
r=int(input("Enter Radius of cirle"))
area=pi*r**2
print("the area of circle os ",area)
|
import turtle
import time
heart = turtle.Pen()
i=20
heart.color("red")
heart.left(45)
heart.forward(100)
heart.right(90)
heart.forward(100)
heart.right(90)
heart.forward(200)
heart.right(90)
heart.forward(200)
heart.right(90)
heart.forward(100)
heart.right(90)
heart.forward(100)
heart.left(135)
heart.forward(i)
he... |
import turtle
import random
toad = turtle.Pen()
color = ["red", "green", "black", "blue", "yellow"]
toad.shape("turtle")
toad.hideturtle()
toad.speed(0)
for i in range(200):
toad.fillcolor(random.choice(color))
toad.begin_fill()
toad.circle(2*i)
toad.left(10)
toad.end_fill()
# for j in range(... |
# data attributes: account_num, interest_rate, and balance
class SavingsAccount:
def __init__(self, account_num, interest_rate, balance):
self.account_num = account_num
self.interest_rate = interest_rate
self.balance = balance
# methods: get_account_num, check_balance, apply_interest, d... |
# # class Person:
# # def __init__(self, name, age):
# # self.name, self.age = name, age
# # def getName(self):
# # print("Name: %s" %(self.name))
# # def getAge(self):
# # print("Age: %d" %(self.age))
# # def getSex(self):
# # print("Sex: %s" %(self.sex))
# # class Male(Person):
# # sex = "Male"
# # ... |
def hello(name):
print("Hello " + name + " !")
hello("Kim")
def sum(list, start =0):
sum = 0
i = start
while i < len(list):
sum += list[i]
i += 1
return sum
# for i in list:
# sum += i
# return sum
result = sum([1,2,3], 2)
print("result: %s" %result) |
#!/usr/bin/env python
import pandas as pd
def avgcity(city, my_csv):
citypop = {}
for line in my_csv:
mycity = line["loc"] #identificamos la localidad
pop = float(line["pop"])# identificamos la poblacion y transformamos a un numero float
if line["cases"] != "NA": # en este caso NA es ... |
'''class shifu(object):
def __init__(self):
self.hui = '煎饼果子配方'
def zuo(self):
print(f'我会用{self.hui}做煎饼果子')
class tudi(shifu):
pass
aa = tudi()
aa.zuo()
'''
'''class shifu(object):
def __init__(self):
self.gongfu = '麻辣'
self.__qian = 200
def make(self):
pr... |
euro = int(input("Diguem una quantitat d'euros\n"))
print("el valor en pesetes es:",euro*166.3860)
|
from math import sqrt
A = int(input("Nombre elevat a 2\n"))
B = int(input("Nombre elevat a 1\n"))
C = int(input("Terme independent\n"))
if ((B**2)-4*A*C) < 0:
print("La rael dona negativa")
else:
print("les solucions són")
print((-B+sqrt(B**2-(4*A*C)))/(2*A))
print((-B-sqrt(B**2-(4*A*C)))/(2*A))
|
preu = int(input("Quin es el preu del producte?\n"))
IVA = int(input("quin es el porcentatge de IVA?\n"))
print("l'IVA són:", IVA/100*preu,"€")
print("El preu total es:",IVA/100*preu+preu,"€")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.