text stringlengths 37 1.41M |
|---|
def intervalo(numero):
if (numero >= 0 and numero <= 25):
return "Intervalo [0,25]"
elif (numero >25 and numero <=50):
return "Intervalo [25,50]"
elif (numero>50 and numero<=75):
return "Intervalo [50,75]"
elif (numero>75 and numero<=100):
return "Intervalo[75,100]"
e... |
# #day01通过代码获取两段内容,并且计算他们长度的和
# a = len(input("请输入a的值:"))
# print("a的长度:",a)
# b = len(input("请输入b的值:"))
# print("b的长度:",b)
# print("字段长度和",a+b)
#day02在字典里输入name、age、sex
d = {}
print(d)
a= input("请输入姓名:")
b = input("请输入年龄:")
c = input("请输入性别:")
d.update(name=a)
d.update(age=b)
d.update(sex=c)
print(d) |
#Stephen Bowen 2020
import string
asciiString = string.ascii_lowercase
alternatives = ('0','1','2','3','4','5','6','7','8','9','!','@','#','$','%','^','&','*','(',')','-','=','<','>','?','=')
masterCipher = {asciiString[i] : alternatives[i] for i in range(len(asciiString))}
inverseCipher = {y : x for x , y in masterCi... |
#Stephen Bowen 2020
def display_list(SortOrder, foodList):
print(SortOrder)
print(*foodList, sep='\n')
foods = ['pizza','salad','hamburger','steak','apple','orange']
display_list("foods in original order:", foods)
foods.sort()
display_list("foods in ascending alphabetical order:", foods)
foods.sort(reverse... |
name = input("Cual es tu primer nombre?")
name += " " + input("Cual es tu segundo nombre?")
name += " " + input("Cual es tu primer apellido?")
name += " " + input("Cual es tu segundo apellido?")
year = input("En que año naciste?")
print("Hola " + name)
print("Probablemente tienes " + str(2019-int(year)) + " años") |
#!/usr/bin/env python
#!coding=utf-8
print('''
\t \t *** CALCULADORA ***
Ingresa la letra que corresponda a la opcion deseada
\t a. Sumar
\t b. Restar
\t c. Dividir
\t d. Multiplicar
''')
option = input()
if not((option == 'a') or (option =='b') or (option =='c') or (option =='d')):
# print(type (op... |
name = "Monika"
age = 34
fav_color = "green"
print("My name is {}".format(name))
print("I am {} years old".format(age))
print("My favourite color is {}".format(fav_color))
#oprion 2
print("My favourite color is " + fav_color) |
#!/usr/bin/env python3
# GS-Shapley Algorithm
# Created by: Akshay Singh and
# Date: 09/20/2017
# Purpose: It creates pairs of men and women
# using gale-shapley alroithm.
# INPUT(S): None
# OUTPUT(S): Participants
# Preferences
# Pairing
# CPU Time and CLock Time
# EXAMPLES:
# Sahr :Erik... |
l1=[1,5,7,3,9]
l2=[2,4,8,1,9]
a=set(l1)
b=set(l2)
c=a.intersection(b)
if(c!=0):
print("values occur in both the list are ",c)
|
import csv
f=open("flowers.csv","w")
writer=csv.DictWriter(f,fieldnames=["flower","count"])
writer.writeheader()#writeheader() write headers to the csvfile
writer.writerow({"flower":"rose","count":"1"})
writer.writerow({"flower":"lilly","count":"2"})
writer.writerow({"flower":"lotus","count":"3"})
writer.writero... |
s1=str(input("enter 1st string : "))
s2=input("enter 2nd string : ")
a=s1[1:]
b=s2[1:]
print("The new string formed : ",s2[0]+a+" "+s1[0]+b)
|
#!/usr/bin/env python3
# return input
def load_data(filename):
file = open(filename, "r")
data = 0
for line in file:
data = int(line)
file.close()
return data
# return tuple (digit of tens, digit of ones)
def get_digits(number):
return (int(number / 10) % 10, number ... |
def eggs(eggs_of_gold, eggs_not_of_gold):
print(f"You have {eggs_of_gold} golden eggs!")
print(f"You have {eggs_not_of_gold} eggs to eat!")
print("Golden geese what a pain\n" )
print("We can just give the function numbers directly:")
eggs(1, 900)
print("Or, we can use variables from our script:")
eggs_o... |
def save_file(results, file_path):
# Create File Object
f = open (file_path, 'w')
# Write Results
f.write (results)
# Close File Object
f.close ()
def open_file(file_path):
# Create File Object
f = open (file_path, 'r')
# Read File Contents
file_contents = f.read (... |
# Prompt the user for input
j = input('Enter a value for j: ')
for k in range(((j + 13) / 27), 11, 1):
i = 3 * k - 1
print ('i: ' + str(i))
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
num = raw_input()
array = raw_input()
array = array.split()
sum1 = 0
array = map(int,array)
print sum(array)
|
#! /usr/bin/python
import numpy as np
from scipy import linalg as la
class Molecule:
"""
implements the basic properties of a molecule
"""
def __init__(self, geom_str, units="Angstrom"):
self.read(geom_str)
self.units = units
def read(self, geom_str):
"""
Read in ... |
''' Linear Search '''
def linearSearch(list, target):
for i in range(len(list) -1):
# if the target is int the ith element, return True
if list[i] == target:
return True
return False # If not found, return false
list = [12, 5, 13, 8, 9, 65]
print linearSearch(list, 5)
|
# Linked-List Queues #
def Enqueue(top_sentinel, new_value):
# Make a cell to hold the new value
new_cell = New Cell
new_cell.value = new_value
# Add the new cell to the linked list
new_cell.next = top_sentinel.next
top_sentinel.next = new_cell
new_cell.prev = top_sentinel
def Dequeu... |
# Randomizing Arrays
import random
def RandomizeArray(myList): # Needs to take list
max_i = myList[len(myList) - 1]
print(myList)
print(max_i)
print(len(myList))
i = 0
for i in range(len(myList)):
j = random.randint(i,(len(myList) - 1))
temp = myList[i]
myList[i] = myLi... |
# One Dimensional Arrays(Lists in Python):
''' In Python there is no specific data structures called arrays '''
''' We are using lists instead of arrays '''
''' Finding Items in List '''
def IndexOf(list, target):
for i in range(len(list)):
if list[i] == target:
retur... |
''' Implementation of the Map ADT using closed hashing and a probe with double hashing '''
from arrays import Array
class HashMap:
# Define constants to represent the status of each table entry.
UNUSED = None
EMPTY = _MapEntry(None, None)
# Creates an empty map instance.
def __init__(self):
... |
# Using Python
# This is for already defined 2 values
'''def GCD(a, b):
while (b != 0):
remainder = a % b
a = b
b = remainder
return a
'''
# We are asking user to put input
a = input()
b = input()
# Returns the greatest common divisor of two numbers
def GCD(a,b):
while(b != 0):
... |
author: @nadide
from math import sqrt
def FindPrimes (max_number):
is_composite = []
for i in range(4,max_number+1,2):
is_composite[i] = True
next_prime = 3
stop_at = int(sqrt(max_number))
while (next_prime < stop_at):
#print next_prime
for i in range(next_prime*2,max_numb... |
# Copied from internet, Author name is below:
__author__ = "Adam Traub"
__date__="2/16/2011"
class LinkedList:
'''Linked List'''
class __Node:
'''
private node object. Node's consist of an element
and a pointer to the previous and next Node'''
def __init__(self, element=None):
sel... |
import webbrowser
webbrowser.open("http://www.codeskulptor.org/#user40_RrB5gcTvcf0aDLs.py")
# Rock-paper-scissors-lizard-Spock
# In our first mini-project, we will build a Python function rpsls(name) that takes
# as input the string name, which is one of "rock", "paper", "scissors", "lizard",
# or "Spock". The... |
'''
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
'''
# Definition for sin... |
"""
Given the pointer/reference to the head of a singly linked list, reverse it and return the pointer/reference to the head of reversed linked list.
Consider the following linked list.
head -> 7 -> 14 -> 21 -> 28 -> NULL
Return pointer to the reversed linked list as shown in the figure.
head -> 28 -> 21 -> 14 -> 7 -... |
'''
Given a linked list, remove the n-th node from the end of list and return its head.
Note that the given n will always be valid.
Example:
Given 1->2->3->4->5, and n = 2.
Return 1->2->3->5
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
... |
'''
Given an almost sorted array, in which each number is less than m spots array from its correctly sorted position, and
the value m, write an algorithmn that will return an array with the element properly sorted.
An example input would be the list [3, 2, 1, 4, 6, 5] and m = 3. In the example, each element in the arr... |
# Write a function that takes a string as input and returns the string reversed.
# Example:
# Given s = "hello", return "olleh".
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
def reverse(arr):
start, end = 0, len(arr) - 1... |
"""
Given the head of a singly linked list and 'N', swap the head with Nth node. Return the head of the new linked list.
Original linked list: 7 -> 14 -> 21 -> 28 -> 35 -> 42 -> Null
N = 4
After swaping: 28 -> 14 -> 21 -> 7 -> 35 -> 42 -> Null
Hint: Find (N-1)th node
"""
# Definition for singly-linked list.
class L... |
'''
Write a heap class that represents a minimum heap using an array. Implement the insert method for this min heap class.
min_heap = MinHeap()
min_heap.insert(2)
min_heap.insert(4)
min_heap.insert(1)
# Underlying array should look like: [1, 4, 2]
If time permits, implement the delete_min() method.
'''
# class MinH... |
# Given a string, determine if it is a palindrome, considering only alphanumeric
# characters and ignoring cases.
# For example,
# "A man, a plan, a canal: Panama" is a palindrome.
# "race a car" is not a palindrome.
# Note:
# Have you consider that the string might be empty? This is a good question to ask
# during a... |
# You are climbing a stair case. It takes n steps to reach to the top.
# Each time you can either climb 1 or 2 steps. In how many distinct
# ways can you climb to the top?
# Note: Given n will be a positive integer.
# Example 1:
# Input: 2
# Output: 2
# Explanation: There are two ways to climb to the top.
# 1.... |
string=input()#Enter your statement
count1=0
count2=0
for i in string:
if(i.isupper()):
count2=count2+1
elif(i.islower()):
count1=count1+1
print(count2,count1)#print no of uppercase in your statement
#print(count1)#print no of lowercase in your statement |
import matplotlib.pyplot as plt
plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],
label="BMW",color='b',width=0.5)
plt.bar([0.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],
label="AUDI",color='r',width=0.5)
plt.legend()
plt.xlabel("Days")
plt.ylabel("Distance(kms)")
plt.title("Information")
plt.show() |
# meow.c
# for i in range(3):
# meow()
# def meow():
# print("meow")
# this (above) is the incorrect because python doesn't know the
# function before it is called.
# the proper way is to
def main():
for i in range(3):
meow()
def meow():
print("meow")
main()
|
import requests
import json
userDetails = [["hit","h@123.com",855,"pkg","Hitesh Subnani"],["kj","kj@kj.com",966,"kj","Karina Jangir"]]
def location():
place = input("Search a Place : ").strip().lower()
place = place.replace(' ','%20')
url = 'https://maps.googleapis.com/maps/api/geocode/json?key=AIzaS... |
import random
dataset= [['Name','Item','Amount','Unit_Price']]
customers = ['Bettison, Elnora',
'Doro, Jeffrey',
'Idalia, Craig',
'Conyard, Phil',
'Skupinski, Wilbert',
'McShee, Glenn',
'Pate, Ashley',
'Woodison, Annie']
produc... |
# Write a script that will find and print only elements using a suitable operator or method:
# # Common - which have string01 and string02 common.
# Unique - which characters are present in string01 but not in string02.
string01 = 'Bratislava'
string02 = 'Budapest'
common = set(string01) & set(string02)
unique = set(... |
import os.path
path = os.path.dirname(__file__)
# function for read row number
def read_specific_line(file_path, line_number: int) -> None:
with open(file_path) as handler:
current_line = None
current_line_number = 0
while current_line_number < line_number:
current_line = han... |
import datetime # import library datetime
# Greet the client
print("=" * 80)
print("Welcome in Destination \na place to choose a holiday!!!")
print("=" * 80)
# Offer destinations
print("Offer of holiday destinations:")
print("=" * 80)
print("1 - Prague | 1000\n2 - Wien | 1100\n3 - Brno | 2000\n4 - Svitavy... |
# ask the user for a number
# split the given number in halves (e.g. 123456 -> split to 123 and 456, 12345 -> 12 and 345)
# convert both halves into an integer
# if both halves are an even integer, print: 'Success' - e.g. 12 and 34
# if only the first part is even, print: 'First' - e.g. 12 and 345
# if the second part ... |
#test
a = 1
if a == 0:
print("a je 1")
quit()
else: print("a není 1")
print("End")
"""
# In the Python window you already have Mercedes and Rolls-Royce prices listed (don't forget to covert
# string to integer!). In addition, you have to create a variable that will ask the user for the extra cost.
# Th... |
#class Zdravic:
# """ Třída reprezentuje zdravič, který slouží ke zdravení uživatelů
# """
# def __init__(self):
# self.text = None
#
# def pozdrav(self, jmeno):
# """
# Vrátí pozdrav uživatele s nastaveným textem a jeho jménem.
# """
# return '{0} {1}!'.format(self.text,... |
#!python
import anagram_trie
from anagram_trie import AnagramTrie, AnagramTrieNode
class WordScrambleSolver():
"""A class for solving word scambles using an anagram trie"""
def __init__(self, path_to_anagram_trie):
"""Initalize this words scample solver"""
self.anagram_trie = anagram_trie.lo... |
#!python
class Node(object):
def __init__(self, data):
"""Initialize this node with the given data"""
self.data = data
self.prev = None
self.next = None
def __repr__(self):
"""Return a string representation of this node"""
return 'Node({!r})'.format(self.da... |
import random
def quicksort(in_list):
if len(in_list) <= 1:
return in_list # an in_list of zero or one elements is already sorted
less = []
more = []
pivot = random.choice(in_list)
in_list.remove(pivot)
for x in in_list:
if x <= pivot:
less.append(x)
else:
... |
import os
import sys
import importlib
import inspect
from abc import abstractmethod
import chess
from .types import *
from .history import GameHistory
class Player(object):
"""
Base class of a player of Recon Chess. Implementation of a player is done by sub classing this class, and
implementing each of th... |
class Coche():
# Propiedades.
Largo = 250
Ancho = 120
Ruedas = 4
Encendido = False
# Metodos.
def Arrancar(self):
self.Encendido = True
def Estado(self):
if self.Encendido == True:
return "El Coche esta encendido."
else:
return "El Coche esta... |
print ("I will now calculate the area of a triangle:")
print ("The area of a triangle(base=4, height=6):", 0.5*4*6 )
|
import pandas as pd
import numpy as np
import random
import csv
def calculate_euclidean_distance(point_1, point_2):
"""
Given two points (np.array), calculate Euclidean distance
"""
delta = point_1 - point_2
return sum(delta**2)**0.5
def input_reader(filename):
"""
Read input csv file and retur... |
# -.- coding:utf-8 -.-
'''
Created on 2015年11月16日
@author: chenyitao
'''
import random
class CookiesManager(object):
'''
Cookies管理器
'''
def __init__(self):
'''
Constructor
'''
self.cookies = {}
self.history = []
def set_cookies(self, attr_id, action=0, co... |
def filter_long_words(words:list,length:int):
list_of_words:list = []
for word in words:
if len(word) > length:
list_of_words.append(word)
return list_of_words
print(filter_long_words(['testing','ohyeah','ohno'],3)) |
girls = ['younghee', 'chulsoo', 'hooni', 'subi', 'chanwoo', 'hyunwoo']
def hi(name):
print('Hi ' + name + '!')
for name in girls:
hi(name)
print('Next girl')
|
class BST():
def __init__(self,data):
self.data = data
self.left=None
self.right=None
# self.root=None
def Insert(self,data):
if data==self.data:
#as bst doesnt allow duplicate values
return
elif data<self.data:
# add... |
class Node:
def __init__(self,data):
self.data =data
self.next=None
class Stack:
def __init__(self):
self.head=None
def push(self,data):
new_node=Node(data)
if self.head==None:
self.head=new_node
else:
te... |
# This is interval-exchange-o-matic by Marc Culler and Nathan Dunfield
# (mostly all Marc's work). Written for Maryam Mizakhani 2005/2/4
#
# To use, in Terminal go to the directory containing this file, and type
# "python maryam.py" (w/o the quotes).
#
import os, sys, re, random, math, time
# return a parition whe... |
import sqlite3
import sys
# sys.argv is a list of the passed in args from the command line
print(sys.argv)
super_db = '/Users/andrewherring/nss/Backend/python/notes/superheroes.db'
def get_supers():
# shorthand for creating a connection
with sqlite3.connect(super_db) as conn:
cursor = conn.cursor()
# cursor... |
class Animal:
def say_animal(self):
return "I am an animal"
class Animal_Friend:
def say_friend(self):
return "My friend is Mr. Farmer"
class Cow(Animal, Animal_Friend):
def say_cow_thing(self):
print(f"{self.say_animal()} and {self.say_friend()}")
# "I am an animal and my friend is Mr. Farmer"... |
print("This is used to convert miles to kilometers. Please enter the number of miles.")
num = int(input("Please enter a number: "))
kilometercalc = (num * 1.609344)
print("The number of kilometers from what you typed is: ", round(kilometercalc, 2)) |
text = input ("The given text: ")
print("The # of a: ", text.count('a'))
print("The # of b: ", text.count('b'))
print("The # of c: ", text.count('c'))
print("The # of d: ", text.count('d'))
print("The # of e: ", text.count('e')) |
class Solution(object):
def threeSumClosest(self, nums, target):
nums = sorted(nums)
lens = len(nums)
mindist = float("inf")
for i in range(lens-1):
if i != 0 and nums[i] == nums[i-1]: continue
j,k = i+1,lens-1
while j < k:
print i,... |
#Objective
#In this challenge, we learn about normal distributions. Check out the Tutorial tab for learning materials!
#Task
#In a certain plant, the time taken to assemble a car is a random variable, X, having a normal distribution with a mean of 20 hours and a standard deviation of 2 hours. What is the #probability ... |
# A=B-3
a = int(input())
for i in range(a):
b, c = input().split()
b = int(b)
c = int(c)
print(b+c)
|
# 평균
# 세준이의 성적을 위의 방법대로 새로 계산했을 때,
# 새로운 평균을 구하는 프로그램을 작성하시오.
# 점수 list를 생성하고 list 중 최댓값을 추출 = list_score, max_score
# 일반적인 평균과 세준이의 계산법을 적용한 후 평균을 구한다. = before, after_average
# after_average 출력
N = int(input())
list_score = list(map(int, input().split()))
max_score = max(list_score)
before_average = sum(list_sco... |
from search import ROUTE_API
def get_statements_with_value_path(issue_uid: int, search_value: str = '') -> str:
"""
Create the query string to get statements matching a certain string.
This method contains all parameters used in search(service).
:param issue_uid: uid of the issue to search in
:pa... |
#!/usr/bin/python
class Replacee(object):
def __init__(self, value):
self.value = value
def GetValue(self):
return self.value
r = Replacee(2)
print r.value
print r.GetValue()
Replacee.GetValue = lambda _: 3
print r.value
print r.GetValue()
|
class BinaryNode:
left = None
right = None
value = 0
def __init__(self, value):
self.value = value
def getBinaryTree():
root = BinaryNode(20)
# left
nodel = BinaryNode(8)
nodell = BinaryNode(5)
nodelll = BinaryNode(3)
nodellr = BinaryNode(6)
nodell.left = node... |
cities = {}
city_0 = {'country': 'China', 'popu': '13min', 'fact': 'good'}
city_1 = {'country': 'ina', 'popu': '13min', 'fact': 'good'}
city_2 = {'country': 'Ca', 'popu': '13min', 'fact': 'good'}
cities['0'] = city_0
cities['1'] = city_1
cities['2'] = city_2
for city_name in cities.keys():
city_info = cities[city_na... |
def switcher(choice):
case = ""
if choice.islower():
case = "lower"
elif choice.isupper():
case = "upper"
elif choice.isdigit():
case = "digit"
switcher_dict = {
'lower': 'lowercase letter',
'upper': 'uppercase letter',
'digit': 'digit letter'
}
return switcher_dict.get(case, "others")
print(switche... |
def get_list_intersection(list_1, list_2):
return_list = []
for i in list_1:
for j in list_2:
if i == j:
return_list.append(i)
return return_list
list_1 = [1, 2, 3, 4, 5]
list_2 = [3, 4, 5, 6, 7]
print(get_list_intersection(list_1, list_2))
|
foods = ('rice', 'noodle', 'dumplings', 'burger', 'steak')
for food in foods:
print(food)
foods = ('rice', 'chicken', 'fish', 'burger', 'steak')
for food in foods:
print(food) |
# for i in range(1, 21):
# print(i)
# max_list = list(range(1, 1000000))
# print(min(max_list))
# print(max(max_list))
# print(sum(max_list))
# odd_list = []
# for i in range(1,21,2):
# odd_list.append(i)
# for i in odd_list:
# print(i)
# div_list = []
# for i in range(3,31,3):
# div_list.append(i)
# print(div_... |
import csv
# create function to put each col into list
def list_importer(lst, csv_file, col_name):
with open(csv_file) as insurance_file:
insurance_data = csv.DictReader(insurance_file)
for row in insurance_data:
lst.append(row[col_name])
return lst
# In my Python file I crea... |
import random
def add_node(graph, node, S):
if graph.get(node) is None:
graph[node] = [node in S, []]
def add_edge(graph, n1, n2):
graph[n1][1] += [n2]
graph[n2][1] += [n1]
# Question 9.a
def create_fb_graph(S, filename="facebook_combined.txt"):
with open(filename) as f:
lines = f.re... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 16 14:22:57 2020
@author: wangjingxian
"""
#232. 用栈实现队列
'''
使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop()... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 10:25:18 2020
@author: wangjingxian
"""
#189. 旋转数组
'''
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: [1,2,3,4,5,6,7] 和 k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]
示例 2:
输入: [-1,-100,3,99] 和 k = 2
输出: [... |
from string import ascii_lowercase
from string import punctuation
import collections
alphabets = ''.join(list(ascii_lowercase))
monoKey = "hljfrtzyqscnbexvumpaokwdgi" # should converted to user input in gui
length=26
#Should be changed to input in gui
text="one way to solve a encrypted message if we know its language... |
#Напишите программу,
# которая выводит чётные числа из заданного списка и останавливается, если встречает число 237.
import random
a=random.randint(88,300)
list_1=list(range(1,a))
list_1.append(237)
random.shuffle(list_1)
print(list_1)
for i in list_1:
if i % 2 ==0:
print(i)
elif i==237:
print... |
# listas
colores = ["Azul", "Rojo", "Verde", "Amarillo"]
# print(colores)
# imprimir una posicion determinada
# print(colores[1])
# imprimir el ultimo item de la lista
# print(colores[-1])
# imprimir desde la posicion 1 hasta la 3
# print(colores[1:3])
# imprimir desde la posicion 2 hasta el final
# print(colores[2... |
import time
import random
def print_pause(message):
print(message)
time.sleep(2)
# print and sleep 2 sec
def intro():
name = input("What is your name?\n")
# save the random choice to use it later
print_pause("You have arrived at your friend Mohammed's house")
print_pause("You knock on the do... |
import sys # importing system function for exit with error
from math import * # importing math functions
import matplotlib
import matplotlib.pyplot as plt #imprting graph functions
import numpy as np
#main function
def fit_linear(fileName): # main function. this function input is a text file of data and output i... |
'''
Crie um programa que leia dois valores e mostre um menu como abaixo:
[1] Somar
[2] Multiplicar
[3] Maior
[4] Novos números
[5] Sair do programa
Seu programa deverá realizar a operação solicitada em cada caso.
'''
from time import sleep
menu = 0
n1 = 0
n2 = 0
n1 = int(input('Digite um numero: '))
n2 = int(input('D... |
'''
Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre todos
os valores e qual foi o maior e o menor valor lido. O programa deve perguntar ao usuário se ele quer ou não continuar
a digitar valores.
'''
continua = True
soma = media = cont = maior = menor = 0
opcao... |
'''
Refaça o Desafio 035 dos triângulos, acrescetando o recurso de mostrar que tipo de triângulo será formado:
- Equilátero: todos os lados iguais
- Isósceles: doios lados iguais
- Escaleno: todos os lados diferentes
'''
r1 = float(input('Digite o primeiro segmento da reta: '))
r2 = float(input('Digitel o segundo segm... |
'''
Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas lista extras que vão
contar apenas os valores pares e os valores ímpares digitados, respectivamente. Ao final, mostre o conteúdo das
três listas geradas.
'''
numeros = list()
impar = list()
par = list()
while True:
nume... |
''' Faça um programa que calcule a soma entre todos os números impares que são múltiplos de três e que se
encontram no intervalo de 1 até 500. '''
soma = 0
conta = 0
for count in range(1, 501, 2):
if count % 3 == 0:
conta += 1
soma += count
print('A soma de todos os valores {} solicitados é {}'.for... |
''' Desenvolva um programa que leia o primeiro termo e a razão de uma PA.
No final, mostre os 10 primeiros termos dessa progressão '''
primeiro = int(input('Digite o primeiro termo: '))
razao = int(input('Digite a razão: '))
décimo = primeiro + (10 - 1) * razao
for c in range(primeiro, décimo + razao, razao):
pri... |
# Faça um programa que leia um número interio e mostre na tela o seu sucessor e seu antecessor.
n1 = int(input('Digite um numero: '))
#print('O numero digitado foi {}'.format(n1))
#print('Seu sucessor é {} e seu antecessor é {}'.format((n1 + 1), (n1 - 1)))
print('Analisando o numero digitado {}, o seu antecessor é {} ... |
'''
Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com sua idade, se ele ainda vai se alistar ao serviço militar,
se é a hora de se alista ou se já passou do tempo de alistamento.
Seu programa também deverá mostrar o tempo que falta ou que passsou do prazo.
'''
from datetime import date... |
''' Escvreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em
quantos anos ele vai pagar.
A prestação não pode exceder 30% do salário ou então o empréstimo será negado.
'''
vlr_casa = float(input('Qual o valor da casa R$ '))
salario = float... |
#CTI 110
#M6T1 Kilometer Converter
#Jeffrey Lee
# Oct 24 2017
#Write a program that asks the user to enter a distance in kilometers
#then converts that distance to miles
#the conversion formula:Miles = Kilometers * 0.6214
#create two functions for this program
#main() function
#show_miles()function that take... |
#CTI 110
#M6Lab Age and name
#Jeffrey Lee
#1 Nov 2017
#Write a program that will ask the user their name and then ask their age.
#The program should then greet them by name, and tell them their age
#infant, child, teenager, or adult
#main() which is a void function
#greet(name) which is a void function
#ageC... |
import csv, json
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
from tkinter.messagebox import showinfo
# root window
root = tk.Tk()
root.title('CSV to JSON File Dialog')
root.resizable(False, False)
root.geometry('300x150')
def convert(file):
with open(file, encoding='utf-8') a... |
"""
Based on this list of tuples: [(1,2),(2,2),(3,2),(2,1),(2,2),(1,5), (10,4), (10, 1), (3, 1)]
Sort the list so the result looks like this: [(2, 1), (3, 1), (10, 1), (1, 2), (2, 2), (2, 2), (3, 2), (10, 4), (1, 5)]
"""
t = [(1,2),(2,2),(3,2),(2,1),(2,2),(1,5), (10,4), (10, 1), (3, 1)]
# sorting first by last value ... |
# %%
# From 2 lists, using a list comprehension, create a list containing:
# [('Black', 's'), ('Black', 'm'), ('Black', 'l'), ('Black', 'xl'),
# ('White', 's'), ('White', 'm'), ('White', 'l'), ('White', 'xl')]
# colors = ['Black', 'White']
# sizes = ['s', 'm', 'l', 'xl']
colors = ['Black', 'White']
sizes = ['s', 'm',... |
import time
""" Create a decorator function that slows down your code by 1 second for
each step. Call this function slowdown()
For this you should use the ‘time’ module.
When you got the ‘slowdown code’ working on this recursive function,
try to create a more (for you) normal function that does the
countdown usin... |
#######################################################################################################################
"""
------------------
DATA PREPROCESSING
------------------
"""
#######################################################################################################################
# Importing th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.