text stringlengths 5 121k |
|---|
def min_list():
list = [8, 6, 4, 8, 4, 50, 2, 7]
k=min(list)
print(k)
min_list()
|
def ft_sum_even_part_lst(a):
b = 0
for i in a:
if i % 2 == 0:
b += i
return b
|
p1_score = 0
p2_score = 0
roll = 0
import random
def login():
usernameone = input('Enter Username One Username: ')
passwordone = input('Enter Username One Password: ')
usernametwo = input('Enter Username Two Username: ')
while usernameone == usernametwo:
usernametwo = input('Error ')
pa... |
degree_celsius = float(input())
if (degree_celsius >= 26.00) and (degree_celsius <= 35.00):
print(f"Hot")
elif (degree_celsius >= 20.10) and (degree_celsius <= 25.90):
print(f"Warm")
elif (degree_celsius >= 15.00) and (degree_celsius <= 20.00):
print(f"Mild")
elif (degree_celsius >= 12.00) and (degree_cels... |
vacation_days = int(input())
minutes_game = ((365 - vacation_days) * 63) + vacation_days * 127
diff = 30000 - minutes_game
if diff > 0:
down_min = 30000 - minutes_game
print(f"Tom sleeps well")
print(f"{down_min // 60} hours and {down_min % 60} minutes less for play")
else:
over_min = minutes_game - ... |
word_1 = input().lower()
word_2 = input().lower()
if word_1 == word_2:
print(f"yes")
else:
print(f"no")
|
def print_col(col):
print(f"{col} ", end='')
def print_row():
print()
def draw(n):
for row in range(1, n+1):
for col in range(1, row+1):
print_col(col)
print_row()
for row in range(n, 1, -1):
for col in range(1, row):
print_col(col)
print_row()... |
num_1 = int(input())
num_2 = int(input())
for n in range(num_1, num_2 + 1):
odd_sum = 0
even_sum = 0
number = n
for i in range(3):
even_sum += n % 10
n = n // 10
odd_sum += n % 10
n = n // 10
if odd_sum == even_sum:
print(number, end=' ')
|
while True:
saved_money = 0
country = input()
if country == 'End':
break
budget = float(input())
while not saved_money >= budget:
money = float(input())
saved_money += money
if saved_money >= budget:
print(f'Going to {country}!')
break
|
num_open_site = int(input())
salary = int(input())
for _ in range(num_open_site):
name_site = input()
if name_site == 'Facebook':
fine = 150
elif name_site == 'Instagram':
fine = 100
elif name_site == 'Reddit':
fine = 50
else:
fine = 0
salary -= fine
if salar... |
num = int(input())
num_list = []
while num:
n = int(input())
num_list.append(n)
num -= 1
print(f"{max(num_list)}")
|
num_tables = int(input())
length = float(input())
width = float(input())
usd = 1.85
cover_table_big = (width + 0.60) * (length + 0.60)
cover_table_small = length / 2 * length / 2
price_usd = (cover_table_big * num_tables * 7) + (cover_table_small * num_tables * 9)
print(f"{price_usd:.2f} USD")
print(f"{price_usd * usd... |
hour_exam = int(input())
minute_exam = int(input())
hour_arrival = int(input())
minute_arrival = int(input())
exam = (hour_exam * 60) + minute_exam
arrival = (hour_arrival * 60) + minute_arrival
diff_time = exam - arrival
if diff_time < 0:
print(f"Late")
if abs(diff_time) < 60:
print(f"{abs(diff_time)... |
change = float(input())
change = round(change * 100)
coin = 200
total_coins = 0
while not change == 0:
coins = change // coin
change = change % coin
coin = coin // 2
if coin == 25:
coin = 20
total_coins += coins
print(total_coins)
|
word = input()
sum_vowels_letters = 0
vowels_letters_dict = {
'a': 1,
'e': 2,
'i': 3,
'o': 4,
'u': 5
}
for l in word:
if l in vowels_letters_dict.keys():
sum_vowels_letters += vowels_letters_dict[l]
print(sum_vowels_letters)
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib.layers import fully_connected
mnist = input_data.read_data_sets("/tmp/data")
n_inputs = 28*28
n_hidden1 = 30
n_hidden2 = 10
n_outputs = 10
learning_rate = 0.01
n_epochs = 10
batch_size = 50
X = tf.place... |
"""
Created on Sun Jul 18 19:15:26 2021
@author: Ayush
"""
def TeacherAlice(n):
if n==1 or n==2:
return n+1
else:
c1 = TeacherAlice(n-1)
c2 = TeacherAlice(n-2)
return c1+c2
if __name__=="__main__":
T = int(input())
for i in range(1,T+1):
n = i... |
"""
Created on Sat Jul 17 13:47:33 2021
@author: Ayush
"""
def fact(n):
if n==0 or n==1:
return 1
return n * fact(n-1)
if __name__=="__main__":
print(fact(5)) |
ch = input()
num = int(input())
l = []
for x in range(0, num):
s = input()
if (s.count(ch.upper()) + s.count(ch.lower()) >= 3):
l.insert(0, s)
for x in l:
print(x)
|
weight, height = map(float, input().split())
bmi = weight / (height ** 2)
if bmi < 18.5:
grade = 'A'
elif 18.5 <= bmi < 24:
grade = 'B'
elif 24 <= bmi < 28:
grade = 'C'
else:
grade = 'D'
print("{}:{:.2f}".format(grade, bmi)) |
gain = float(input("What is the revenue this month? $"))
costs = float(input("What is the monthly expenses? $"))
if gain == costs:
print ("Not bad. No losses this month")
elif gain < costs:
print("It's time to think seriosly about cutting costs")
else:
print("Great! This month you have a profit")
staff... |
print("This program calculates the average of two numbers")
firstNumber = float (input({"What will the first number be:"}))
secondNumber = float (input({"What will the second number be:"}))
print("The numbers are",firstNumber, "and",secondNumber)
print("The average is: ", (firstNumber + secondNumber )/ 2) |
import sys
from checksum_checker import create_checksum
from disk_path_scanner import RecursivePathWalker
from os.path import getsize
def find_duplicates(path='/tmp'):
"""
Recursive finder of all duplicate path
:param path: paht name
:return:
"""
dup = []
record = {}
d = RecursivePa... |
import random
def coin_toss(call,bet):
num = random.randint(1, 2)
if call == "Heads" and num == 1:
print("Heads, you won " + str(bet))
return bet
elif call == "Tails" and num == 2:
print("Tails, you won " + str(bet))
return bet
elif call == "Tails" and num == 1:
... |
for _ in range(int(input())):
string = input()
aCost = int(input())
bCost = int(input())
length = len(string)
ans = 0
for i in range(0,length//2):
if(string[i] == '/' or string[length - i - 1] == '/'):
if(i == length - i - 1):
ans += min(aCost, bCost)... |
class InvalidLengthException (Exception):
pass
class Mobile:
def __init__ (self,mob_no):
self.__mob_no=mob_no
def validate_mobile_number(self):
try:
if(len(self.__mob_no)!=10):
raise InvalidLengthException
else:
print("Valid M... |
import os
board = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]
def print_board(board):
print(board[7] + ' |' + board[8] + ' |' + board[9])
print("--------")
print(board[4] + ' |' + board[5] + ' |' + board[6])
print("--------")
print(board[1] + ' |' + board[2] + ' |' + board[3])
def game()... |
x=[10,2,3,40,3]
print (x)
x.remove(3)
print("after removing 3" , x)
del x[3]
print("after deleting index3" , x)
x.append(5)
print("after appending 5" , x)
x.pop(1)
print("after popping index 1" ,x)
|
class Human:
def talk(self):
print('I can talk')
def walk(self):
print('I can walk')
def eat(self):
print('I can eat')
class Teacher():
def teach(self):
print('I can teach')
class Honored_Teacher(Teacher,Human):
def __init__(self,number):
self.number = number
def prize(self):
print(f"I received {sel... |
"""
Utility module to handle sending of email messages.
"""
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
__author__ = "Jenson Jose"
__email__ = "jensonjose@live.in"
__status__ = "Alpha"
class MailUtils:
"""
Utility class containing methods for sending of... |
import numpy
from constant import *
class Playground:
"""
class playground is a dimension_x* dimension_y grid
mark the objects' position
be shown by show() in trustGame.py
"""
dimension_x = 0
dimension_y = 0
grid = numpy.zeros((1, 1), dtype=int)
apples = []
def __init__(self, ... |
age = input("What is your age? ")
newage=90-int(age)
days=newage*365
months=newage*12
weeks=newage*52
print(f"You have {days} days, {weeks} weeks, and {months} months left.")
|
import math
def paint_calc(height, width, cover):
num = height*width
num_of_cans = math.ciel(num/cover)
print(f"You'll need {num_of_cans} of paint")
test_h = int(input("Height of wall: "))
test_w = int(input("Width of wall: "))
coverage = 5
paint_calc(height=test_h, width=test_w, cover=coverage)
|
logo = '''
___________
\ /
)_______(
|"""""""|_.-._,.---------.,_.-._
| | | | | | ''-.
| |_| |_ _| |_..-'
... |
import turtle
from tkinter import messagebox, simpledialog, Tk
import math
import turtle
if __name__ == '__main__':
window = Tk()
window.withdraw()
num = simpledialog.askinteger("Enter a radius",None)
Shivam = turtle.Turtle()
Shivam.circle(num)
Shivam.penup(... |
def even_odd(n):
if n%2 == 0:
return True
return False
|
def squareroot(n):
num=0
while num*num<n:
num +=1
return num
|
import unittest
from city_functions import city_details
class TestCityDetails(unittest.TestCase):
def test_city_details(self):
testcitydetails = city_details('santiago','chile')
self.assertEqual(testcitydetails,'Santiago, Chile')
def test_city_details_population(self):
testcitydetails... |
class AnonymousSurvey():
"""A class to collect anonymous answers to a survey Question"""
def __init__(self, question):
"""Store a Question and prepare to store reponses"""
self.question = question
self.responses = []
def show_question(self):
"""Display the Question"""
... |
values = []
for i in range(1000, 3001):
s = str(i)
if (int(s[0])%2==0 and int(s[0])!=0 )and (int(s[1])%2==0 and int(s[1]) !=0) and (int(s[2])%2==0 and int(s[2]) !=0) and (int(s[3])%2==0 and int(s[3])!=0):
values.append(s)
print (",".join(values))
|
import numpy as np
import pandas as pd
from ggplot import *
import statsmodels.api as sm
import matplotlib.pyplot as plt
def normalize_features(df):
"""
Normalize the features in the data set.
"""
mu = df.mean()
sigma = df.std()
if (sigma == 0).any():
raise Exception("One o... |
import turtle
turtle.shape('turtle')
def o(n):
turtle.left(n)
for i in range(1,120):
turtle.forward(1)
turtle.left(3)
turtle.right(n)
for h in range(0,360,60):
o(h)
|
import numpy as np
def constructTransitions(filename):
p = np.zeros(shape=(26, 26))
prior = np.zeros(shape=(26, 1))
with open(filename) as f:
for line in f:
for word in line.split():
for i, c in enumerate(word):
to_c = ord(c) - or... |
"""
Created on Tue Sep 20 15:04:49 2016
@author: jameslegros
"""
s = 'azcbobobegghakl'
length = len(s)
i = 0
count = 0
while (length > i):
if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or s[i] == 'o' or s[i] == 'u':
count += 1
i += 1
print ("Number of vowels: " + str(count)) |
"""
Created on Tue Jun 4 22:15:32 2019
@author: Emily
"""
with open('sunspots.txt', 'r') as f:
entire_file = f.read()
list_of_data = entire_file.split("\n")
dict_of_sunspots = {}
sunspot_values_list = []
for n in list_of_data:
n = n.split("\t")
dict_of_sunspots[int(n[0])] = float(n[1])
... |
import pandas as pd
"""
Class specialized in cleaning files by removing columns
"""
class DataCleaner:
def __init__(self, old_separator=',', new_separator='\t'):
self.old_separator = old_separator
self.new_separator = new_separator
def validate_formatting(self, data_header):
try:
columns = len(data_head... |
class Person:
def __init__(self, name, age, fav_color):
self.name = name
self.age = age
self.fav_color = fav_color
def say_hello(self):
print(f'Hi, my name is {self.name}')
def change_fav_color(self, new_color):
self.fav_color = new_color
class Swimmer(Person):
... |
"""
fixme
https://leetcode.com/problems/odd-even-linked-list/
Q18. 홀짝 연결 리스트
연결 리스트를 홀수 노드 다음에 짝수 노드가 오도록 재구성하라. 공간 복잡도 O(1), 시간 복잡도 O(n)에 풀이하라.
입력 : 1 → 2 → 3 → 4 → 5 → NULL
출력 : 1 → 3 → 5 → 2 → 4 → NULL
입력 : 2 → 1 → 3 → 5 → 6 → 4 → 7 → NULL
출력 : 2 → 3 → 6 → 7 → 1 → 5 → 4 → NULL
"""
class ListNode:
def __... |
S = int(input())
R = [[x for x in input().split()] for y in range(S)]
word=""
word2=""
word3=""
for i in range(S):
word = R[i][1]
for j in range(len(word)):
word2 = word[j]*int(R[i][0])
word3+=word2
print(word3)
word3="" |
import sys
input = sys.stdin.readline
class Solution:
def section(self, x: int, y: int):
if x > 0:
if y > 0:
return 1
else:
return 4
else:
if y > 0:
return 2
else:
return 3
x =... |
from sys import stdin
if __name__ == '__main__':
C = int(stdin.readline())
answers = []
for i in range(0, C):
case = list(map(int, stdin.readline().split()))
sum = 0
for j in range(1, len(case)):
sum += case[j]
average = sum / case[0]
count = 0
f... |
"""
fixme. https://leetcode.com/problems/trapping-rain-water/
fixme. Q08. 빗물 트래핑
fixme. 높이를 입력받아 비 온 후 얼마나 많은 물이 쌓일 수 있는지 계산하라.
fixme. Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
fixme. Output: 6
fixme. Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
fixme. In this... |
N = int(input())
YX = []
for i in range(N):
x, y = map(int, input().split())
YX.append([y, x])
YX.sort()
for i in range(N):
print(YX[i][1], end=" ")
print(YX[i][0]) |
from typing import List
import collections
from sys import stdin
class Solution:
def numberCard2(self, N: int, cards: List[int], M: int, problems: List[int]) -> List[int]:
answer = []
counter = collections.Counter(cards)
for problem in problems:
if problem in counter:
... |
number = [int(i) for i in input()]
number.sort()
number.reverse()
for i in range(len(number)):
print(number[i], end="") |
"""
fixme
https://leetcode.com/problems/reverse-linked-list/
Q15. 역순 연결 리스트
연결 리스트를 뒤집어라.
입력 : 1 → 2 → 3 → 4 → 5 → NULL
출력 : 5 → 4 → 3 → 2 → 1 → NULL
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseListRecur(self, head... |
def myfunc(a, b, b2):
if b2 == 0:
print(a*b)
return
print(a * (b2 % 10))
myfunc(a, b, b2//10)
if __name__ == '__main__':
n1 = int(input())
n2 = int(input())
myfunc(n1, n2, n2)
|
def course_grader(test_scores):
test_avg = sum(test_scores)/len(test_scores)
if test_avg >= 70 and min(test_scores) > 50:
return("pass")
elif test_avg < 70 or min(test_scores) <= 50:
return("fail")
def main():
print(course_grader([100,75,45]))
print(course_grader([100,70,8... |
def arrayChange(inputArray):
count = 0;
for i in range(len(inputArray)-1):
if inputArray[i+1]<=inputArray[i]:
while inputArray[i+1]<=inputArray[i]:
inputArray[i+1]+=1
count+=1
return count
print(arrayChange([-1000, 0, -2, 0])) |
import graph
from random import randrange
def black_left_column(width, height, length):
for y in range(height):
for x in range(width):
if x < length:
graph.plot(y, x)
def black_rectangle(x1, x2, y1, y2):
for y in range(y1, y2):
for x in range(x1, x2):
... |
"""
From: projecteuler.net
Problem ID: 4
Author: Walter Vives
GitHub: https://github.com/WalterVives
Problem:
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers... |
def percy_replacer(string_about_percy):
return string_about_percy.replace("Percy", "Ron")
def weasley_invitation(name,day,date,month):
return "The family of {first_name} Weasley proudly invite you to celebrate their graduation from Hogwarts on {day} the {date} of {month}. Festivities will be held at The Bur... |
class RetailItem:
def __init__(self, descr, inv, price):
self.__description = descr
self.__units = inv
self.__price = price
def set_descr(self, descr):
self.__description = descr
def set_inventory(self, units):
self.__units = units
def set_pri... |
import math
import unittest
import random
def wallis(n):
pi = 0.0
for i in range(1, n):
x = 4 * (i ** 2)
y = x - 1
z = float(x) / float(y)
if (i == 1):
pi = z
else:
pi *= z
pi *= 2
return pi
class TestWallis(unittest.TestCase):
def ... |
"""
create a text file with word on a number of lines
1. open the text file and print out 'f.read()'. What does it look like?
2. use a for loop to print out each line individually. 'for line in f:'
3. print our words only with "m", or some other specific letter.
"""
|
"""
name: str
cost: int
nutrition: int
"""
class Food:
""" Food class
Attributes:
name (str): name of food
cost (int): cost of food
nutrition (int): how nutritious it is
"""
def __init__(self, name: str, cost: int, nutrition: int):
""" Create a Food object.
Arg... |
from collections import deque
class Solution(object):
def mergeTrees(self, t1, t2):
mergedTree = None
q = deque()
triplet = []
if (t1 is not None and t2 is not None):
mergedTree = TreeNode(t1.val + t2.val)
triplet = [mergedTree, t1, t2]
elif (t... |
def make_rectangle(A):
board = [
['.' for i in range(1001)]
for j in range(1001)
]
print("{} {}".format(2, 2))
count = 3
i = 1
j = 1
while i > 0 and j > 0:
line = raw_input()
i = int(line.split(' ')[0])
j = int(line.split(' ')[1])
print("2 {}".format(count % A))
count... |
class Solution:
def middleNode(self, head):
first = head
second = head
while second and second.next:
first = first.next
second = second.next.next
return first
|
from collections import deque
class Solution:
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
if not root:
return 0
path_count = 0
que = deque()
que.append((root, [root.val]))
whi... |
class Solution(object):
def findWords(self, words):
keyboard = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
op = []
for word in words:
if (word == ""):
op.append(word)
else:
valid = 1
for line in keyboard:
... |
from collections import deque
from statistics import mean
class Solution:
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
queue = deque()
levels = []
queue.append((root, 0))
while queue:
node_tuple ... |
def cls():
print(50 * "\n")
def backwards(text):
result=text.split(" ")
lnth=len(result)
j=range(lnth)
text=[]
for i in j:
text.append(result[lnth-i-1])
result=[]
result=" ".join(text)
return(result)
def backwards2(text):
result=text.split... |
def cls():
print(50 * "\n")
def player_choice(player):
print("Player " + str(player) + ", what is your choice?")
for i in range(0, len(tab)):
print(str(i) + " - " + tab[i])
choice=-1
while choice not in ["0","1","2"]:
choice=input("Enter 0, 1 or ... |
import random
def cls():
print(50 * "\n")
def game(nr):
unr = 1
while (unr < 1000) or (unr > 9999):
unrtxt = input("Give me a 4-digit number (1000-9999) or press enter for quit: ")
if unrtxt == "": break
unr = 1
for i in unrtx... |
import re
def isPalindrome(s):
s = s.lower()
s = re.sub('[^a-z0-9]','',s)
if s == s[::-1]:
return True
else:
return False
s = str(input("Enter the string: "))
print(isPalindrome(s)) |
import tkinter
from tkinter import messagebox
import random
root = tkinter.Tk()
root.title('3')
heads_img = tkinter.PhotoImage(file = "heads_coin.gif")
"""
panel = tkinter.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
"""
tails_img = tkinter.PhotoImage(file = "tails_coin.gif"... |
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while(1):
_, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_blue = np.array([45,100,50])
upper_blue = np.array([75,255,255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
... |
def fibbonaci(n):
if n==0:
return [0]
if n==1:
return [0,1]
numbers=[0,1]
count=2
while count<n:
numbers.append(numbers[count-2]+numbers[count-1])
print(numbers[count-2]+numbers[count-1])
count=count+1
return numbers
var=fibbonaci(20)
print(var)
def fib(n... |
name= input("Enter name:")
print (name)
m=list(name)
n=m[0]
x=len(m)
for i in range(1,x):
if(m[i]==n):
m[i]='$'
print ("".join(m))
|
class Student:
def __init__(self):
self.final = []
self.final = "".join(x for x in input("Enter Data : ")).split()
self.final1 = []
def print_data(self):
for i in range(0,len(self.final)-1,2):
self.final1.append([self.final[i],self.final[i+1]])
print... |
s = str(input('Enter string:'))
word=sorted(s)
alternatives = (list(str(ar) for ar in input('Enter string: ').split()))
for a in alternatives:
if word == sorted(a):
print (a)
|
import math
class Circle:
def __init__(self,radius):
self.radius=radius
def area(self,radius):
self.radius=radius
a=math.pi*self.radius**2
return a
def parimeter(self,radius):
self.radius=radius
p=2*math.pi*self.radius
return p
r=int(input('Enter the radius of circle: '))
c=Circle(r)
area=c.area(r)
pr... |
from abc import ABCMeta, abstractmethod
class Polygone:
__metaclass__ = ABCMeta
def __init__(self):
self.n = int(input("Enter the number of sides"))
self.list_size = [int(a) for a in input('Enter size of sides: ').split()]
@abstractmethod
def compute_Area(self):
"""Abstract met... |
"""Codeforces problem 1030A "In Search of an Easy Problem"
"""
if __name__ == "__main__":
n = int(input())
answers = [int(x) for x in input().split()]
if any(answers):
print("HARD")
else:
print("EASY")
|
"""Codeforces problem 705A - Hulk
"""
if __name__ == "__main__":
n = int(input())
FIRST_PHRASE = "I hate that "
SECOND_PHRASE = "I love that "
result = ""
for i in range(1, n + 1):
if i % 2 == 1:
result += FIRST_PHRASE
else:
result += SECOND_PHRASE
pr... |
class Node:
def __init__(self,data):
self.data=data
self.head=None
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def insert(self,data):
if(self.head is None):
new_node=Node(data)
self.head=new_node
else:
new_node=... |
import sys
class Vertex:
def __init__(self, v_name):
self.name = v_name
self.neighbors = {}
self.parent = None
def add_neighbor(self, v, w=0):
'''Given input is already a vertex object.
v: the connecting neighbor, w: the weight
'''
if v not in ... |
def print_twice(x):
print(x, end=' ')
print(x, end=' ')
def h_left(f, x):
print('+', end=' ')
f(x)
f(x)
def unit_one(f, x):
h_left(f, x)
h_left(f, x)
print('+')
def v_left(f, x):
print('|', end=' ')
f(x)
f(x)
def unit_t... |
'''Write a Python program to find missing and additional values in two lists.'''
list_1 = ['a','b','c','d','e','f']
list_2 = ['d','e','f','g','h']
missing_values_in_list_2 = [i for i in list_1 if i not in list_2]
additional_values_in_list_2 = [i for i in list_2 if i not in list_1]
print("Missing values in list 2: "+str... |
'''Write a Python function that takes a list of words and returns the length of the longest one. '''
def longest_word(sentence):
words = sentence.split()
length_words = [len(i) for i in words]
return words[length_words.index(max(length_words))]
sentence = input("Enter a sentence: ")
print("Longest word: "... |
'''Write a Python function that takes a list and returns a new list with unique
elements of the first list.'''
num_list = [1,2,2,2,3,3,4,4,4,4,5,5,5,5,5]
set(num_list)
'''for making list'''
unique_elements = []
for i in num_list:
if i not in unique_elements:
unique_elements.append(i)
print(unique_eleme... |
'''Write a Python program to get the smallest number from a list'''
def smallest_item(items):
return(min(items))
items = [2,4,5,8,3,0]
print(smallest_item(items))
|
'''Write a Python program to find the maximum occurring character in a given string.'''
string = input("Enter an string: ")
chars = []
count = []
for i in string:
if i not in chars:
chars.append(i)
for i in chars:
n = 0
for j in list(string):
if i == j:
n+= 1
count.append(... |
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title('Hi!')
root.iconbitmap(r'C:\Users\aadan\Desktop\2.ico')
frame = LabelFrame(root, padx=50, pady=50)
frame.pack(padx=10, pady=10)
b = Button(frame, text="Don't click me!")
b2 = Button(frame, text="... or here!")
b.grid(row=0, column=0)
b2.grid... |
class Node:
def __init__(self, val):
self.val = val
self.rank = 0
self.parent = self
def find(x):
if x != x.parent:
x.parent = find(x.parent)
return x.parent
def union(x,y):
x = find(x)
y = find(y)
if x == y:
return
if x.rank > y.rank:
y.... |
def partition_hoare(array, low, high):
pivot = array[low]
(i, j) = (low - 1, high + 1)
while True:
while True:
i = i + 1
if array[i] >= pivot:
break
while True:
j = j - 1
if array[j] <= pivot:
break
if i... |
def dfs_arr(graph):
def dfs_visit_arr(g, u):
print(u, end=' ')
nonlocal time
time += 1
visited[u] = True
for v in g[u]:
if not visited[v]:
parent[v] = u
dfs_visit_arr(g, v)
time += 1
time = 0
n = len(graph)
vi... |
import unittest
import mock
import player_keyboard_input
PlayerKeyboardInput = player_keyboard_input.PlayerKeyboardInput
class TestPlayerKeyboardInput(unittest.TestCase):
def setUp(self):
self.player = PlayerKeyboardInput('x')
self.player._board = mock.MagicMock()
def test_make_move_proper... |
name = input("What is your name?")
print("Hi " + name + ", nice to meet you. I am Chatbot-1024.")
sport = input("What is your favorite sport? ")
if (sport == "football") or (sport == "Football"):
yards = int(input("I like football too. Can you tell me the length of a football field in yards? "))
if ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.