text stringlengths 37 1.41M |
|---|
#Max.py
a=int(input('第一个数:'))
b=int(input('第二个数:'))
c=int(input('第三个数:'))
if a>b and a>c:
max=a
elif b>a and b>c:
max=b
else:
max=c
print(max)
|
def calculation():
while True:
count = 0
score = 0
while count < 2:
number = float(input())
if 0 <= number and number <= 10:
count += 1
score += number
else:
print("nota invalida")
print("media = {0:.2f}".format(score/2))
break
if __name__ == "__main__":
calculation()
x = 3
while (x !... |
number = 0
count = 0
while count < 2:
n = float(input())
if n >= 0 and n <= 10:
number += n
count += 1
else:
print("nota invalida")
result = number / 2
print("media = {0:.2f}".format(result))
|
values = str(input(""))
number = values.split(" ")
A = int(number[0])
B = int(number[1])
C = int(number[2])
D = int(number[3])
if B > C and D > A and (C+D) > (A+B) and C > 0 and D > 0 and A % 2 == 0:
print("Valores aceitos");
else:
print("Valores nao aceitos");
|
import math
pi = 3.14159
R = float(input())
formula = (4/3.0)*pi*R**3
print('VOLUME = %.3f' %formula)
|
n = int(input())
number = []
for i in range(0, n):
num = int(input())
number.append(num)
for i in range(0, n):
if number[i] == 0:
print("NULL")
elif number[i] % 2 == 0:
if number[i] > 0:
print("EVEN POSITIVE")
else:
print("EVEN NEGATIVE")
elif number[i] % 2 == 1:
if number[i] > 0:
print("ODD P... |
numbers_list = []
count = 0
for i in range(0,6):
number = float(input())
numbers_list.append(number)
if number > 0:
count +=1
print("%d valores positivos" %count)
|
# import dependencies
import csv
import os
# declaring file location
budget_csv_path = os.path.join("Resources /budget_data.csv")
with open(budget_csv_path) as csvfile:
csv_reader = csv.reader(csvfile, delimiter=",")
csv_header = next(csv_reader)
print(f"CSV Header: {csv_header}")
# Lists to iterate... |
'''
stack-validation-example.py - a program by Nate Weeks to check for
properly closing parenthesis - February 2019
>>> parChecker('{{([][])}()}')
True
>>> parChecker('[{()]')
False
>>> parChecker('[({})]}')
False
>>> parChecker('[(]')
False
>>> parChecker('[(])')
False
'''
from LinkedStack import LinkedStack
def pa... |
def are_anagrams(s1, s2, s3):
# definiuję funkcję tworzącą słownik znaków i ich powtórzeń występujących w łańcuchu
def dict_of_characters(x):
dict = {}
for i in x:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
return dict
# spraw... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def get_percentage(a, b):
"""This function is used to calcuate percentage. Given two data, the function will return the percentage of a and b
:param a: Denominator to calcuate the percentage
b: Numerator to calcuate the percentag... |
#!/usr/bin/env python3
from collections import deque
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
result = []
queue = deque()
... |
#!/usr/bin/env python3
class Solution:
def removeOuterParentheses(self, S: str) -> str:
result = ''
count = 0
for s in S:
count += 1 if s == '(' else -1
if s == '(' and count > 1 or s == ')' and count > 0:
result += s
return result
|
#!/usr/bin/env python3
from collections import Counter
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
counter = Counter(arr)
occurs = [counter[k] for k in counter]
return len(occurs) == len(set(occurs))
|
#!/usr/bin/env python3
class Solution:
def reverseOnlyLetters(self, S: str) -> str:
S, i, j = list(S), 0, len(S) - 1
while True:
while i < len(S) and not S[i].isalpha():
i += 1
while j >= 0 and not S[j].isalpha():
j -= 1
if i >= j... |
""" https://docs.opencv.org/master/d6/d6e/group__imgproc__draw.html#ga07d2f74cadcf8e305e810ce8eed13bc9
void cv::rectangle ( InputOutputArray img,
Point pt1,
Point pt2,
const Scalar & color,
int thickness = 1,
int lineType = LINE_8,
int shift = 0
)
Python:
img = cv.rectangle( img, pt1,... |
class BellmanFord(object):
def calculateShortestPath(self, graph, start):
dist = [float("inf") for x in range(graph.V)]
dist[start]=0.0
#calculate shortest paths from start vertex to all other vertices
self.calc(graph, dist, False)
#rerun algorithm to find vertice... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 14 22:10:52 2019
@author: jigyasa
"""
'''Syntax of if statement:
if expression:
statement(s)
-----------------------------
Syntax of if-else
if exp:
statement(s)
else:
statement(s)
------------------------... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = np.array([1,2,3,4,5,6,7])
y = x*2+5
plt.bar(x,y)
plt.title("bar plot")
plt.xlabel("x cubugu")
plt.ylabel("y cubugu")
plt.show() |
import Draw
import random
#Set the Canvas
canvasSize = 1000
Draw.setCanvasSize(canvasSize, canvasSize)
#Global variables representing the starting point of the frog
startingPointX = canvasSize//2
startingPointY = canvasSize - 300
#Functions to Draw the board
def drawWater():
WATER = Draw.color(100, 130, 250) #W... |
'''
Harshad Number.
If a number is divisible by the sum of its digits, then it will be known as
a Harshad Number.
For example:
The number 156 is divisible by the sum (12) of its digits (1, 5, 6 ).
some of harshad numbers:-->10,12,18,20,120,140,152,156,198,200
'''
num=int(input())
sum_of_digits=0
temp=num
w... |
#! /usr/bin/env python
"""
wallpaper - finds a random picture and sets it as wallpaper
you need another program (this uses bsetbg) for actually
setting the wallpaper
In a unix/linux/bsd system, you can schedule this to run regularly
using crontab. For example, I run this every hour. So I go
to a she... |
import matplotlib.pyplot as plt
def f(i):
if i % 2 == 0:
return int(i / 2)
else:
return 3 * i + 1
# начальные значения -- числа [3..31]
xs = list(range(3, 32))
n = len(xs)
# сгенерируем случайные цвета
# Lehmer RNG, 97 - простое,
# число 40 пораждает полную последовательность
randoms = []
s =... |
while True:
print("Current Room Temperature: " + input.temperature(TemperatureUnit.FAHRENHEIT) + "°F" + " - " + input.temperature(TemperatureUnit.CELSIUS) + "°C")
if input.temperature(TemperatureUnit.FAHRENHEIT) >= 130:
light.set_all(light.rgb(255,0,0))
elif input.temperature(TemperatureUnit.FAHRENH... |
jumsu = int(input())
score = ""
if jumsu >= 90:
score = "A"
elif jumsu >= 80:
score = "B"
elif jumsu >= 70:
score = "C"
elif jumsu >= 60:
score = "D"
else:
score = "F"
print(score) |
'''
Exercicio:
Criar um formulário que pergunte o nome, cpf, endereço, idade, altura e telefone
e imprima em um relatório organizado.
'''
nome = input("Digite seu nome: ")
cpf = input("digite seu CPF: ")
endereco = input("Digite seu endereço: ")
idade = input("Digite sua idade: ")
altura = input("Digite sua altura: "... |
import queue
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class rightSideView:
def solution(self, root: TreeNode) -> List[int]:
if root == None:
return []
res = []
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class middleNode:
def solution(self, head):
p1 = head
p2 = head
p2Forward = True
while p1:
p1 = p1.next
p2Forward = not p2Forward
if p2Forward:
... |
class reverseWords:
def solution(self, s: str) -> str:
word = s.split()
str1 = " ".join(word[::-1])
return str1 |
#!/usr/bin/python
import os
import sys
def mean(a):
return sum(a)/len(a)
if __name__ == '__main__':
one = []
two = []
four = []
six = []
eight = []
ten = []
thou = []
tthou = []
for x in sys.argv[1:]:
print x
with open(x,"r") as f:
for line in f:
if '#' in line:
continue
sline = line.s... |
# n=12
# name = 'Rinshu'
# print(f"Name is {name.upper()} and no is {n}")
# print("name is {} and no is {}".format(name,n))
# x='refactor'
# print(x[-1:-4:-1])
#List comprehension
# list = [num*2 for num in range(10)]
# print(list)
#map()
def even(num):
return num*2
l = [1, 2, 3, 4, 5, 6 ,7 , 8, 9, 10]
# resu... |
import cv2
import numpy as np
# Class of functions used for simple image processing
class Functions:
def createCircle(w, h):
# creates distance img for creating circular crops
X, Y = np.ogrid[:w, :h]
CenterX, CenterY = w / 2, h / 2
img = ((X - CenterX) ** 2 + (Y - CenterY) ** 2)
... |
import matplotlib.pyplot as plt
#from matplotlib import pyplot plt
plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],label="BMW",color='b', width= .5)
plt.bar([0.25,1.05,2.75,3.75,4.75],[80,20,20,50,60],label="Audi",color= 'g', width= .5)
plt.legend()
plt.xlabel("Days")
plt.ylabel("Distance (KM's)")
plt.title("Inform... |
num = int(input("Enter Number : "))
factorial = 1
if num < 0:
print("Enter Positive Number")
elif num == 0:
print("Factorial is = 1 ")
else:
for i in range(1, num + 1):
factorial = factorial * i
print(factorial)
|
# _ _
# ((\o/))
# .-----//^\\-----.
# | /`| |`\ |
# | | | |
# | | | |
# | | | |
# '------===------'
def process_line(line):
line = line.strip().split('x')
li... |
"""Задача №3
Написать программу, которая генерирует в указанных пользователем границах:
a. случайное целое число,
b. случайное вещественное число,
c. случайный символ.
Для каждого из трех случаев пользователь задает свои границы диапазона.
Например, если надо получить случайный символ от 'a' до 'f', то вводятся э... |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'maxStreak' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER m
# 2. STRING_ARRAY data
#
def maxStreak(m, data):
max_conse = 0
current_conse ... |
email_dict = {}
def getEmailThreads(emails):
thread_num = 1
result = []
for comma in emails:
first = comma.find(",")+1
second = comma[first:].find(",")+1
text=comma[first+second:].strip()
print(text)
#text = email[2]
index = text.rfind("---") #find last index
... |
def binary_search(arr, x):
l = 0
m = 0
r = len(arr) - 1
while l <= r:
m = (l + r) // 2
if arr[m] == x:
return m
if arr[m] < x:
l = m + 1
continue
if arr[m] > x:
r = m - 1
continue
return -1
|
class Binary:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def height(A):
if A == None:
return 0
else:
ldepth = height(A.left)
rdepth = height(A.right)
if(ldepth > rdepth):
return 1+rdepth
... |
def max_sum_SubArray(arr):
current_sum = 0
max_so_far = arr[0]
for i in range(len(arr)):
current_sum = current_sum + arr[i]
if max_so_far < current_sum:
max_so_far = current_sum
elif current_sum < 0:
current_sum = 0
return max_so_far
arr = [4, ... |
def sort_colour(arr):
red = 0
blue = 0
for i in range(len(arr)):
if arr[i] == 1:
red+=1
elif arr[i] == 2:
blue+=1
return [1]*red + [2]*blue + [3]*(len(arr) - red - blue)
a = [1, 2, 3, 1, 3, 2, 1, 2, 3, 1]
print(sort_colour(a)) |
def odd_even(l):
whole = []
odd = []
even = []
for items in l:
if items % 2 == 0:
even.append(items)
else:
odd.append(items)
whole = [odd, even]
return whole
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(odd_even(list1)) |
import numpy as py
r = int(input("Enter the number of rows : "))
c = int(input("Enter the number of columns : "))
arr = py.zeros((r, c), dtype = int)
length = len(arr)
for i in range(length):
for j in range(len(arr[i])):
x = int(input("Enter the elements : "))
arr[i][j] = x
for i in r... |
def length():
string = input("Enter the stirng : ").split()
last_word = len(string[-1])
print(last_word)
length() |
class Phone:
def __init__(self, brand, model_name, price):
self.brand = brand
self.model_name = model_name
self.price = price
def full_name(self):
return f"This phone is {self.brand} {self.model_name}"
def make_a_call(self, number):
return f"Di... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
number = int(raw_input().strip())
l = []
for i in range (number):
inp = raw_input().split(" ")
command = inp[0]
if command == "insert":
l.insert(int(inp[1]),int(inp[2]))
elif command == "print":
print (l)
elif c... |
# get_bin_value.py
'''
This standalone program converts the letters A through G (and P for decimal point)
to their respective binary value for a common-anode seven segment display.
'''
output = ''
flags = {
"a": 0,
"b": 1,
"c": 2,
"d": 3,
"e": 4,
"f": 5,
"g": 6,
"p": 7
}
def main(): ... |
from collections import deque
import random
class DeckEmptyError(Exception):
# Constructor or Initializer
def __init__(self, value):
self.value = value
# __str__ is to print() the value
def __str__(self):
return(repr(self.value))
class Cards(object):
shades =(... |
import re
def long_repeat(line):
"""
length the longest substring that consists of the same char
"""
result = 0
for letter in set(line):
for match in re.findall(letter + "+", line):
if len(match) > result:
result = len(match)
return result |
#! /usr/bin/env python
from copy import deepcopy
d = {}
d['names'] = ['Alfred', 'Bertrand']
c = d.copy()
dc = deepcopy(d)
d['names'].append('Clive')
print c
#{'names': ['Alfred', 'Bertrand', 'Clive']}
print dc
#{'names': ['Alfred', 'Bertrand']}
print '\n\n\n\n\n'
x = {'username': 'admin', 'machines': ['foo', 'bar',... |
#! /usr/bin/env python
class Polymorphism:
"""
This class is an example of polymorphism
"""
#def run_account(self, *args):
def run_account(self, *args):
"""polymorphism example in method overloading
"""
print" ".join(args)
# creating instance of a class, create an object obj of a class Plo... |
#練習09 うるう年の判定 (ex09.py)
#うるう年というのは、四年に一度、二月が29日まである年のことをいうと思われていますが、正確にはもっと複雑です。西暦の年に対して、
#年が400で割り切れるなら、うるう年です。
#そうではなくて年が100で割り切れるならば、うるう年ではありません。
#そうでもなくて年が4で割り切れるならば、うるう年です。
year = int(input("西暦で年を入力して下さい >"))
if year % 400 == 0:
print(year,"年はうるう年です")
elif year % 100 == 0:
print(year,"年はうるう年ではありません")
el... |
#金額を入力するとその金額を出来るだけ少ない枚数の貨幣を使って支払えるように貨幣の枚数を数えるプログラムを書きなさい。貨幣は、{1万円札、五千円札、千円札、五百円玉、百円玉、五十円玉、十円玉、五円玉、一円玉}とする(余り使わないので2千円札は除く)。
money = int(input("金額(円) >"))
print(money,"円")
maisu =money // 10000
money = money % 10000
print("一万円札= ",maisu,"枚")
maisu =money // 5000
money = money % 5000
print("五千円札= ",maisu,"枚")
mais... |
print('Hello,Welcome to Quiz:')
ans=input('You Want to play (yes/no):')
score=0
total_q=4
if ans.lower() == 'yes':
ans=input('1.What is Best Programming language:Option=[java],[python] ')
if ans=='python':
score +=1
print('correct Answer')
else:
print('incorrect Answer')
ans = i... |
from queue import PriorityQueue as pq
from collections import defaultdict
from pprint import pprint as pp
class Graph:
def __init__(self, vertices):
self.vertexLbl = {vertex: pos for pos, vertex in enumerate(vertices)}
self.vertices = vertices
self.adjMat = [[-1] * len(vertices) for verte... |
from typing import List
class ListNode:
def __init__(self, x, next=None):
self.val = x
self.next = next
class LinkedList:
def __init__(self, vals: List[int] = []):
cur_node = None
self.head = None
self.d = dict()
for i in range(len(vals)):
... |
'''
286. Walls and Gates
You are given a m x n 2D grid initialized with these three possible values.
-1 - A wall or an obstacle.
0 - A gate.
INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
Fill each empty... |
'''
Graph is valid tree when it has no cycle and all nodes are connected
'''
from typing import List
visited:set
graph:List[List[int]]
def is_valid_tree(graph: List[List[int]]) -> bool:
visited = set()
# DFS
has_cycle = DFS(0, graph, visited)
is_connected = len(visited) == len(graph)
... |
from typing import List
from sys import maxsize
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
return self.check_node(root, -maxs... |
import unittest
from closest_two_sum import find_closest_pair
class TestClosestTwoSum(unittest.TestCase):
def test_find_closest_two_sum(self):
array = [10, 22, 28, 29, 30, 40]
n = len(array)
target = 54
self.assertEqual(find_closest_pair(array, n, target), (22, 30))
if __name__ =... |
'''
Quick Sort is divide and conqure algorithm with recursion
* In-Place sorting
* Best time O(N log N)
* Worst time O(N^2) if array is already sorted
'''
from typing import List
class QuickSort:
def sort(self, nums):
self.quickSort(nums, 0, len(nums)-1)
def quickSort(self, num... |
from typing import List
from collections import defaultdict
class Solution:
@staticmethod
def alienOrder(words: List[str]) -> str:
i = 1
adj_list = defaultdict(list)
while i < len(words):
word = words[i-1]
nextWord = words[i]
for charW1, charW2 in... |
class Solution:
def calculate_fibonacci(self, n) -> int:
# 0th fibonacci number is 0
if n == 0:
return 0
# 1st fibonacci number is 1
if n == 1:
return 1
if n == 2:
return 1
return self.calculate_fibonacci(n-1) + self.calcula... |
'''
261. Graph Valid Tree
Medium
942
32
Add to List
Share
Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
Example 1:
Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: true
Example 2:... |
'''
336. Palindrome Pairs
Hard
1253
147
Add to List
Share
Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.
Example 1:
Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],... |
from collections import defaultdict, deque
from pprint import pformat
from typing import List
class Graph:
def __init__(self, vertices: List[str]):
self.adj_list = {vertex: defaultdict(int) for vertex in vertices}
def add_edge(self, src, dest):
self.adj_list[src][dest] = 1
def breadth... |
'''Disjoint Set data structure to group edges of a graph into sets
Union Find is the algorithm on disjoint set which continously does union operation
Collapsing Find is another name for Union Find
Can find cycle in Undirected Graph applying Union Find on Disjoint Set'''
class Graph:
def __init__(self, v... |
def read_edges():
input_file = open('input1.txt', 'r')
input_data = input_file.read()
input_list = input_data.split("\n")
return_list = []
for input_row in input_list:
row_params = input_row.split(' ')
if len(row_params) != 3:
break
u = int(row_params[0])
v = int(row_params[1])
... |
# 載入內建的 sys 模組並取得資訊
# import sys as system
# print(system.platform)
# print(system.maxsize)
# 建立geometry模組, 載入並使用
# import geometry
# result=geometry.distance(1,1,5,5)
# print(result)
# result=geometry.slope(1,2,5,6)
# print(result)
# 調整搜尋模組的路徑
import sys
sys.path.append("mod") #在模組的搜尋紀錄中心新增
print(sys.path) #印出模組的搜尋路徑
... |
#參數的預設資料
# def power(base,exp=0):
# print(base**exp)
# power(3,2)
# power(4)
#使用參數名稱對應
# def divide(n1,n2):
# print(n1/n2)
# divide(3,6)
# divide(n1=6,n2=3)
#無限/不訂 參數資料
def avg(*ns):
sum=0
for x in ns:
sum+=x
print(sum/len(ns))
avg(7,5,6) |
# while 迴圈
# 1+2+3+.....+10
#n=1
#sum=0 #紀錄累加的結果
#while n<=10 :
# sum=sum+n
# n+=1
#print(sum)
# for 迴圈
# 1+2+3+.....+10
# sum=0
# for x in range(1,11):
# sum=sum+x
# print(sum) |
from time import sleep
def countdown(n):
while n>0:
yield n
n -= 1
# Fibonacci数生成器
def fib():
a, b = 0, 1
while True:
a, b = b, a + b
yield a
# 偶数生成器
def even(gen):
for val in gen:
if val % 2 == 0:
yield val
def main():
gen = even(fib())
f... |
def is_palindrome():
return "malayalam" == "malayalam"[::-1]
res=is_palindrome()
if res == True:
print("String is a palindrome")
else:
print("String is not a palindrome")
|
class User:
"""
Class that generates new instances of users
"""
user_list = [] # Empty user list
def __init__(self, first_name, last_name, email_address, password):
# docstring removed for simplicity
self.first_name = first_name
self.last_name = last_name
self.em... |
# https://en.wikipedia.org/wiki/Insertion_sort
def insertion_sort(collection):
for i in range(1, len(collection)):
while i > 0 and collection[i - 1] > collection[i]:
collection[i - 1], collection[i] = collection[i], collection[i - 1]
i -= 1
return collection
result = insertio... |
# https://leetcode.com/problems/01-matrix/
from typing import List
def updateMatrix(matrix: List[List[int]]) -> List[List[int]]:
from collections import deque
offsets = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def bfs(i2, j2):
nonlocal offsets, matrix
queue = deque([(i2, j2, 1)])
visite... |
#
#
#
#
#Basic Object Oriented Programing
#Notes
#how to create a class
class Hotel():
pass
#create instances of the class
bates_motel = Hotel()
grand_budapest = Hotel()
#create unique instance of the class
class Hotel():
#Constructor
#can contain default properties, must come after required properties
... |
from histogram import histogram
from anagram import make_anagram_dict
from math import log10
words = open("words.txt", "r").readlines()
dictionary = make_anagram_dict(words)
def anagram_count(dictionary):
"""
Given a dictionary of anagrams, this function counts how many keys have n
anagrams, f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 21 07:03:15 2019
@author: prapti
"""
import cv2
import math
img = cv2.imread('lenna.png', cv2.IMREAD_GRAYSCALE)
print(img.shape)
cv2.imshow('input image',img)
'''
GAMMA TRANSFORMATION
'''
gamma = float(input("Enter Gamma Value:"))
#gamma = 1.5
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:yiluzhang
"""
Reinforcement learning maze example.
Red rectangle: explorer.
Black rectangles: hells [reward = -1].
Yellow bin circle: paradise [reward = +1].
All other states: ground [reward = 0].
This script is the main pa... |
# Testing drawing 500 bezier points with algorithm from http://stackoverflow.com/questions/246525/how-can-i-draw-a-bezier-curve-using-pythons-pil/2292690#2292690
import timer
import random
from pascal_bezier import *
NUM_CURVES = 500
NUM_STEPS = 1000
R = random.randint
points = [[(R(0,999), R(0,999)), (R(0,999), R(0... |
import os
import csv
# Path to collect data from the Resources folder
votes_csv = os.path.join('Resources', 'election_data.csv')
#Function created to more easily check whether candidate already has an entry in the candidate list[]
def candidate_in_list(candidateList, aCandidate):
name = str(aCandidate)
inList... |
def fibonacci(x):
if x<0:
print("invalid input")
elif x==0:
return 0
elif x==1:
return 1
else:
return fibonacci(x-1)+fibonacci(x-2)
print("Fabonacci series is as follows: ")
i=0
while i<10:
print(int(fibonacci(i)))
i=i+1
print("done")
|
listaclientes = []
clientes = 0
while clientes < 500:
cliente = input("Nombre:")
producto = input("Su producto es:")
costo = float(input("Su costo es:"))
registro = dict(cliente=cliente, producto=producto, costo=costo)
listaclientes.append(registro)
# final = input("¿Se agregara otro cliente... |
myList = LinkedList()
myList.add(500)
myList.add(100)
myList.add(200)
myList.add(300)
myList.add(500)
myList.add(400)
myList.add(500)
myList.add(500)
myList.add(600)
#
myList.isEmpty()
# Adding elements to linked list
myList.add()
# Returning the size of the linked list
myList.size()
# Finding e... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"... |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def rorateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head == None:
return head
if k ... |
# Given n non-negative integers a1, a2, ..., an ,
# where each represents a point at coordinate (i, ai).
# n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0).
# Find two lines, which, together with the x-axis forms a container,
# such that the container contains the most wa... |
C = 0
farenheit = 0
for C in range(10, 110, 10) :
farenheit = C * 1.8 + 32
print("A temperatura em graus é", C, "C⁰", "e em farenheit", farenheit, "F")
|
ini = int(input('insira o limite inferior :'))
fini = int(input('insira o limite superior'))
soma = 0
i = ini
f = 1
y = 0
while ini <= i <= fini :
soma = ini + ini + f
i += 1
f += 1
y = y + soma
print(soma)
|
a = {'a':3, 'b': 4, 'c': 5}
print(a['a'])
a['a'] += 1
print(a)
|
A = int(input("digite Votos validos de A:"))
B = int(input("digite Votos validos de B:"))
C = int(input("digite Votos validos de C:"))
nda = int(input("digite Votos nulos de A:"))
ndb = int(input("digite Votos nulos de B:"))
ndc = int(input("digite Votos nulos de C:"))
eba = int(input("digite Votos em branco de A:"))... |
a = int(input('insira num:'))
b = int(input('insira num:'))
c = int(input('insira num:'))
if a > b and b >c :
print(a, b, c)
print('o maior numero é {}'.format(a))
elif b > a and a > c :
print(a, b, c)
print('o maior numero é {}'.format(b))
else :
print(a, b, c)
print('o maior numero ... |
mes = int(input("digite o mes:"))
if ((mes <= 0) or (mes > 12)) :
print("mes invalido")
else :
ano = int(input("insira valor de anos:"))
if (ano % 4 == 0) and (ano % 100 != 0) :
print("ano bissexto")
elif (ano % 400 == 0) :
print("ano bissexto")
else :
print("ano comun")
|
'''
Created on 15 Nov 2014
@author: MuresanVladut
'''
class Student:
def __init__(self,idd,name,group):
self.idd=idd
self.name=name
self.group=group
def getId(self):
return self.idd
def getName(self):
return self.name
def getGroup(self):
return self.gr... |
import sys
from typing import Tuple, Optional
global nums
def sum2(start: int, end: int, target: int) -> Optional[Tuple[int, int]]:
"""
Find two number in the nums[start:end] whose sum is equal to target.
"""
seen = set()
for i in range(start, end):
n = nums[i]
if target - n in se... |
def compare(point, position):
x = 1 if point[0]-position[0]>0 else (0 if point[0]-position[0]==0 else -1)
y = 1 if point[1]-position[1]>0 else (0 if point[1]-position[1]==0 else -1)
return x, y
# lx: the X position of the light of power
# ly: the Y position of the light of power
# tx: Thor's starting X pos... |
import datetime
def array_to_date(array):
return datetime.date(array[2], array[1], array[0])
def today_to_array():
today = datetime.date.today()
return [today.day, today.month, today.year]
def array_to_string(array):
arr = [str(number) for number in array]
return '-'.join(arr)
def string_to_a... |
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.queue = collections.OrderedDict()
def get(self, key):
if key not in self.queue:
return -1
value = self.queue.pop(key)
self.queue[key] = value
return self.queue[key]
d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.