text stringlengths 37 1.41M |
|---|
"""
Remove Duplicates from Sorted List
==================================
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
"""
from __future__ import print_function
from linked_list import Node
d... |
"""
Merge Two Sorted Lists II
=========================
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note: You have to modify the array A to contain the merge of A and B.
Do not output anything in your code.
TIP: C users, please malloc the result into a new array and return the result.... |
"""
2 Sum
=====
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 < index2.
Please note that your returned answers (both index1 and index2 ) are not zero-based.
... |
"""
Balanced Binary Tree
====================
Given a binary tree, determine if it is height-balanced.
Height-balanced binary tree : is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Return 0 / 1 ( 0 for false, 1 for true ) for this problem
Example :
Inp... |
# -*- coding: utf-8 -*-
"""
Largest Rectangle in Histogram
==============================
Given n non-negative integers representing the histogramโs bar height where the width of each bar is 1,
find the area of largest rectangle in the histogram.
For example,
Given height = [2,1,5,6,2,3],
return 10.
Solution
-------... |
"""
Combinations
============
Given two integers n and k, return all possible combinations of k numbers out of 1 2 3 ... n.
Make sure the combinations are sorted.
To elaborate,
Within every entry, elements should be sorted. [1, 4] is a valid entry while [4, 1] is not.
Entries should be sorted within themselves.
Exa... |
"""
Hotel Bookings Possible
=======================
A hotel manager has to process N advance bookings of rooms for the next season.
His hotel has K rooms. Bookings contain an arrival date and a departure date.
He wants to find out whether there are enough rooms in the hotel to satisfy the demand.
Write a program that ... |
"""
Sum Of Fibonacci Numbers
========================
How many minimum numbers from fibonacci series are required such that sum of numbers should be equal to a given Number N?
Note: repetition of number is allowed.
Example:
N = 4
Fibonacci numbers : 1 1 2 3 5 .... so on
here 2 + 2 = 4
so minimum numbers will be 2
""... |
"""
Remove Duplicates from Sorted List II
=====================================
Given a sorted linked list, delete all nodes that have duplicate numbers,
leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
"""
from __future__... |
"""
Maximum Consecutive Gap
=======================
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Try to solve it in linear time/space.
Example :
Input : [1, 10, 5]
Output : 5
Solution
--------
The constraints of the problem can be met with sort... |
"""
Clone Graph
===========
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
"""
from __future__ import print_function
class Node:
def __init__(self, label, neighbours=None):
self.label = label
if neighbours is None:
neighbours = []
... |
"""
Merge Two Sorted Lists
======================
Merge two sorted linked lists and return it as a new list.
The new list should be made by splicing together the nodes of the first two lists, and should also be sorted.
For example, given following linked lists:
5 -> 8 -> 20
4 -> 11 -> 15
The merged list should b... |
def table(number):
for i in range(1,11):
print "%s * %s = %s"%(number,i,(number*i))
inp = input("enter a number : ")
table(inp) |
def read_lines(filename):
'''
read the content of a given file
'''
fobj = open(filename,"r")
data = fobj.readlines()
fobj.close()
return data
data1 = read_lines("sample.txt")
#print data1
########################################################
fobj = open("C:\\Users\\Ram\\Deskt... |
def fibo(num):
if (num<=1):
return num
else:
return (fibo(num-1) + fibo(num-2))
num = int(input("enter a number of terms : "))
print " Fibonacci sequence"
for i in range(num):
print fibo(i) |
def Bubble_Sort(lst):
print lst
sort = True
while sort:
sort = False
for i in range(len(lst)-1):
if lst[i] > lst[i+1]:
lst[i],lst[i+1] = lst[i+1],lst[i]
sort = True
return lst
seq = [2,1,3,12,4,6,7,11,8,10,9]
print Bubble_Sort(... |
print "A"
for row in range(1,5):
for col in range(1,8):
if row+col ==5 or col-row == 3 or ((row ==3) and (col>1 and col<7)):
print '*',
else:
print " ",
print ""
print "K"
for row in range(1,8):
for col in range(1,5):
if col == 1 or row+ col... |
print('์ฌ์์ฑ์ด ๋ง์ถ๊ธฐ ๊ฒ์์ ์์ํฉ๋๋ค')
print('---------------------------------')
a = ['๊ฐ๊ณผ์ฒ์ ','๊ตฌ์ฌ์ผ์','๊ตฐ๊ณ์ผํ', '๋ฌด์ฉ์ง๋ฌผ', '๋๊ณ ๋๋ฝ']
b = print(input('๋ฏธ๋ฆฌ ์ค๋นํด๋๋ฉด ๊ทผ์ฌ ๊ฑฑ์ ์ด ์๋ค \n ์ด ๋ง์ ์ฌ์์ฑ์ด๋? :')
for i in a :
if i == a[0] :
print(success)
else :
print(failed)
print(ends) |
student = []
#
# for i in range(5) :
# scores = int(input('ํ์' + str(i+1) + 'student score : ')
# student.append(scores)
# print(sum/len(student))
#
b = input('ํ์ ์ ์
๋ ฅ : ')
scores=[]
sum_s = 0
for i in range(int(b)) :
score = input('ํ์' + str(i+1) + ' ์ ์ ์
๋ ฅ : ')
scores.append(score)
for s in scores :
... |
def showinfo() :
print('ํ๊ธธ๋')
print('20')
print('010-1234-1234')
showinfo()
# ์ฒซ๋ฒ์งธ ๋ฐฉ๋ฒ
def sum(n1,n2) :
print(input('์ซ์1 ์
๋ ฅ : %d \n์ซ์2 ์
๋ ฅ : %d \nํฉ : %d ' % (n1, n2, n1+n2) ))
# ๋๋ฒ์งธ ๋ฐฉ๋ฒ
def sum1(n1,n2) :
print('ํฉ :', n1+n2)
n1 = int(input('์ซ์1 ์
๋ ฅ : '))
n2 = int(input('์ซ์2 ์
๋ ฅ : '))
sum1(n1,n2)
# ์ธ๋ฒ์งธ... |
# ์ํ์ ๋ฆฌ์คํธ์ ์ถ๊ฐ
# ์ํฐํค ๋๋ฅด๋ฉด ์
๋ ฅ ์ข
๋ฃ๋๊ณ ๋ฑ๋ก๋ ์ํ ๋ฆฌ์คํธ ์ถ๋ ฅ
products = []
while True :
product = input('์ํ๋ฑ๋ก(์ํฐํค๋ง ๋๋ฅด๋ฉด ์ข
๋ฃ) : ')
if product == '' :
break
products.append(product)
print('๋ฑ๋ก๋ ์ํ : ', end=' ')
for product in products :
print(product, end=' ')
nums =[1,2,3,4]
nums[2:2] = [90,91]
print(nums)
|
# ๋๋ค์ซ์ ์์ฑ(๋์).py
# ํ์ด์ฌ์์ ๋์(random number) ์ฌ์ฉํ๊ธฐ ์ํด์๋ ๋ชจ๋(random)์ ์ฌ์ฉํด์ผ ํจ
# random ๋ชจ๋์ randint() ํจ์๋ฅผ ์ด์ฉํด์ ๋์๋ฅผ ๋ฐ์์์ผ ๋ด
# randint(์ต์, ์ต๋)
# ์ต์๋ถํฐ ์ต๋ ์ฌ์ด์ ์์์ ์ ์ ๋ฐํํด์ฃผ๋ ํจ์
# ๋ชจ๋์ ํ๋ก๊ทธ๋จ ์์ผ๋ก ๊ฐ๊ณ ์์ผ ํจ
# from random import randint
# n = randint(1,100) - 1๋ถํฐ 100 ์ฌ์ด์์ ์์ ์ซ์ ํ๋๋ฅผ ๋ฐํ
from random import randint
n = randint(1,100)
print(n)
... |
#Funciones de conversion de Decimal a Binario/Octal/Hexadecimal
def decimalabinario(a):
binario = []
while a > 0:
binario.insert(0, a % 2)
a = a // 2
binario = "".join(str(i) for i in binario)
return(binario)
def decimalaoctal(b):
octal = []
while b > 0:
octal.insert(0, b % 8)
b = b // 8
oc... |
from dataclasses import dataclass
@dataclass
class Triangle(object):
height: int = 0
width: int = 0
def print_area(self) -> None:
print(f'triangle area is: {self.height * self.width / 2}')
def initilise() -> Triangle:
return Triangle |
def split_and_join(line):
return(line.replace(" ", "-"))
# new_s = ""
# for i in line:
# if (i == " "):
# new_s += "-"
# else:
# new_s += i
# return(new_s)
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result)
|
# This will be more of proof of concept to figure out if keying in the model and allowing users
# to play around with the variables to get the model on different steady states. we will see. :)
# pretty sure I'm doing this wrong. Need to reference my notes on Recursive dynamic programming.
class model:
def __init__... |
"""Implement quick sort in Python.
Input a list.
Output a sorted list."""
def quicksort(array):
quick(array,0,len(array)-1)
print "ok"
return []
def partition(Array,low,up):
i = low+1
j = up
pivot = Array[low]
while(i<=j):
while(Array[i]<pivot and i<up):
i = i+1
while(Array[j]>pivot):
j = j-... |
import random
print("***** RANDOM NUMBER GUESSING GAME *****")
print("\n")
print("I'm thinking of a number between 1-10.")
print("Can you guess it?")
my_number = random.randint(1,10)
your_number = input("Try below: \n")
while (your_number != my_number):
your_number = input("Try again: \n")
if (your_number == my_n... |
print "You are transported to Victorian England. You are now in a room with Mr. Darcy. What do you do? Do you..."
print "1. Kiss him."
print "2. Shoot him with a revolver."
decision = raw_input("> ")
if decision == "1":
print "You have uncovered the secret to happiness! You are now Mrs. Darcy and will inherit Pemb... |
num1, num2 = raw_input("Enter a number and a divisor.").split()
num1 = int(num1)
num2 = int(num2)
if num2 == 0:
raise ValueError('Cannot divide by zero')
if num1 % num2 == 0:
print("Divides perfectly!")
else:
print("Oops! Still a remainder.")
|
from copy import deepcopy
def solveBackTrack(A, D, R2, R1, order):
#remove the unity restrictions from D
#print("D: ", D)
D = constrictR1(D, R1, order)
print("D after unity constriction: ", D)
AC3(order, D, R2)
print("D after AC3: ", D)
s = backTrack(A, D, R2, order)
return s
def backTrack(A, D, R2, order):
... |
# Sam Goodin 9/15/17
# Lab Assignment Week 4
# To be checked-off
# The use of min, max, sum, map, etc. functions that would be deemed shortcuts is prohibited
#
# Please call the function at the bottom of the code and print the result.
# None of the functions should call PRINT
#
# Created by Larry Gates
# Please commi... |
#Sam Goodin 9/15/17
#Sums all numbers in a list using a for-loop
def sumListFor(aList):
result = 0
for number in aList:
result += number
return result
aL = [1, 2, 3, 4]
result = sumListFor(aL)
print("Adding list: " + str(result))
# Multiply the numbers in a list together using a while-loop
def ... |
while 0 < 1:
bloodType = (input("What is your blood type? ")).lower()
if bloodType == "a+":
print("You can donate to A+ or AB+!")
elif bloodType == "a-":
print("You can donate to A+, A-, AB+, and AB-!")
elif bloodType == "b+":
print("You can donate to B+ or AB+!")
elif blood... |
class Car:
"""
Class to represent the make, model, and year of a car
"""
def __init__(self, theMake, theModel, theYear):
"""
Takes in a string for the make, the model, and int representing the year
"""
self.make = theMake
self.model = theModel
self.year =... |
date = 15
if date == 1:
print("start your new month")
elif date == 30:
print("end your month")
else:
print("enjoy your day")
#ternary
mydate = 15
myword = "start or end of your month" if mydate == 1 or mydate == 30 else "enjoy your day"
print(myword)
a = 3
a = 7 if 3**2 > 9 else 14
print(a) |
def Reverse(head):
q = p = head
while p != None:
q = p
p = p.next
q.next = q.prev
q.prev = p
return q |
"""
You are given a list of size N, initialized with zeroes.
You have to perform M operations on the list and output the maximum of final values of all the elements in the list.
For every operation, you are given three integers a, b and k and you have to add value k to all the elements ranging from index a to b(both... |
from tkinter import *
import LTAT
window = Tk()
window.title("Lets Take A Trip")
window.geometry('350x300')
lbl = Label(window, text="Starting Location")
lbl.grid(column=0, row=0)
start = Entry(window,width=30)
start.grid(column=1, row=0)
lbl = Label(window, text="Ending Location")
lbl.grid(column=0, row=1)
end = E... |
# Iterable protocol: can be called by iter() to get an iterator
# Iterator protocol: can be called by next() to fetch the next item
my_iterable = [1, 2, 3, 4]
my_iterator = iter(my_iterable)
print(my_iterator.__next__())
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
# print(next(my_iterat... |
# strings are homogeneous immutable sequence of unicode chars
# the common usage with the other languages:
print("len('English'):", len('English'))
# Strings are immutable so += re-binds variables reference to a new var. This may cause performance degradation
print("'Eng' + 'lish':", 'Eng' + 'lish')
print("names = ', ... |
from pprint import pprint
letters = ['a', 'b', 'c']
numbers = [1, 2, 3]
combined = [letters, numbers]
print("combined:")
pprint(combined, width=20)
print("----zipped_with_index----")
zipped_with_index = zip(combined[0], combined[1]) # manually select the inner lists with index
for item in zipped_with_index:
pr... |
from typing import Callable
def first_name(name):
""" Normal function statement """
return name.split()[0]
# Lambdas are actually of type Callable
func1: Callable[[str, int], str] = lambda name, age, : name.split()[-1]
func2: Callable[[], None] = lambda: print("I take no arguments and products no returns")
... |
class Point1D:
def __init__(self, x):
self.x = x
class Point2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
"""
Supports str(object) method
str() produces a readable, human-friendly representation of an object (not programmer orientat... |
class ShippingContainer:
next_serial = 100
def __init__(self, owner_code, content):
self.owner_code = owner_code
self.content = content
self.serial = ShippingContainer._get_next_serial()
@classmethod
def _get_next_serial(cls):
result = cls.next_serial
cls.next_s... |
x=raw_input("Enter the number: ")
x=int(x)
try:
x != 0
y= 10 / (x*1.0)
print y
except:
print '0 is not accepted'
|
def strange_algo(x, y):
z = 0
step = 0
while x != 0:
step += 1
some = (x % 2)*" not"
print(f"x={x} y{some}={y} z={z}")
if x % 2 == 1:
z = z + y
x = x // 2
y = y * 2
some = (x % 2)*" not"
print(f"x={x} y{some}={y} z={z}")
print(f"Z={z}... |
import random as rand
from error import Error
import card as cardManager
class Player:
def __init__(self,socket):
"""Constructor for player"""
self.playerid = 0 # player id for attack/defend
self.currentHand = [] # store current cards in hand
self.AI = False # future implementations... |
class MatrixFunctions(self):
def __init__(self, a, b):
self.a=a
self.b=b
def matrixaddf(self):
c=[[],[],[]]
for i in range(0,3):
for j in range(0,3):
z=self.a[i][j]+self.b[i][j]
c[i].append(z)
return c
def mat... |
class Gizmo:
def __init__(self):
print('Gizmo is: %d' %id(self))
x = Gizmo()
def ct(name):
print(name)
cx = ct
print(id(cx), id(ct))
print(cx is ct, cx == ct)
print(dir(Gizmo)) |
# List: []
# Dictionary: {}
# Tuple: ()
# Tuple: immutable
# List: mutable
post = ('Python Basics', 'Intro guide to python', 'Some cool python content')
# Tuple unpacking
title, sub_heading, content = post
# Equivalent to Tuple unpacking
# title = post[0]
# sub_heading = post[1]
# content = post[2]
print(title)
p... |
"""
Assignment: Names
Write the following function.
Part I
Given the following list:
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
C... |
def fizzbuzz():
# loop from 0 to 100
for i in range(101):
#as we loop, check if number is evenly divisible by 3
if i % 3 == 0 and i % 5 == 0:
print "fizzbuzz"
elif i % 3 == 0:
print "fizz"
elif i % 5 == 0:
print "buzz"
else:
... |
""" Creates an index of all the files contained in the path's folder and subfolders.
The module creates an list of dicts representing all the files in the folder and subfolders
of the path provided. That index can then be filtered and dumped in a csv file.
Typical usage:
index = Indexer("../")
index.create_index(min... |
strings = input().split(' ')
search_word = input()
palindrome_list = []
for word in strings:
if word == word[::-1]:
palindrome_list.append(word)
print(f'{palindrome_list}\nFound palindrome {palindrome_list.count(search_word)} times')
'''
wow father mom wow shirt stats
wow
#['wow', 'mom', 'wow', 'stats... |
grade = float(input())
print('Excellent!' if grade >= 5.5 else '')
|
row, col = input().split(', ')
matrix = [[int(col) for col in input().split(', ')] for _ in range(int(row))]
print(sum([sum(row) for row in matrix]))
print(matrix)
'''
3, 6
7, 1, 3, 3, 2, 1
1, 3, 9, 8, 5, 6
4, 6, 7, 9, 1, 0
''' |
loop = int(input())
num_list = [int(input()) for _ in range(loop)]
print(f'Max number: {max(num_list)}\nMin number: {min(num_list)}')
'''
5
10
20
304
0
50
#Max number: 304
#Min number: 0
'''
|
#! /usr/bin/env python3
from __future__ import annotations
import Matrix2
import typing
class Vector2:
def __init__(self, x: float = 0, y: float = 0):
self.x = x
self.y = y
def __add__(self, other: Vector2) -> Vector2:
return Vector2(self.x + other.x, self.y + other.y)
def __sub__(self, ot... |
first = input('Enter first number ')
second = input('Enter second number ')
if first > second:
print(first)
else:
print(second) |
"""
Use a function to find the determinants of any size matrix.
Uses raw python.
The same functionality is available in numpy.linalg.det
"""
from itertools import repeat
from typing import List
def find_determinant(matrix: List[List[int]], expansion_row: int=None) -> int:
"""
Find the determinant... |
# L8 PROBLEM 5
def dToB(n, numDigits):
"""requires: n is a natural number less then 2**numDigits
returns a binary string of length numDigits representing the
decimal number n."""
assert type(n) == int and type(numDigits)==int and n >= 0 and n < 2**numDigits
bStr = ''
while n > 0:
n = n//2
while numDigits - le... |
#!/usr/bin/env python
"""
@author: jstrick
"""
import argparse
parser = argparse.ArgumentParser("A Celsius-to-Fahrenheit converter")
parser.add_argument('ctemp',type=float, metavar='CELSIUS-TEMPERATURE')
args = parser.parse_args()
ftemp = ((9 * args.ctemp) / 5 ) + 32
print("{0:.1f} C is {1:.1f} F".format(args.cte... |
#!/usr/bin/env python
"""
@author: jstrick
Created on Wed Mar 20 07:55:25 2013
"""
from datetime import datetime as DateTime
event = DateTime(2012,7,4,11,15)
print(event)
print()
print('{0:%A, %B %d, %Y}'.format(event))
print('{0:%m/%d/%y %I:%M %p}'.format(event))
|
#!/usr/bin/env python
# (c)2015 John Strickler
import re
alice_text = '''
of getting up and picking the daisies, when suddenly a White
Rabbit with pink eyes ran close by her.
There was nothing so VERY remarkable in that; nor did Alice
think it so VERY much out of the way to hear the Rabbit say to
itself, `Oh dear! ... |
#!/usr/bin/env python
class UnknownKnightError(Exception):
pass
class Knight(object):
def __init__(self,name):
self._name = name
try:
with open('../DATA/knights.txt') as K:
for line in K:
(name,title,color,quest,cmt) = line[:-1].split(":")
... |
#!/usr/bin/env python
from random import randint
for i in range(10):
num = randint(1,15)
print('*' * num)
|
#!/usr/bin/env python
class Animal(object):
def __init__(self,species,name,sound):
self._species = species
self._name = name
self._sound = sound
@property
def species(self):
return self._species
@property
def name(self):
return self._name
def m... |
#!/usr/bin/env python
# (c)2015 John Strickler
import re
# text from www.pigeon.org
pigeon_racing = '''
You can seek out your own comfort level with the birds. If you desire a lower-key approach,
with only a handful of homing pigeons for the family to enjoy, that's certainly an
attractive approach for many. The spectr... |
# Comprehension is a compact way of creating a python data structure from iterators
# List comprehension is a way to build a new list by applying an expression to each item in an iterable
# common way
name = "MadhuSudhanaRaju"
new_list = []
for item in name:
new_list.append(item)
print(new_list)
# pythonic way
ne... |
# -----------
# User Instructions:
#
# Modify the the search function so that it returns
# a shortest path as follows:
#
# [['>', 'v', ' ', ' ', ' ', ' '],
# [' ', '>', '>', '>', '>', 'v'],
# [' ', ' ', ' ', ' ', ' ', 'v'],
# [' ', ' ', ' ', ' ', ' ', 'v'],
# [' ', ' ', ' ', ' ', ' ', '*']]
#
# Where '>', '<', '^',... |
# ํ์ด์ฌ๊ณผ ๊ฐ์ ๋ช๋ช ํ๋ก๊ทธ๋๋ฐ ์ธ์ด๋ Pothole_case ๋ฅผ ๋ ์ ํธํ๋ ์ธ์ด๋ผ๊ณ ํฉ๋๋ค.
#
# Example:
#
# codingDojang --> coding_dojang
#
# numGoat30 --> num_goat_3_0
#
# ์ ๋ณด๊ธฐ์ ๊ฐ์ด CameleCase๋ฅผ Pothole_case ๋ก ๋ฐ๊พธ๋ ํจ์๋ฅผ ๋ง๋ค์ด์!
def CameleCase_to_Pothole_case(cc):
pc=''
for c in cc:
if c.isupper():c='_'+c.lower()
elif c.isdigit():c='_... |
# def facto(n):
# if n==1: return 1
# return n*facto(n-1)
#
# print(facto(6))
# def arr_gen(n):
# arr=[]
# for i in range(n):
# arr.append(i)
# yield(arr)
#
# for x in arr_gen(10):
# print(x)
# def fibonacci(n):
# """Ein Fibonacci-Zahlen-Generator"""
# a, b, counter = 0, 1... |
def insertion_sort(A,n):
for i in range(1,n):
print(i)
key=A[i]
j=i-1
while j>=0 and A[j]>key:
A[j+1]= A[j]
j=j-1
A[j+1]=key
|
def recursive_linear_search(A,n,i,x):
if i>=n:
return "NOT FOUND"
elif A[i]==x:
return i
else:
return recursive_linear_search(A,n,i+1,x)
A=[1,2,3,4,5]
print(recursive_linear_search(A,len(A),0,6)) |
class Phone:
def __init__(self, brand, price):
self.brand = brand
self.price = price
def __call__(self, phoneNumber):
print(f"{self.brand} is calling")
def __str__(self) -> str:
return f"Brand{self.brand}Price = {self.price}"
iphone = Phone("Iphone 7+", 300)
samsung = Ph... |
#Naive approach
def max_prod_naive(arr):
product = 0
for i in range(len(arr)):
for j in range(i+1,len(arr)):
product = max(product,arr[i]*arr[j])
return product
#Fast approach
def max_prod_fast(arr):
p1 = max(arr)
arr.remove(p1)
p2 = max(arr)
return p1*p2
#Stress test
fro... |
num1 = int(input(" Informe un numero qualquer:"))
num2 = int(input(" Informe outro numero qualquer:"))
escolha = 0
while escolha != 5:
print('-'*20)
print(' [1] soma\n',
'[2] multiplicaรงรฃo\n',
'[3] maior\n',
'[4] novos numeros\n',
'[5] sair\n')
print('-'*20)
esco... |
from random import randint
lista = (randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10))
print('Os numeros sortiados foram:', end=" ")
for c in lista:
print(f'{c}',end=" ")
print(f'\nO maior numero sorteado foi {max(lista)}')
print(f'O menor numero sorteado foi {min(lista)}')
|
print('\033[0;33;40m*-\033[m'*20)
print(' Analisador de frase ')
print (' ------PALINDROMO-------')
print('\033[0;33;40m*-\033[m'*20)
frase = str(input(' Digite uma frase \n')).strip().upper()
separar = frase.split()
junto = ''.join(separar)
inverso = ''
for letra in range(len(junto) -1,-1,-1):... |
lista = []
impar = []
par = []
while True:
num = int(input('Informe um numero inteiro:'))
lista.append(num)
if num%2 ==0:
par.append(num)
else:
impar.append(num)
stop = str(input('Deseja continuar inserindo numeros em sua lista?[S/N]')).upper().strip()[0]
while stop not in 'SN':
... |
numero = int(input('Digite um numero de 0 a 9999: \n'))
unid = numero // 1 % 10
dez = numero // 10 % 10
cen = numero // 100 % 10
mil = numero // 1000 % 10
print(' Analisando o numero {} '.format(numero))
print(' Unidade : {}'.format(unid))
print(' Dezena : {}'.format(dez))
print(' Centena : {}'.format(cen))
print(' Mi... |
num1 = int(input('Informe um numero inteiro \n'))
num2 = int(input('Informe outro numero inteiro \n'))
if num1 > num2:
print(' O primeiro numero {} รฉ maior que o segundo numero {}'.format(num1,num2))
elif num2 > num1:
print(' O segundo numero {} รฉ maior que o primeiro numero {}'.format(num2,num1))
else:
pr... |
from datetime import date
ano = int(input('Informe o ano em que vocรช nasceu: \n'))
idade = (date.today().year )-ano
tempo = idade - 18
tempo1 = 18 - idade
if idade == 18:
print('Parabens! Vocรช esta no periodo de alistamento')
elif idade > 18:
print('Vocรช jรก passssou do periodo de alistamento a {} anos'.form... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
# ๆฐๆฎ
x = [1, 2, 3]
y = [7, 2, 9]
x2 = [1, 2, 3]
y2 = [10, 20,2]
# ๅฎไนๆฐๆฎๆ ็ญพ
plt.plot(x, y, label = "First one")
plt.plot(x2, y2, label = "Second one")
# ๅฎไนๅพๆ ๆจช็ซ่ฝดๆ ็ญพ๏ผๅพๆ ๅ็งฐ
plt.xlabel('Plot number')
pl... |
# Sum of Array Element
def sumArrayElement(arry, n):
s = 0 # Variable
for i in range(0, n): # Loop for array summation
s = s + arry[i] # Sum the current array element with right element
print("%d " % s) # Print the results
arry = [9, 3, 5, 2, 6, 8] # Given Array
n = 6 # Given Frequency... |
""" Program to read data from file, process it
and draw graphs using matplotlib
Appropriate titles should be given
and axis should be labeled
Author: Varun Aggarwal
Username: aggarw82
Github: https://github.com/Environmental-Informatics/08-time-series-analysis-with-pandas-aggarw82
"""
i... |
age = int(input("Please enter your age:"))
if age>= 21:
print('yes,you can.')
else:
print('No,you can\'t. Idiot.')
|
#Give the absolute Value of X
def my_abs(x):
print(abs(x))
#Try it, fill in the blank!
my_abs(-3)
#Solve for x in 0 = ax**2+by+c
def quadratic(a, b, c):
X1 = ((-1*b + ((b**2)-4*a*c))**.5)/(2*a)
X2 = ((-1*b + ((b**2)-4*a*c))**.5)/(2*a)
if X1 ==complex:
print ('no solution')
else:
... |
class City:
def __init__(self, passing_name = "Unknown", pop = 0, gdp = 0):
self.name = passing_name
self.population = pop
self.gdp_per_capita = gdp
def __str__(self):
return "{} has {} people, with gdp per capita of ${}.".format(self.name, self.population,self.gdp_per_capi... |
def sed(pattern, replace, source, dest):
"""Reads a source file and writes the destination file.
In each line, replaces pattern with replace.
pattern: string
replace: string
source: string filename
dest: string filename
"""
f1 = open(source)
f2 = open(source, 'w')
for line in f... |
def factor(n):
#Housekeeping--> Make sure the numbers entered are integers and above zero.
if not int(n)==n and n>=0:
print("Positive and whole number please.")
#Run a loop that stops at the number divided by any number up to itself.
#If the remainder of dividing the original number by the test... |
from threading import Lock
class FileFifo:
def __init__(self, filename):
self.filename = filename
self.lock = Lock()
try:
f = open(filename,'w')
f.close()
except:
print("impossibile aprire o creare il file")
raise
def append(self,... |
# Crie um programa que pergunte o nome de um funcionรกrio, seu salรกrio atual e uma alรญquota de aumento
# em seguida este programa deve retornar o novo salรกrio com o reajuste solicitado
print('=' * 40)
print('{:^40}'.format('Reajuste salarial'))
print('=' * 40)
nome = str(input('Informe o nome do funcionรกrio: '))
salar... |
#!/usr/bin/python3
N = 15
# The main routine of AI.
# input: str[N][N] field : state of the field.
# output: int[2] : where to put a stone in this turn.
def Think(field):
CENTER = (int(N / 2), int(N / 2))
flg=0
flg2=0
best_position = (0, 0)
#best_position2 = nul
for i in range(N):
for ... |
# coding: utf-8
# # Chapter 1: Computing with Python
# ### Overview: a typical Python-based scientific computing stack.
# 
#
# * Resources:
# - [SciPy](http://www.scipy.org)
# - [Python Numeric & Scientific topics](http://wiki.python.org/moin/NumericAndScientific)
... |
#Import the modules we need
import turtle
import random
#Create a screen
win = turtle.Screen()
#Draw a finish line
naychelle = turtle.Turtle()
naychelle.color("red")
naychelle.penup()
naychelle.goto(150,300)
naychelle.pendown()
naychelle.right(90)
naychelle.forward(500)
#Create two turtles and give them colors and ... |
# On a pour depart, un chiffre aleatoire qui est choisi
# apres, le jeu nous demande de taper un nombre entre 0 et 100
# si la reponse est inerieur au nombre aleatoir
# il doit afficher "le nombre est plus grand"
# si la reponse est superieur au nombre aleatoire
# il doit afficher "le nombre est plus petit"
# et sinon,... |
#!/bin/python3
import os
import sys
#
# Complete the diagonalDifference function below.
#
def diagonalDifference(a):
#
# Write your code here.
#
#n = int(input())
total1 = 0
total2 = 0
for i in range(n):
total1 += a[i][i]
total2 += a[i][n-i-1]
ret... |
from typing import List
class A:
x: int
def __init__(self, x):
print('creating A')
self.x = x
def foo(self):
self.x += 1
class B(A):
y: int
def __init__(self, y):
super().__init__(2 * y)
self.y = y
def goo(self):
self.foo()
def foo(sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.