text stringlengths 37 1.41M |
|---|
# sieve of Eratosthenes
from math import sqrt
def sieve_of_eratosthenes(start, end):
res = []
it = start
while it <= end:
res.append(it)
it += 1
det = sqrt(end)
ind = 2
while ind <= det:
for i in res:
if (i % ind == 0) & (i != ind):
res.remo... |
# This small program calculates the number of commits per Author and saves it in a dictionary.
# It then prints the number of commits per author and the name of the author.
#
# To get log file to input into program:
# git log > log.txt
#
#
#
# I also added a second function (commented out in main) that saves the date... |
def f(a):
return False
def satisfiesF(L):
copiedL = L
L = []
toRemove = []
print copiedL
if copiedL == []:
return 0
for aString in copiedL:
#print aString
if f(aString):
L.append(aString)
print toRemove
#print L
... |
def item_order(order):
order = order.lower()
ham_count = 0
salad_count = 0
water_count = 0
size = len(order)
counter = 0
for char in order:
if counter >= (size-4):
break
if char == 'h':
if counter < (size-8):
comp = order[counter: count... |
''' this program allows users to create their own country for Democracy 3 '''
from tkinter import *
from tkinter import messagebox
import csv
WIDTH = 1255
HEIGHT = 950
# formatting
BG_COLOUR = "light grey"
ENTRY_COLOUR = "white"
HEADING_1 = ("Arial",16)
BUTTON = ("Arial",12)
BODY = ("Arial",8)
SB_WIDTH = 17
# load ... |
vize = int(input("Vize Notu :"))
final = int(input("Final Notu :"))
ortalama = (vize * 0.4) + (final * 0.6) # vizenin %40 final %60 olarak al?nd?
if (ortalama >= 85):
print("Harf notunuz : AA0")
elif (ortalama >= 70 and ortalama < 85):
print("Harf notunuz : BA")
elif (ortalama >= 60 and ortalama < 70):
pri... |
# Name Error, not defined
#print(my_variable)
# Gives Trace (Stacktrace), where it occured
# Bottom: Error Description
# Line of Code raised the error
# Fuction / Stack Trace --> Caller, Caller, Caller...
#Example
#add_movie
#->show_movie
#->->show_movie_details Error
#Built in Errors
# IndexError
## Out of Range
# ... |
def i_return():
return 5 + 5
def i_print():
print(5 + 5)
result = i_return()
print(result)
another = i_print() # Returns None
print(another)
def fives():
addition = 5 + 5
print(addition)
return addition # stops at return
print('hello')
|
a = 1
b = 2
c = 3
my_sum = a + b
another_sum = 5 + 10
"""
letters, numbers and underscores.
Cannot strart witrh a number
"""
math_operators = 1 + 3 * 4 / 2 - 2
print(math_operators)
float_division = 12 / 3
print(float_division)
integer_division = 12 // 3
print(integer_division)
division_with_reminder = 12 // 5
re... |
# Ask for forgiveness, not for permission
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def __repr__(self):
return f'{self.make} {self.model}'
class Garage:
def __init__(self):
self.cars = []
def __len__(self):
return l... |
def sortit(arr,n):
for i in range(n):
arr[i]=i+1
if __name__=='__main__':
arr=[10,7,9,2,8,3,5,4,6,1]
n=len(arr,n)
sortit((arr,n)
for i in range(n):
print(arr[i],end="")
|
import math
s1,k=map(int,raw_input().split())
p=s1*k
if math.sqrt(p).is_integer():
print "yes"
else:
print "no"
|
start=int(input("enter a number"))
end=int(input("enter a number"))
for val in range(start,end):
if val>1:
for n in range(2,val):
if(val%n)==0:
break
else:
print(val)
|
x=int(input("enter the number1:))
y=int(input("enter the number2:))
a=x^y
b=x^y
c=x^y
print("after swapping:x=",a,"y=",b)
|
sentence=input("enter a string:")
count=0
for c in sentence:
if c.isspace()!=true:
count=count+1
print("total number of character",count)
|
str12=input()
m=len(str12)
print(str12[::3],end='')
print(str12[1:m:3],end='')
|
pregunta = input("Dime una frase: ")
numero = 0
for cambiar in pregunta:
if cambiar == "a" or cambiar == "e" or cambiar == "i" or cambiar == "o" or cambiar == "u":
pregunta1 = pregunta.find(cambiar) + 1
pregunta1 = str(pregunta1)
pregunta = pregunta.replace(cambiar, pregunta1, 1)
print(pre... |
lista = ["asd", "hola", "lucia", "papa", "patatas", "cinco"]
listado = []
for recorrido in lista:
listado.append(len(recorrido))
print("Cada string de la lista la longitud de {} ".format(listado)) |
numeros = [1, 2, 3, 4, 5, 15, 123, 23, 434, 54, 64, 75]
lista_2 = []
lista_3 = []
lista_5 = []
lista_7 = []
for indice in range(len(numeros)):
posicion = numeros[indice]
if posicion % 2 == 0:
lista_2.append(posicion)
if posicion % 3 == 0:
lista_3.append(posicion)
if posicion % 5 ==... |
def sum_even_fibonacci(n_max):
fib_n_1 = 0
fib_n = 1
sum = 0
while fib_n <= n_max:
new_fib = fib_n_1 + fib_n
fib_n_1 = fib_n
fib_n = new_fib
if fib_n % 2 == 0:
sum += fib_n
return sum
print(sum_even_fibonacci(3999999))
|
#Anthony Sistilli
#Example using Scikit learn with Linear regression on a random dataset from the internet
#Following tutorial from: http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html#sphx-glr-auto-examples-linear-model-plot-ols-py
###################################################################... |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 14 17:57:23 2018
@author: Kurt Tito
EE 381
"""
from scipy.special import comb
print("\n PART 1 \n")
# PART 1
# Exercise 1: Calculating binomial probabiliity using its PMF.
# ------------------------------------------------
n = 5
x = 3
p = 0.7
C = comb(n, x)
q = 1 - p... |
def ordered_word(string1):
maxSubString = ""
temp = ""
previousChar = ""
for char in string1:
if char >= previousChar:
return True
previousChar = char
print ordered_word("aabbddd")
|
def get_all_substrings(input_string):
length = len(input_string)
return [input_string[i:j+1] for i in xrange(length) for j in xrange(i,length)]
print get_all_substrings("abcd") |
def encrypt(string1):
length = len(string1)
count = 1
compression = ""
compression += string1[0]
for index in range(length - 1):
if string1[index] == string1[index + 1]:
count += 1
else:
if (count >= 1):
compression += str(count)
co... |
#Finding Min Value
def min(l):
min = l[0]
i = 1
for i in range(len(l)):
if l[i] < min:
min = l[i]
print i
return min
print min([1,7,3,0,6,9]) |
# Document at least 3 use cases of generators
# 1.
# To FIBONACCI SEQUENCE (a sequence of number that starts with 0 and 1 and subsequent numbers are obtained by adding two consequtive numbers)
def fibonacci(n):
a = 0
b = 1
for i in range(n):
yield a
a, b = b, a+b
fib_list = [x f... |
# Welcome back!
# Yesterday we saw string manipulations
# Let's say we received the following input for a command
# sentence = input("Enter a sentence")
# And we received a sentence with
sentence = "This sentwnce has a typo"
# we can access the location of the typo
print(sentence[9])
# but we cannot change it lik... |
import csv
total_votes = 0
candidates_dictionary = {}
Name = ""
file_path = "./Resources/election_data.csv"
output_file = "./Analysis/output.txt"
with open(file_path) as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile)
# Read the header row first(s... |
# 実行結果
# funny
name =
if name == "Micky" :
print("fine")
elif name == "Minny" :
print("cute")
elif name == "Donald" :
print("funny")
elif name == "Daizy" :
print("lovely")
else :
print("who are you?")
|
class Node:
def __init__(self, data, next_node=None):
self.data = data
self.next_node = next_node
class Data:
def __init__(self, key, value):
self.key = key
self.value = value
class HashTable:
def __init__(self, table_size):
self.table_size = table_size
self... |
#
# @lc app=leetcode id=125 lang=python3
#
# [125] Valid Palindrome
#
# @lc code=start
import re
class Solution:
def isPalindrome(self, s: str) -> bool:
pattern = re.compile("[a-zA-Z0-9]") # remove non-alphanumeric
converted = "".join(pattern.findall(s)).lower()
for i in range(len(... |
import math
import sys
# example cat data
def parseFile(input_file):
with open(input_file) as textFile:
w, h = [int(x) for x in next(textFile).split()] # read first line
input = [ ]
for line in textFile: # read rest of lines
input.append([int(x) for x in line.split()]) ... |
# Day1_Puzzle_Input.txt is a text file with the list of numbers provided for the puzzles
# Advent of Code, Day 1, Puzzle 1:
f = open("Day1_Puzzle_Input.txt", "r")
out = []
n = 0
while True:
line = f.readline()
n = n + 1
if not line:
n = n - 1
break;
out.append(line.strip())
f.close()
for i in ra... |
#Script that determines if a string is a pangram.
import unicodedata, string, re
def is_pangram(chars):
chars = str(unicodedata.normalize('NFD', chars).encode('ascii','ignore'))
chars = re.sub('\W+','', chars)
chars = re.sub('_','', chars)
chars = re.sub('\d','',chars)
chars = set(list(chars.... |
# This program calculates the derivative of a function at a point
# This is a function that you define
def f(x):
return pow(x,2)
def derivative(f, *args):
h = 1./10000000.
slope = (f(*args[0]+h) - f(*args[0]))/h
return slope
derivative(f, 3) # Example
|
# Generates the prime factorization of a number
import math
def generate_primes(n):
"""generate_primes(n) -> list
Returns a list of all primes <= n."""
sqrtN = math.sqrt(n)
if n < 2:
return []
elif n < 3:
return [2]
primes = [2]
... |
# Module for complex numbers
class Complex:
''' Creates a complex number. The first parameter is the real component, the second
parameter is the imaginary component.'''
def __init__(self, r, i):
self.r = r
self.i = i
''' Calling print() will display the complex number in the form... |
# Quick sort
def quick_sort(array):
if len(array) <= 1:
return array
pivot = array[len(array)// 2]
left = [i for i in array if i < pivot]
middle = [j for j in array if j == pivot]
right = [k for k in array if k > pivot]
return quick_sort(left) + middle + quick_sort(right)
|
# Rabin-Karp Algorithm
# Checks if pattern is within the string using hashes
def rabin_karp(string, pattern):
m = len(string)
n = len(pattern)
hash_pattern = hash(pattern)
for i in range(m):
hash_string = hash(string[i:i+n])
if hash_string == hash_pattern:
if string[i:i+n] =... |
# Module for polynomial math
class Polynomial:
''' Creates a polynomial. When inputting the array of coefficients, start
from the degree (highest exponent) term.'''
def __init__(self, coefficients):
# Reverses the input to make addition and other operations easier
self.coefficients = c... |
# https://edabit.com/challenge/u7ykayCJjyQXAk7gw
def count_animals(str):
animals = ["dog", "cat", "bat", "cock", "cow", "pig",
"fox", "ant", "bird", "lion", "wolf", "deer", "bear",
"frog", "hen", "mole", "duck", "goat"]
count = 0
tempStr = list(str)
for animal in animals... |
#https://edabit.com/challenge/XALogvSrMr3LRwXPH
def is_shuffled_well(arr):
count = 0
check = False
temp = []
last_result = 0
for i in range(0, len(arr)):
if(i != len(arr)-1):
res = arr[i] - arr[i+1]
if abs(res) == 1 and check and last_result == res:
... |
#https://edabit.com/challenge/6hh5BsRivRwMhiZrt
def isPrime(num):
for i in range(2, int(num/2)+1):
if num % i == 0:
return False
return True
def sum_ff(num):
arr = []
for i in range(1, num):
if num % i == 0 and not isPrime(i):
arr.append(i)
if(len(arr) != 0... |
# Simple Statistics with a List of Numbers
digits = list(range(0, 10))
print(digits)
print(min(digits))
# 0
print(max(digits))
# 9
print(sum(digits))
# 45
squares = [value**2 for value in range(1,11)]
print(squares)
#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] |
# 5-3. Alien Colors #1: Imagine an alien was just shot down in a game. Create a
# variable called alien_color and assign it a value of 'green', 'yellow', or 'red'.
# • Write an if statement to test whether the alien’s color is green. If it is, print
# a message that the player just earned 5 points.
# • Write one versio... |
# Given a non-negative int n, return the sum of its digits recursively (no loops).
# Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while
# divide (/) by 10 removes the rightmost digit (126 / 10 is 12).
# sumDigits(126) -> 9
# sumDigits(49) -> 13
# sumDigits(12) -> 3
def sumDigits(n):
if (n <... |
# Given a string and a non-empty substring sub, compute recursively the largest
# substring which starts and ends with sub and return its length.
# strDist("catcowcat", "cat") -> 9
# strDist("catcowcat", "cow") -> 3
# strDist("cccatcowcatxx", "cat") -> 9
def strDist(inp, sub):
if (inp == "" or len(inp) < len(sub))... |
# The fibonacci sequence is a famous bit of mathematics, and it happens to have
# a recursive definition. The first two values in the sequence are 0 and 1
# (essentially 2 base cases). Each subsequent value is the sum of the previous
# two values, so the whole sequence is: 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on.
# Def... |
# nlogn
# Select a pivot, usually 1st element
# For the remaining array, left = pivot + 1, right = end; all elements < pivot
# are to left and all element < pivot are moved to right.
# Finally pivot is swapped with right, it's final position
# quicksort left array and right array of pivot.
def quick_sort(input, start, ... |
# Given a string and a non-empty substring sub, compute recursively if at least
# n copies of sub appear in the string somewhere, possibly with overlapping.
# N will be non-negative.
# strCopies("catcowcat", "cat", 2) -> true
# strCopies("catcowcat", "cow", 2) -> false
# strCopies("catcowcat", "cow", 1) -> true
def st... |
import random
#parse through the csv file
def parse(inputfile):
file = open(inputfile, 'r') #open the file in read mode
raw = file.read() #get the text
return raw.split("\n") #split on new lines + return list of lines
#separate jobs from percentages
def separate(inputlist):
index = 0
... |
"""Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.
For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb"."""
def sub_r(s, k):
def _sub_helper(s, k, m):
# print("string", s)
num_d... |
"""Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds."""
from threading import Thread
import time
def job_scheduler(f, n):
delayed_start = Thread(target=_run_after_mils_thread, args=(f, n))
delayed_start.start()
return
def _run_after_mils_thread(f, ... |
import turtle
import pandas
screen = turtle.Screen()
screen.title("Indian states game")
image = "ezgif.com-gif-maker.gif"
screen.addshape(image)
turtle.shape(image)
data = pandas.read_csv("31_states.csv")
states = data["state"].to_list()
states_guessed = [False for i in range(31)]
x_cor = data["x"].to_list()
y_cor = d... |
def bubbleSort(mylist):
moreSwaps = True
while moreSwaps:
moreSwaps = False
for element in range(len(mylist) - 1):
if mylist[element] > mylist[element + 1]:
moreSwaps = True
temp = mylist[element]
mylist[element] = mylist[element + 1]
... |
# 주석 : 개발자가 보기 위한 설명. 프로그램 수행시 해석되지 않는 코드
# 한줄주석
"""
문장
문장2
문장3
"""
'''
여러줄 주석
주석
'''
print(3+5)
print("Hello world!")
print('Hello world')
print("She's gone.")
print("문장",12333)
print(3 + 5)
# 문자열 출력
print("hello world")
# 한 줄로 쓰려면
# 두 문자열 사이에 공백이 들어감
print("She's", "gone")
... |
# 0 ~ 4 : 5개
for i in range(5): # range(0, 5) range(0, 5, 1)
print("신보람", i)
# 1 ~ 5: 5개
for i in range(1, 6):
print("안녕", i)
# 5 ~ 1: 5개
for i in range(5, 0, -1): # 5 4 3 2 1
print("모니터", i)
# 1+2+3+4+5+6+7+8+9+10 합계
sum = 0
for i in range(1, 11):
sum += i
print(sum)
for... |
input_list = [3, 4, 5, 8, 9, 10]
def q01_chocolates(my_list=input_list):
list2 = []
values = 0
for item in my_list:
if item%2 !=0:
values +=item
list2.append(values)
return list2
|
def search(array, n):
for i in array:
if i == n:
return True
return False
arr = [23,4,89,19,0,700,30]
print("Number 19 found: ", search(arr, 19))
print("Number 20 found: ", search(arr, 20))
|
print("BMI Calculator")
unit = input("Choose the unit of measure: 1 for Metric, 2 for Imperial: ")
while (unit != "1" and unit != "2"):
unit = input("Choose the unit of measure: 1 for Metric, 2 for Imperial: ")
if (unit == "1"):
while True:
weight = input("Enter weight in kg: ")
try:
... |
import math as m
def cos(x, terms):
return sum(((-1)**i) * (x ** (2*i)) / (m.factorial(2*i)) for i in range(terms))
def sin(x, terms):
sini = 0
for i in range(terms):
sign = (-1)**i
sini = sini + ((x**2.0*i+1))/m.factorial(2*i+1)*sign
return sini
print(cos(1.2, 30))
print(sin(1.6, 20)... |
while True:
value = input("Enter a number: ")
try:
x = float(value)
except ValueError:
print("Try entering again...")
else:
break
if x > 100:
print(str(x) + " is over 100.")
else:
print(str(x) + " is less than 100.")
|
import math
def isPrime(n):
if n<2:
print("{} is not prime number.".format(n))
return n
else:
for i in range(2,int(math.sqrt(n))+1):
if n%i==0:
print("{} is not prime number.".format(n))
return i
elif n%1!=0 and i==int... |
def parse_input():
with open("input.txt") as f:
input = f.read().split("\n")
wires = []
for wire in input:
wires.append(wire.split(','))
return wires
def define_lines(wire):
cur_pos = (0,0)
positions = []
positions.append(cur_pos)
for delta_pos in wire:
directi... |
import random
name = input("What is your name?")
print("Game is starting, good luck ", name.capitalize())
words = ['rainbow', 'computer', 'science', 'programming',
'python', 'mathematics', 'player', 'condolence',
'reverse', 'quite', 'software']
word = random.choice(words)
print("Guess the characters... |
#!/usr/bin/env python3
import sys
from a0_learner import A0Learner
from re_parser import REParser
if len(sys.argv) < 2 or '-h' in sys.argv or '--help' in sys.argv:
print("""
A0LREe - Learns Automaton from examples and extracts Regular Expression
The pipeline consists of these stages:
* Const... |
class Heap(object):
"""Heap implementation with a Python list, first element starting on index
1. Values should be stricly non negative integer.
Type defines type of heap: min heap if type == 1 else max heap"""
def __init__(self, heap=None, type=1):
if heap is None:
self.heap = [0]
... |
#sdahal1 : Rob github page
class Human(object):
def __init__(self, name, height, weight):
print "creating a human"
self.name = name
self.height = height
self.weight = weight
self.health = 100
def verbalattack(self, target):
print "aargh"
target.health -=... |
# def num():
# for i in range (1,13):
# a =''
# for j in range(1,13):
# a+= str(i*j)
# print a
# num()
#
def stars(list):
for i in range (len(list)):
print '*' * list[i]
stars ([4,6,1,3,5,7,25])
|
#list_one = [1,2,5,6,2]
#list_two = [1,2,5,6,2]
#list_one = [1,2,5,6,5]
#list_two = [1,2,5,6,5,3]
#list_one = [1,2,5,6,5,16]
#list_two = [1,2,5,6,5]
#list_one = ['celery','carrots','bread','milk']
#list_two = ['celery','carrots','bread','cream']
list_one = ['celery','carrots','bread','milk']
list_two = ['celery',... |
# # Multiples. This code prints all odd numbers from 1 to 1000.
#
# def printOdd():
# for i in range(1,1001,2): #this gives the range of values
# print i
# printOdd()
#
#
# # Part II:
#
# def printMults5to1mil():
# for i in range(5,1000005,5):
# print i
#
# printMults5to1mil()
# Sum List.... |
cont = soma = 0
while True:
usuario = float(input('Digite um valor (999 para parar): '))
if usuario == 999:
break
cont += 1
soma += usuario
print(f'A soma dos valores é {soma}. Foram lidos {cont} números.') |
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
media = (n1+n2)/2
if media < 5.0:
print(f'Sua média foi {media:.1f}. REPROVADO.')
elif 5.0 < media < 6.9:
print(f'Sua média foi {media:.1f}. RECUPERAÇÃO.')
elif media >= 7.0:
print(f'Sua média foi {media:.1f}. APROVAD... |
n1 = float(input('Digite a primeira nota do aluno: '))
n2 = float(input('Digite a segunda nota do aluno: '))
print(f'A média das notas é {(n1+n2)/2}. ')
#n1 = float(input('Primeira nota do aluno: '))
#n2 = float(input('A segunda nota do aluno: '))
#média = (n1+n2)/2
#print(f'A média do aluno é {média}. ') |
'''a = int(input('Digite o primeiro número: '))
b = int(input('Digite o segundo número: '))
c = int(input('Digite o terceiro número: '))
menor = a
if b < a and b < c:
menor = b
if c < a and c < b:
menor = c
maior = a
if b > a and b > c:
maior = b
if c > a and c > b:
maior = c
print(f'O menor valor digi... |
#Solução matemática
'''numero = int(input('Digite um número de 0 a 9999: '))
u = numero // 1 % 10
d = numero // 10 % 10
c = numero // 100 % 10
m = numero // 1000 % 10
print(f'Unidade: {u}')
print(f'Dezena: {d}')
print(f'Centena: {c}')
print(f'Milhar: {m}')'''
#Solução com String
num = str(input('Digite um número de 0... |
nome = input('Qual é o seu nome? ')
# Formatação de texto // ^ = centralizado // < alinhado à esquerda // > alinhado à direita // = == repetir função
print(f'Prazer em te conhecer, \033[1;36m{nome:=^20}\033[m! ')
#sem declaração de variavel para soma
n1 = int(input('Um valor: '))
n2 = int(input('Outro valor: '))
print... |
print('-='*8)
print('TABUADA')
print('-='*8)
usuario = int(input('Digite um número para exibir sua tabuada: '))
for tabuada in range(1, 11):
resultado = usuario * tabuada
print(f'{usuario} x {tabuada:2} = {resultado}')
print('FIM')
'''num = int(input('Digite um número para ver sua tabuada: '))
for c in range(1... |
print('Calculadora de tinta. ')
l = float(input('Digite a largura da parede: '))
h = float(input('Digite a altura da parede: '))
a = l*h
print(f'Sua parede tem a dimensão de {l} x {h} e sua área é de {a:.1f}m². ')
print(f'Você precisará de {a/2:.1f}l de tinta para pintar a parede. ') |
def validate_pin(pin):
if not (len(pin) == 4 or len(pin) == 6):
return False
pinDigits = set(pin)
for a in pinDigits:
if not a.isdigit():
return False
return True
print(validate_pin("a234")) |
import unittest
from mathdojo import MathDojo
class Test_MathDojo(unittest.TestCase):
def setUp(self):
print("Preparando el contexto")
self.md = MathDojo()
self.num1 = 1
self.num2 = 1
self.num3 = 1
self.num4 = 1
def test01(self):
print("Realizando Test ... |
ch=input("enter the chracter")
if((ch>="a" and ch<="z") or (ch>="A" and ch<="Z")):
print("a charecter is an alphabet")
else:
print("not a alphabet")
|
a = 5
if(a>10):
print("a es mayor a 10")
elif(a<0):
print("El numero es negativo")
else:
print("El numero es menor a 10")
|
#Actividad
#Realizar un programa que pida el nombre de 3 personas, a cada persona se le pedira que ingrese su calificacion(5),
#sacar promedio de cada persona, desplegar un mensaje con el nombre de la persona y su promedio
alumnos = []
calificaciones = []
aux = []
promedios = []
for x in range(0,3):
alumnos.appe... |
# Author: Sam Shenoi
# File Description: This file defines a class object that can
# be used to pull gene sequences from Ensembl
# Imports
import requests
import json
import re
import sys
import time
# This class accesses the Ensembl REST servers and returns sequences associated with identifiers
class Ensembl:
... |
from collections import Counter
def isValid(s):
# get frequencies
c=Counter(s)
# case 1 same freq
if len(set(c.values())) == 1:
return("YES")
# case 2 more than 2 freq
elif len(set(c.values())) > 2:
return("NO")
#case 3 unique 2 freq
else:
for key in c:
c[key] -= 1
... |
import tkinter
from tkinter import messagebox
from tkinter import *
def student():
Label(root,text="C/C++程序设计").grid(row=0)
Label(root,text="Python程序设计").grid(row=1)
Label(root,text="Java程序设计").grid(row=2)
entry1=Entry(root)
entry2=Entry(root)
entry3=Entry(root)
entry1.grid(row=0,column=1)
... |
def solution(record):
answer = []
dic = {}
split_record = list()
record_len = len(record) ## 문자열의 갯수
for i in range(0, record_len):
split_record.append(record[i].split(' '))
if split_record[i][0] != "Leave":
dic[split_record[i][1]] = split_record[i][2] ## uid key에 닉네... |
'''
Una panaderia vende barras de pan a 3.49€ cada una. El pan que no es del dia tiene un descuento del 60%
Escribe un programa que comience leyendo el número de barras vendidas que no son del dia.Despues tu progrma debe mostrar el precio habitual
de una barra de pan, el descuento que se le hace por no se fresca y el c... |
from __future__ import annotations # for typing the enclosing class
import abc
import random
from time import sleep
from game import Connect4Game, Connect4Viewer
class Player:
game: Connect4Game
def __init__(self, player_turn_id=None):
self.player_turn_id = player_turn_id
self.last_moves =... |
class toyota:
def __init__(self,model,make,color,price,type):
self.model = model
self.make = make
self.color = color
self.price = price
self.type = type
def description(self):
print("Model of Car : ",self.model)
print("Make of Car : ",self.make)... |
def numbers(x,y):
print("decimal binary octal Hexadecimal")
for i in range(x,y+1):
binary = bin(i)
octal = oct(i)
Hex = hex(i)
print("d:{:5d} b:{:5b} o:{:5o} H:{:5X}".format(i,i,i,i))
numbers(1,10)
|
# -*- coding: utf-8 -*-
"""
印出1~100的質數,並顯示總共有幾個
"""
s=[2]
for i in range(1,101):
if i%2 !=0:
s.append(i)
print(s)
print(len(s))
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
班級:資管4A
學號:104111118
姓名:黃凱裕
日期:2019/7/3
題目:假設一賽跑選手在x分y秒的時間跑完z公里,請撰寫一程式,輸入x、y、z數值,
最後顯示此選手每小時的平均英哩速度(1英哩等於1.6公里)。
提示:輸出浮點數到小數點後第一位。
版本:1.0
說明:
"""
x = eval(input("輸入分:"))
y = eval(input("輸入秒:"))
z = eval(input("輸入公里:"))
time = ( x + y/60 )/60
mile = ( z / 1.6) /... |
# -*- coding: utf-8 -*-
"""
班級:資管4A
學號:104111118
姓名:黃凱裕
日期:2019/07/08
題目:撰寫一個程式,1-100之間產生一個亂數,使用者輸入數字,猜對顯示猜的次數並結束,
否則提示大小。
版本:1.0
說明:使用while
"""
import random
ans = random.randint(1,100) #取從1到10的亂數
times = 0
print('請猜一個1~100的數字,輸入超過100結束遊戲')
play = True
while(play):
guess = int(input('猜一個數字:')) #i... |
import pandas as pd
weather = pd.read_csv('/Users/apple/desktop/pandasFoundation/dataset/weather_data_austin_2010.csv', index_col='Date', parse_dates=True)
# NOTE: parse_dates will return the date format
print(weather.head())
# partial string index
# only print the 'Temperature' column in august
august = weather.loc... |
# hist: histogram
# PDF: probability Density Functions
# CDF: cumulative Density Functions
import pandas as pd
import matplotlib.pyplot as plt
tips = pd.read_csv('/Users/apple/desktop/pandasFoundation/dataset/tips.csv')
# print(tips.head())
# print(tips.info())
#format the plot that they appear on separate rows
fig,... |
#Faça um programa para calcular e exibir a quantidade de parcelas sem juros
#e o valor de cada parcela, conforme o valor da compra digitado pelo usuário
valor = float(input("Entre com o valor da compra: "))
if valor <= 100:
parcela = 2
valorParcela = valor/2
print(f'A quantidade de parcelas é {parce... |
#Faça um programa para calcular e exibir a porcentagem
#de comissão de vendas de um vendedor, conforme o volume
#mensal de vendas do mesmo digitado pelo usuário
vendas = float(input("Digite o valor de vendas: "))
if vendas <= 5000:
comissao = vendas * 0.02
print(f'O valor da sua comisão é de {comissao}.'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.