text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/01/08
# @Author : yuetao
# @Site :
# @File : LeetCode990_等式方程的可满足性.py
# @Desc : 查并集,一般公司不会考察
"""
https://zhuanlan.zhihu.com/p/93647900
https://leetcode-cn.com/problems/satisfiability-of-equality-equations/solution/shi-yong-bing-cha-ji-chu-li-bu-... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/30
# @Author : yuetao
# @Site :
# @File : 合并两个排序的链表.py
# @Desc :
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/30 0030 11:40
# @Author : Letao
# @Site :
# @File : LeetCode5000.py
# @Software: PyCharm
# @desc :
"""
设 f[i] 是以 nums[i] 结尾,乘积为正的最长子数组的长度。
设 g[i] 是以 nums[i] 结尾,乘积为负的最长子数组的长度。
"""
class Solution(object):
def getMaxLen(self, nums):
... |
def changeChar(string,ch1,ch2,begin=0,end=-1):
if(end ==-1):
end=len(string)
i,newstring=0,""
while(i<len(string)):
if(string[i]==ch1 and i>=begin and i<=end ):
newstring = newstring+ ch2
else:
newstring = newstring + string[i]
i+=1
return newstring
phrase = 'Python is really magic'... |
from turtle import *
def triangle(tsize,tcolor,tangle):
color(tcolor)
i=0
while (i<3):
forward(tsize)
right(120)
i+=1
def stars5(scolor,ssize):
i=0
angle=72
while (i<5):
forward(ssize)
right(144)
i += 1
|
#Associate the month with the corresponding number of day
t1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
t2 = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin','Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre']
t3 = []
i=0
while i <12:
t3.append(t2[i])
t3.append(t1[i])
print(t2[i]... |
def MonthName(n):
"Function to find a month name"
mname=['January','February','March','April','May','June','July','August','September','October','November','December']
z=mname[n-1]
return z
#Usage
print(MonthName(1))
|
#This program count the number of char in a name
name = [ 'Jean-Michel' , 'Marc' , 'Vanessa' , 'Anne' , 'Maximilien ' , 'Alexandre-Benoît' , 'Louise' ]
i = 0
while i < len(name):
charcount=len(name[i])
print(name[i],' : ',charcount)
i += 1
|
# Add numbers between 'a' and 'b' which are multiple of 3 or 5
a,b = 0,32
i = a
z = 0
while i<=b:
#check if number is multiple of 3 or 5
if not(i%3) or not(i%5):
z = z + i
else:
print("ignoring",i)
i = i + 1
print("Result is",z)
|
#!/usr/bin/python
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the ... |
"""Rafaela tem uma loja de antiguidade e decidiu avaliar quanto vale o seu estoque de 1500
peças. Escreva um programa que receba como entrada a descrição, o valor e o ano de cada item presente na loja"""
#A quantidade de items produzidos antes de 1827
#o valor médio dos intens
# a descrição e o ano do objeto mais vali... |
import gpioRap as gpioRap
import RPi.GPIO as GPIO
#Create GpioRap class using BCM pin numbers
gpioRapper = gpioRap.GpioRap(GPIO.BCM)
#Create an LED, which should be attached to pin 17
led = gpioRapper.createLED(17)
#Create a button, which should be monitored by pin 4, where a False is read when the button is pressed
... |
from Board import Board
from GameTree import AI
import sys
import time
import random
from Input import Input
WHITE = True
BLACK = False
#player gets to choose which side to play
#default player is black
def chooseSide():
playerChoiceInput = input(
"Would you like to be white(w) or Black(B)? ").lower()
... |
def getFormattedInput(filename):
return [[isTree == "#" for isTree in x] for x in open(filename, "r").read().split("\n")]
def solve3a(inputMatrix, slope):
i, j = [0, 0]
numTrees = 0
while i <= len(inputMatrix) - 1:
if inputMatrix[i][j]:
numTrees += 1
j = (j + slope[0]) % l... |
#iterācija - kādas darbības atkārtota izpildīšana (iterable)
mainigais = [1, 2, 3] #list
for elements in mainigais:
print(elements)
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
for x in myList:
print(x)
for _ in myList: #var nerakstīt cikla mainīgo
print("Sveiki")
#atrast pāra skaitļus
for skaitlis... |
#Nosacījums: Aprēķini ievadīto naturālo skaitļu faktoriālo summu.
n = int(input("Ievadi naturālu skaitli: "))
while True:
if n<1:
n = (input("Ievadi naturālu skaitli: "))
else:
break
faktorials = 1
summa = 0
for i in range(n):
faktorials = faktorials*(i+1)
summa = summa + faktorials
... |
#pirmais uzdevums
a = 15
b = 2.5
c = 4.78
#lielākais skaitlis
if (a > b) and (a > c):
print("15 ir lielākais skaitlis")
elif(b > a) and (b > c):
print ("2.5 ir lielākais skaitlis")
else:
print("4.78 ir lielākais skaitlis")
#mazākais skaitlis
if (a < b) and (a < c):
print("15 ir mazākais skaitlis")
elif... |
from matplotlib import pyplot as plt
import numpy as np
x=np.arange(1,11)
y=x//2
plt.plot(x,y)
plt.xlabel("X-axis")
plt.ylabel("y-axis")
plt.title("y=x/2 graph")
plt.show() |
def cocktail(a):
for i in range(len(a)//2):
swap = False
for j in range(1+i, len(a)-i):
# test whether the two elements are in the wrong order
if a[j] < a[j-1]:
# let the two elements change places
a[j], a[j-1] = a[j-1], a[j]
sw... |
# Check internet connection
import urllib.request as urllib2
def check_network():
try:
urllib2.urlopen("http://google.com", timeout=2)
return True
except urllib2.URLError:
return False
print( 'connected' if check_network() else 'no internet!' ) |
# coding=utf-8
"""
Program Name: Battleship
Author: blackk100
License: MIT License
Description: A Python3 based, CLI implementation of the board game, Battleship.
Current Version: Alpha
"""
# Imports
import os
from time import sleep
from random import randint as rand
# Generic Functions
def cls():
"""Clears the t... |
import time
import sys
print("Приветствую вас в своем калькуляторе!\nЗдесь вы сможете сложить/вычесть/умножить/разделить два числа.")
a = (input("Введите первое число и нажмите ENTER.\n"))
try:
a = float(a)
except (ValueError) as a:
print("до связи.")
time.sleep(1.5)
sys.exit()
b = (input("Введите второ... |
# Decorators
# All Decorators are clousures
# demo is decorators function
# sayhi is decorated function
def demo(a):
def inner(b):
def innermost():
print("This is innermost -> ", a, b)
return innermost
return inner
@demo("Testing it")
def sayhi():
print("Hi from sayhi!")
say... |
class Animal():
def __init__(self):
print("Animal Created!")
def who_am_i(self):
print("I am an Animal!")
class Dog(Animal):
def __init__(self, breed):
Animal.__init__(self)
print("Dog of {}".format(breed))
self.breed=breed
def bark(self):
print("Wo... |
mdarray=[[3,8],[1,2],[2,1],[1,3],[3,6],[2,4]]
print(mdarray)
for i in range(len(mdarray)-1,0,-1):
for j in range(i):
if mdarray[j][1] > mdarray[j+1][1]:
temp=mdarray[j+1]
mdarray[j+1]=mdarray[j]
mdarray[j]=temp
print(mdarray)
|
def main():
A = ['a','d','c','b']
_quicksort(A, 0, len(A)-1)
print(A)
def partition(xs, start, end):
follower = leader = start
while leader < end:
if xs[leader] <= xs[end]:
xs[follower], xs[leader] = xs[leader], xs[follower]
follower += 1
leader += 1
xs[... |
def main():
arr=[3,6,7,4,2,1,8,9,5]
print("Array Before Sorting :",arr)
bubblesort(arr)
print("Array After Sorting :", arr)
def bubblesort(args):
for i in range(len(args)-1,0,-1):
print(i)
for j in range(i):
if args[j]<args[j+1]:
temp=args[j]
... |
# URL :- https://www.hackerearth.com/practice/math/number-theory/basic-number-theory-2/practice-problems/algorithm/sum-of-primes-7/
import math
def prime_or_not(num):
pr=True
if num == 1:
return False
if num == 2:
return True
if num % 2 == 0:
pr = False
else:
for k ... |
def switchCase(ltr):
if ltr.islower():
return ltr.upper()
elif ltr.isupper():
return ltr.lower()
else :
return ltr
mystring="This is 2 PyThOnIc.."
cstr=str().join([switchCase(x) for x in mystring])
print(cstr) |
words = [ 'word1', 'word2', 'foo']
daSearch = open("foo.txt", "r").read()
for word in words:
if word in daSearch:
print(word)
else:
print("not found")
print("\nDone")
|
user=str(input("enter the string"))
string=input("enter string to be counted")
upper=string.upper()
lower=string.lower()
big=(user.count(upper))
small=(user.count(lower))
Total=big+small
print(Total)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 08:31:46 2019
@author: Michael ODonnell
"""
# Question:
# write a method to replace all spaces in a string with '%20'
# You may assume that the string has sufficient space at the end to
# hold the addition characters, and that you are given the "true"
# length of the ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 08:33:26 2019
@author: Michael ODonnell
"""
# Question:
# Given a string, write a function to check if it is a permutation of a palindrome.
# A palindrome is a word or phrase that is the same forwards and backwards.
# A permutation is a rearrangement of the letters. T... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 24 22:48:26 2019
@author: Michael ODonnell
"""
# Question
# You are given two sorted arrays, A and B.
# Write a method to merge B into A in sorted order.
A = []
B = []
import random
for x in range(10):
A.append(random.randint(1,100))
B.append(random.randint(1,10... |
# Adam Shaat
# Check if one number divides another.
p = 8
m = 2
if (p % m) == 0:
print(p, "divided by", m, "leaves the remainder of zero.")
print("I'll be run too if the condition is true.")
else:
print(p, "divided by", m, "does not leave the remainder of zero.")
print("I'll be run too if the conditio... |
# Adam Shaat
# a function to sqaure numbers
import math
def power(x, y):
ans = x
y = y - 1
while y > 0:
ans = ans * x
y = y - 1
return ans
def f(x):
ans = (100 * power(x, 2) + 10 * power(x, 3)) // 100
ans = ans - (power(x, 3) // 10)
return ans
def isprime(i):
# loop through all values f... |
"""
"""
# Should do earlier itself
def investigate(data)->None:
print(data.shape)
print(data.info())
print(data.describe())
def drop_nan_columns(data, ratio=1.0)->pd.DataFrame:
"""
From an initial look at the data it seems like some columns are entirely nan columns (e.g. id, there are... |
# File: integrate_parsed_data.py
# Purpose: to combine the county level data produced by the other two python scripts, adn potentially do some analysis
# Date: 2/23/2021
import pandas
import itertools
# Calculate the pearson correlation coefficient, and draw a graph if the coefficient value is less than -0.5 or great... |
arr = input()
arr = arr.split()
sums = 0
set = []
x = 0
set.append(sums)
for i in range(len(arr)):
sums = sums + int(arr[i])
if (sums in set):
x = 1
break
else:
set.append(sums)
if (x == 1):
print('exists')
else:
print('not exists')
'''
Explaination:
We create a set which st... |
"""
Hello,
I'm a Python program for suggesting words based on Project Gutenberg books.
Before you start using me please do:
$ python3 -m nltk.downloader punkt
To use me type:
$ python3 whats_next.py --book-id <book id> --query <your query>
For example:
$ python3 whats_next.py --book-id 46 --query god bless
I seem ... |
# Joan Quintana Compte-joanillo. Assignatura CNED (UPC-EEBE)
'''
ZF-52: xln(x)-1, trobar el 0 pel mètode de la bisecció
https://www.math.ubc.ca/~pwalls/math-python/roots-optimization/bisection/
cd /home/joan/UPC_2021/CNED/apunts/python/T1/
PS1="$ "
python3 biseccio1.py
'''
import matplotlib
import matplotlib.pyplot a... |
import codecs
import json
import re
# import matplotlib.pyplot as plt
import pylab as plt
import numpy as np
class TextAnalyses:
"""
Use this once the text tokens have been extracted; e.g. on the readability_tokens.json file. The most
important thing we need to do is document frequency generation
"""
... |
import math
def logcount(arr, a, b):
# Check base case
if len(arr) == 0:
return 0
middle = math.floor(len(arr)/2)
if arr[middle] > b:
# print('greater' + str(arr))
return logcount(arr[:middle], a, b)
elif arr[middle] < a:
# print('less' + str(arr))
retur... |
import collections
import itertools
import operator
operators = {
"<": operator.lt,
"<=": operator.le,
"==": operator.eq,
"is": operator.eq, # Note: not pure python `is`!
"iis": lambda x, y: x.lower() == y.lower(),
"!=": operator.ne,
"<>": operator.ne,
"not": operator.ne,
"inot": l... |
from collections import Counter
occurrences = Counter(input().strip())
sorted_occurrences = sorted(occurrences.items(), key=lambda x: (-x[1], x[0]))
print(sep='\n', *['{} {}'.format(symbol, count) for symbol, count in sorted_occurrences[:3]])
|
import sys
def sub_strings_count(string, sub_string):
sub_strings_count = 0
string_length = len(string)
sub_string_length = len(sub_string)
for i in range(0, string_length):
if i + sub_string_length > string_length:
break
all_matched = True
for sub_i in range(0, sub... |
import re
N = int(input())
emails = (input().strip() for _ in range(0, N))
valid_email = re.compile(r'''
# It must have the username@websitename.extension format type.
# The username can only contain letters, digits, dashes and underscores.
# The website name can only have letters and digits.
# The maximum length of t... |
def sub_string_count(string, predicate):
sub_string_count = 0
string_len = len(string)
for i in range(0, string_len):
if predicate(string[i]):
sub_string_count += string_len - i
return sub_string_count
def is_vowel(letter):
return letter in 'AEIOU'
def is_consonant(letter):
... |
def multiplication_table(x = 1):
x = int(x)
for i in range(1,11,1):
print(x,"X",i,'=',x*i)
y = input("Write an Integer and Press Enter")
multiplication_table(y)
multiplication_table() |
saarc = ["Afganistan", "Bangladesh", "Bhutan", "Nepal", "India", "Pakistan", "Sri Lanka"]
country = input("Type a Country name and press Enter ")
if country in saarc:
print(country, "is in Saarc!")
else:
print(country, "is not in Saarc!")
print(type(country))
print("Program Terminated!") |
import turtle
height = 5
width = 5
turtle.speed(2)
turtle.penup()
for y in range(height):
for x in range(width):
turtle.dot()
turtle.forward(20)
turtle.backward(20*width)
turtle.right(90)
turtle.forward(20)
turtle.left(90)
turtle.exitonclick()
|
"""
Functions for handling pareto fronts
"""
import itertools
import collections
def dominates(a, b):
return (a[1] > b[1] or a[2] > b[2]) and a[1] >= b[1] and a[2] >= b[2]
def not_dominates(a, b):
return a[1] <= b[1] or a[2] <= b[2]
def generate_zipped_from_fronts(fronts):
"""
N... |
from collections import deque
class queue:
def __init__(self):
super().__init__()
self.queue = deque()
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
if len(self.queue) == 0:
return None
else:
return self.queue.popleft(... |
def sortboxes(boxes):
for i in range(len(boxes)):
mid = sum(boxes[i]) - min(boxes[i]) - max(boxes[i])
low = min(boxes[i])
high = max(boxes[i])
boxes[i][0] = low
boxes[i][1] = mid
boxes[i][2] = high
# Input: box_list is a list of boxes that have already been s... |
def greedy (grid):
summ=grid[0][0]
leng=len(grid)
i=1
j=0
while i<leng:
if grid[i][j]>=grid[i][j+1]:
summ+=grid[i][j]
else:
j+=1
summ+=grid[i][j]
i+=1
return summ
def main(grid):
return greedy(grid) |
# Schoenfinkeling decorator
def schoenfinkeled(fun):
def new_fun(args):
try:
return fun(args)
except TypeError:
# Returns a function with n-1 arguments
aux = lambda *myArgs: fun(args, *myArgs)
# Recursively applies schoenfinkeling
retur... |
# Generator function which acts as an iterator over ngrams of a string.
def ngrams (size, s):
a, b = 0, size
i = 0
while i <= (len(s)-size):
yield s[a:b]
a += 1
b += 1
i += 1
s = "the quick red fox jumps over the lazy brown dog"
for x in ngrams(3, s.split()):
print (x) |
import turtle as t
import random
score = 0
playing = False
counter = 0
shadow = False
booster = 1
def create_turtle(name, color,x,y,role):
global test
if role == 0:
name.shape("turtle")
else:
name.shape("circle")
name.color(color)
name.speed(0)
name.up()
name.goto(x,y)
ta = t.Turtle()
create_turtle(ta,"re... |
def bubble(x, ascending=True):
if len(x) == 0: # X의 요소가 없는 경우 함수 실행 안함
return False
try:
x = list(x) # X를 리스트로 변환할 수 없는 경우 함수 실행 안함
except:
return False
if ascending: # ascending 인자의 값이 True인 경우 오름차순 정렬
for i in range(0, len(x)-1):
for j in range(0, len(x)... |
import bubble
import insertion
import merge_sort
import quick
import selection
def unsorted():
import random
before = random.sample(range(1, 1000000), 10000)
return before
if __name__ == '__main__':
import time
before = unsorted()
print(before)
# bubble
start_b = time.time()
... |
## ahmed saad saleh
import random
import time
############################# INSERTION SORT RANDOM ############################
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist... |
x = object()
y = object()
x_list = [x] * 5
y_list = [y] * 2
big_list = x_list + y_list
print ("x_list contains %d objects" % len(x_list))
print ("y_list contains %d objects" % len(y_list))
print ("big_list contains %d objects" % len(big_list))
if x_list.count(x) <= 8 and y_list.count(y) <= 6:
print (... |
# making a list of lists to form a matrix
lst_1= [1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]
matrix =[lst_1,lst_2,lst_3]
print (matrix[0])
# sort for lists
new_list = ['a','e','x','b','c']
# reverse list
new_list.reverse()
print (new_list)
# sort list
new_list.sort()
print (new_list)
# list comprehesions
# matrix2 = [[1,2,3... |
if __name__ == '__main__' :
N = int(input())
L = []
for i in range(0, N) :
Str = input()
tempStr = Str.strip().split(" ")
cond = tempStr[0]
if (cond == "print") :
print(L)
elif (cond == "sort") :
L.sort()
elif (cond == "pop") :
... |
#-*- coding:utf-8 -*-
#Python 输入框写法
hieght = input('请输入你的身高:')
print("你的身高是%s"%hieght)
print('=====================\n')
#Python 输入框写法
age = 21 #定义年龄21岁
print("我的年龄是:%d"%age)
|
#-*- coding=utf-8 -*-
import os
str_name = input('请你输入要处理的字符串名称:')
folder_name = input('请你输入要处理的目录:')
# 获取某个目录下的所有文件名称
old_file_names = os.listdir(folder_name)
for name in old_file_names:
print(name.rfind(str_name))
# if name.find(str_name):
|
val1, val2, upper, lower = 0, 0, 100, 0
while True:
print(upper, lower)
val1 = raw_input("Upper: ")
val2 = raw_input("Lower: ")
if float(val1) == 0:
break
if float(val1) < float(upper):
upper = val1
if float(val2) > float(lower):
lower = val2
|
supplies = ['pens', 'staplers', 'flamethrowers', 'binders']
for index, item in enumerate(supplies):
print(f'Index {index} in supplies is: {item}') |
import random
pets = ['dog', 'cat', 'squid', 'spider', 'hamster', 'human', 'zombie']
for i in range(2):
print(random.choice(pets))
pets = ['dog', 'cat', 'squid', 'spider', 'hamster', 'human']
random.shuffle(pets)
print(pets) |
import pandas as pd
X = pd.read_csv("data_2d.csv", header=None)
print(type(X))
print(X.info())
print(X.head()) #default is set to 5 rows
try:
print(X[0,0])
except:
pass
M = X.values # no longer as_matrix
print(type(M))
print(X[0])
# pandas X[0] -> column with name 0
# numpy X[0] -> 0th row
print(typ... |
""" quiz.py
example of a quiz game
using objects for data
"""
from tkinter import *
# from tkMessageBox import *
class Problem(object):
def __init__(self, qtype="", question="", a="", b=""):
object.__init__(self)
self.qtype = qtype
self.question = question
self.a = a
... |
"""
This is a data structure to define a game map
At start we will use only one map, but later we wil add more maps
"""
"""
Default Map
The symbol # is a door.
0 1 2 3
+-----+-----+-----+-----+
0 | A |
| |
+--#--+--#--------+--#--+
1 | ... |
import pandas as pd
from collections import defaultdict
#load into data frame
df = pd.read_csv("data/mobile_price.csv", sep=',')
# check if any null or missing values in entire CSV file
if df.isnull().values.any():
print('Data has missing values')
else:
# file has no null values thus set default data type as... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv("ex1data1.csv")
data.plot.scatter('population','profit')
X = data['population']
y = data['profit']
theta = np.zeros(2)
alpha = 0.01
num_iters = 1500
def predict(X, theta):
retur... |
def binarySearch(arr, key):
l = 0
h = len(arr)-1
while(l<=h):
mid = (l+h)//2
if arr[mid]==key:
return mid + 1
elif arr[mid]>key:
h = mid - 1
else:
l = mid+1
return 0
arr = [3,6,8,12,14,17,25,29,31,36,42,47,53,55,6]
key = 3
print(binar... |
import math
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
@staticmethod
def from_tuple(t):
return Point(t[0], t[1])
def copy(self):
return Point(self.x, self.y)
def clone(self):
return self.copy()
def as_int_tuple(self)... |
import math
def is_powed(a, b, c):
p = (a+b+c) / 2
return math.sqrt(p*(p-a)*(p-b)*(p-c))
a = float(input())
b = float(input())
c = float(input())
S = is_powed(a, b, c)
print(S) |
# min
#
# The tool min returns the minimum value along a given axis.
#
# import numpy
#
# my_array = numpy.array([[2, 5],
# [3, 7],
# [1, 3],
# [4, 0]])
#
# print numpy.min(my_array, axis = 0) #Output : [1 0]
# print numpy.min(my_array, axi... |
# identity
#
# The identity tool returns an identity array. An identity array is a square matrix with all the main diagonal elements as and the rest as . The default type of elements is float.
#
# import numpy
# print (numpy.identity(3)) #3 is for dimension 3 X 3
#
# #Output
# [[ 1. 0. 0.]
# [ 0. 1. 0.]
# [ 0. ... |
def removeDuplicado(grafo, inicio, vizinho): # remove arestas duplicadas
while grafo[inicio].count((vizinho, 1)) > 1:
grafo[inicio].remove((vizinho, 1))
while (inicio, 1) in grafo[vizinho]:
grafo[vizinho].remove((inicio, 1))
return grafo
def criaGrafo(quant_v): # cria um grafo (florest... |
# Fibonacci
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
#Lucas
def lucas(n):
if n == 0:
return 2
elif n == 1:
return 1
else:
return lucas(n - 1) + lucas(n - 2)
#Sum Series
d... |
import tkinter as tk
import sqlite3
"""Payment management system
Written by Hawkins647"""
root = tk.Tk()
root.title("Payment Management System")
root.geometry("600x600")
root.resizable(0, 0)
inbound_db = sqlite3.connect("inbound.sqlite")
outbound_db = sqlite3.connect("outbound.sqlite")
def delete_entry_inboun... |
while True:
p=raw_input("ingresa la operacion\n")
a=p.lower()
if a=="":
break
a+=";"
estado="q0"
for entrada in a:
if entrada=="a" or entrada=="b" or entrada=="c" or entrada=="d" or entrada=="e" or entrada=="f" or entrada=="g" or entrada=="h" or entrada=="i" or entrada=... |
x = int(input())
y = int(input())
ans = 0
if x>0 and y>0:
ans = 1
elif x>0 and y<0:
ans = 4
elif x<0 and y>0:
ans = 2
elif x<0 and y<0:
ans = 3
print(ans) |
N = int(input())
arr = []
for i in range(0,N):
arr.append(input())
arr = list(set(arr))
arr = sorted(arr)
arr.sort(key=len)
for i in range(len(arr)):
print(arr[i]) |
#!/usr/bin/env python
# Presenting menu of options
print ("What would you like to do? ")
# User selects option from menu
option = input("(1) Translate a protein-coding nucleotide sequence to amino acids OR (2) Randomly draw a codon from the sequence? ")
# If user selects option 1.
if option == "1":
dnaSeq = input("... |
# -*- coding: utf-8 -*-
A, DA, B, DB = input().split()
result_a = A.count(DA) * DA
result_b = B.count(DB) * DB
print(int(result_a and result_a or 0) + int(result_b and result_b or 0))
|
# -*- coding=utf-8 -*-
n = int(input()) # 接收参数
step_number = 0
while n != 1: # 直到n=1返回步数
if n % 2 == 0: # 判断奇偶
n /= 2
else:
n = (3 * n + 1) / 2
step_number += 1 # 步数+1
print(step_number)
|
x = input("Number : ")
list_of_digits = [i for i in x]
list_1 = []
sum1 = 0
for i in range(len(x) - 2, -1, -2):
a = str(2 * (int(list_of_digits[i])))
list_1.append(a)
for j in range(len(a)):
sum1 += int(a[j])
sum2 = sum1
for i in range(len(x) - 1, -1, -2):
sum2 += int(list_of_digits[i])
if (sum2... |
"""Faça um Programa que peça as 4 notas bimestrais e mostre a média."""
nota1 = float(input("Digite a primeira nota do aluno --> "))
nota2 = float(input("Digite a segunda nota do aluno --> "))
nota3 = float(input("Digite a terceira nota do aluno --> "))
media = (nota1 + nota2 + nota3) / 3
print(f"A media do aluno é ... |
number = int(input('Enter a 4 digits number: '))
number = number // 10
second_digit = number % 10
print('The second number from the right is: ' + str(second_digit))
|
# insert a number (float / integer) and print the closest even integer
number = float(input('Enter a number: '))
closest_integer = number // 1
if closest_integer % 2 == 0:
closest_even_integer = closest_integer + 2
else:
closest_even_integer = closest_integer + 1
closest_even_integer = int(closest_even_integer... |
#07 - Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha separados
# os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente.
#Resposta
numeros = [[], []]
for i in range(0,7):
num = int(input("Digite um número int... |
def sortRGB( arr):
lo = 0
hi = len(arr) - 1
mid = 1
while mid <= hi:
if arr[mid] == 'R':
arr[lo],arr[mid] = arr[mid],arr[lo]
lo = lo + 1
mid = mid + 1
elif arr[mid] == 'G':
mid = mid + 1
else:
arr[mid],arr[hi... |
# Пользователь вводит строку из нескольких слов, разделённых пробелами.
# Вывести каждое слово с новой строки. Строки необходимо пронумеровать.
# Если в слово длинное, выводить только первые 10 букв в слове.
# insert = str(input('Веедите несколько слов:'))
# num = 0
# for i in insert.split(" "):
# num += 1
# pr... |
# 3. Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц
# (зима, весна, лето, осень). Напишите решения через list и через dict.
dict_data = {
1: 'зима', 2: 'зима',
3: 'весна', 4: 'весна',
5: 'весна', 6: 'лето',
7: 'лето', 8: 'лето',
9: 'осень', ... |
# Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.
# Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369.
n = 10
while n > 9:
n = int(input('введите цифру:'))
print(n)
n_2 = n*10 + n
n_3 = n * 100 + n_2
print(f'{n} + {n_2} + {n_3} = {n + n_2+n_3}') |
#!/usr/bin/python3.4
import sys
import argparse
import json
from datetime import datetime
#this class is the primary object for holding information
#class Birthday(object):
# def __init__(self, name='', date='', comment=''):
# self.name = name
# self.date = date
# self.comment = comment
#def listBdays(all):
def... |
friends = {'chuck': 23, 'fred': 25, 'eugene': 23}
for name, age in friends.items():
print(name, age) |
from art import logo
print(logo)
alphabet = ['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']
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n").lower()
#TODO-2: Inside the 'encrypt' function, shift each letter o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.