text stringlengths 37 1.41M |
|---|
thisTuple=("apple","banana","lemon","cherry","mango") #create Tuple
print(thisTuple) #print Tuple
print(thisTuple[1]) #print a index
print(thisTuple[-2]) #negative index
print(thisTuple[2:5]) #range index
y=list(thisTuple)... |
class emp:
def __init__(self,id,name,dob):
self.id=id
self.name=name
self.dob=dob
def display(abc):
print("ID:"+abc.id)
print("Name:"+abc.name)
print("DOB:"+abc.dob)
obj=emp("A02","Supriyo","15Dec1998")
obj.display()
|
x=["Apple","Mango","Lemon"]
y=["Orange","Apple","Grapes"]
for a in x:
if a in y:
print(a," is present");
|
import tensorflow as tf
import tensorflowvisu
import math
from tensorflow.examples.tutorials.mnist import input_data as mnist_data
print("Tensorflow version " + tf.__version__)
tf.set_random_seed(0)
# neural network with 6 layers of relu neurons and final softmax layer
#
# · · · · · · · · · · (input data, flatte... |
from Utilities.utility import FunctionalCode
f1 = FunctionalCode
class QuestionToFindYourNumber:
try:
my_list = []
print("Enter the N value")
num = int(input())
while num < 0:
print("Please Provide Positive Number(only)")
num = int(input())
for i ... |
"""
******************************************************************************
* Purpose: Takes a date as input and prints the day of the week that date.
* @author: Krishna Murthy A V
* @version: 1.2
* @since: 28-1-2019
*
******************************************************************************
"""
from U... |
"""
******************************************************************************
* Purpose: compute the square root of a nonnegative number c given in the
input using Newton's method
* @author: Krishna Murthy A V
* @version: 1.2
* @since: 28-2-2019
*
***************************************************... |
"""
******************************************************************************
* Purpose: Write static functions to return all permutation of a String
using Recursion method.
*@author: Krishna Murthy A V
* @version: 1.1
* @since: 27-2-2019
*
***********************************************************... |
for letra in "Python":
if letra =="h":
continue #saltea las siguientes instrucciones del bucle
print("Letra: " + letra)
# Pass se suele usar para declarar una clase e implementarla más adelante. Ej_
# Class MiClase:
#pass
email = input("Ingrese un Email: ")
for i in email:
if i =="@":
arroba = True
break;
e... |
i=1
while i<=5: #la tabulación determina el alcance del while salvo que aparezca break
print(f"El valor de i es: {i}")
i=i+1
edad=int(input("Introduce una edad: "))
intentos = 3
while edad < 0 or edad > 100 :
intentos = intentos - 1
if intentos:
if intentos == 1:
print(f"Edad incorrecta, te resta {inten... |
for i in ["Ingeniería", "Informática", 3]: #recorre tantas veces como elementos hay en una lista
print("Hola", end=" ") # se usa para evitar saltos de línea y se puede concatenar un string
for i in "Francisco": #si lo hago contra un string recorre caracter por caracter
print(i)
personas = ["Rodrigo", "Rocío"]
def... |
# .upper(), .lower(), .capitalize(), .count(), .find(), .rfind(),
# .isdigit(), .isalum(), .isalpha(), .split(), .strip(), .replace()
# COSULTAR: http://pyspanishdoc.sourceforge.net/lib/module-string.html
nombreUsuario=input("Nombre de usuario: ")
print("Tu nombre de usuario es: ", nombreUsuario.capitalize())
|
#!python
def is_sorted(list_in):
for index, item in enumerate(list_in):
if index == len(list_in) - 1:
return True
if list_in[index + 1] is not None:
if item > list_in[index + 1]:
return False
return True
def bubble_sort(items, descending=False, comparis... |
class Recommender():
'''
What is this class all about - write a really good doc string here
'''
def __init__(self):
'''
what do we need to start out our recommender system
'''
pass
def read_dataset(self, movies_path='./data/movies_clean.csv', reviews_path='./data/tra... |
def delete_string(array, string):
if string in array:
array.remove(string)
return array
else:
return False
print (delete_string(["a", "b", "c", "d", "e"], "c"))
|
def create_dict(number):
dictionary = {}
for i in range(number):
dictionary[i + 1] = (i+1) * (i+1)
print (dictionary)
create_dict(5)
|
def addup_dictionary(dictionary):
total = 0
for key, value in dictionary.items():
total += value
return total
print (addup_dictionary({1:2,2:6,3:5}))
|
# 元组是一个不可变的序列
# 它和列表的操作方式基本一致
# 创建元组使用()
my_tuple = () # 创建了一个空元组
print(my_tuple, ",", type(my_tuple)) # <class 'tuple'>
# 当元组不是一个空元组是,括号可以省略
# 如果元组不是空元组,它需要包含至少一个元素
my_tuple = 1, 2, 3, 4, 5, 6, 7 # 定义一个包含多个元素的元组
# print(my_tuple)
# my_tuple = 40, # 定义一个只包含一个元素的元组
# print(my_tuple)
# 序列的解包(解构)
# 将序列中的元素依次按顺序赋值给a,... |
"""
实现一个连续浮点数发生器FloatRange(类似range),
根据你给定范围和步长值产生一个列连续浮点数。
如:迭代FloatRange(2.0,4.0,0.2)可产生序列:
正向:3.0 -> 3.2 -> 3.4 -> 3.6 -> 3.8 -> 4.0
反向:4.0 -> 3.8 -> 3.6 -> 3.4 -> 3.2 -> 3.0
"""
class FloatRange:
def __init__(self, start, end, step=0.1):
self.start = start
self.end = end
self.step = ... |
"""
某软件要求,从网络抓取各个城市气温信息,并依次显示:
北京:25~20
天津:17~22
长春:12~18
...
如果依次抓取所有城市田七在显示,显示第一个城市气温时,有很高的延时,
并且浪费存储空间。我们期望以‘用时访问’的策略,并且能把所有城市气温封装到一个对象里,
可用for语句进行迭代,如何解决?
解决方案:
1、实现一个迭代器对象WeatherIterator,next方法每次返回一个城市气温
2、实现一个可迭代对象WeatherIterable,__iter__方法返回一个迭代器对象
"""
import requests
from collections import Iterable, Iterator... |
# 编写一个程序,获取一个用户输入的整数,然后通过程序显示这个数是奇数还是偶数
# input_str=input("请输入一个整数:")
# to_int=int(input_str)
# if to_int % 2 ==0 :
# print("这是一个偶数:",to_int)
# else:
# print("这是一个奇数:",to_int)
# 编写一个程序,检查任意一个年份是否是闰年,如果一个年份可以被4整除不能被100整除,或者可以被400整除,这个年份就是闰年
# year=2016
# if (year % 4 ==0 and year % 100 !=0 ) or year % 400 ==0 :
# pr... |
# 闭包就是能够读取其他函数内部变量的函数
# 形成闭包的条件
# 1、函数嵌套
# 2、将内部函数作为返回值返回
# 3、内部函数必须要使用到外部函数的变量
def make_averager():
# 创建一个列表,用来保存数值
nums = []
# 创建一个内部函数,用于计算平均值
def averager(n):
# 将n添加到列表中
nums.append(n)
print(nums)
# 求平均值
return sum(nums) / len(nums)
return averag... |
"""
There is one way to reach the first step (One 1-weighted step).
There are two ways to reach the second step (Two 1-weighted steps or one 2-weighted step).
For step number n, we can reach it from step number n - 1 or step n - 2. This is a straightforward recursive solution.
"""
class Solution(object):
def clim... |
"""
Similar to staircase/steps problem - Store solution to each subproblem and add the parts to get the whole.
"""
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
memo = {}
... |
from collections import defaultdict
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
def get_counts(word):
counts = [0] * 26
for c in word:
counts[ord(c) - ord('a')] ... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
de... |
"""A multi-producer, multi-consumer queue."""
from collections import deque
from time import time as _time
from pyuv import thread as _thread
__all__ = ['Empty', 'Full', 'Queue']
class Empty(Exception):
"""Exception raised by Queue.get(block=0)/get_nowait()."""
pass
class Full(Exception):
"""Exceptio... |
# Truth test
#
# THE PROBLEM
#
# Assume the following value has already been entered into the
# Python interpreter, representing your trustworthiness
# and how old you purport to be
honest = False
age = 21
# Write an expression, or expressions, to create a string
# declaring your age, and whether you are telling the... |
# Binary interpreter
#
# THE PROBLEM
#
# Assume the following list of binary digits (bits) has already been
# entered into the Python interpreter, representing a binary number
binary_number = [1, 0, 1, 0, 1]
# Write an expression, or expressions, to calculate the decimal value of that
# binary number and output it to... |
"""
Artificial neural network
Using Python 3.6.2 64-bit
"""
# Perceptron (Threshold Logic Unit)
'''
Example of training a single TLU -
Taking iris preset from scikit package
'''
import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import Perceptron
iris = load_iris()
X = iris.data[:,... |
"""
# 짝수와 홀수
* 문제 설명
정수 num이 짝수일 경우 "Even"을 반환하고 홀수인 경우 "Odd"를 반환하는 함수, solution을 완성해주세요.
* 제한 조건
num은 int 범위의 정수입니다.
0은 짝수입니다.
"""
# 입출력 예
# +--------------+
# | num | return |
# |-----|--------|
# | 3 | "Odd" |
# | 4 | "Even" |
# +--------------+
def solution(num):
if num % 2 == 0: # num을 2로 나누었을 때 나머지... |
secret_word = ["MACEDONIA", "SINGAPORE"]
blanks = ["********", "*********"]
lives = 5
def replace(secret_word, blanks, letter):
for i in range(len(secret_word)):
if letter == secret_word[i]:
blanks = blanks[0:i] + letter + blanks[i+1:]
return blanks
def guess():
answer = inp... |
import json
def check_number():
"""Checking if the number is inside the favorite number file"""
filename = 'favorite_number.json'
try:
with open(filename) as f:
number = json.load(f)
except FileNotFoundError:
return None
else:
return number
def new_number():
... |
from random import randint, choice
class Die():
"""Rolls a dice."""
def __init__(self, sides=6):
self.sides = sides
def roll_die(self):
"""Rolling a dice fro 10 times between 1 and sides"""
for roll_num in range(10):
print(randint(1, self.sides))
# results = []
# d10... |
with open('text_files/learning_python.txt') as file_object:
lines = file_object.readlines()
print("First:")
for line in lines:
line = line.strip()
print(f"\t{line.replace('python', 'java')}")
python_list = ''
for line in lines:
python_list += line.strip()
# # print("\nSecond:")
# # ... |
# name = input("Please enter your name: ")
# print(f"\nHello, {name}!")
prompt = "Tell us who you are, and we send a personalized message."
prompt += "\nWhat is your first name? "
name = input(prompt)
print(f"\nHello, {name}!")
|
filename = 'guest.txt'
filename_2 = 'guest_book.txt'
poll = 'programming_poll.txt'
name = input("Please enter your name: ")
with open(filename, 'w') as file_object:
file_object.write(name)
with open(filename_2, 'w') as file_object_2:
print("\nWelcome in the Holiday Inn, please enter your name: ")
print(... |
def make_shirt(size='large', text='I love python'):
print(f"The size of your shirt will be {size}, and have the text '{text}' written on it.")
make_shirt('medium', 'hello world!')
def describe_city(city, country="fairyland"):
print(f"{city} is in {country}.")
describe_city('brugge')
describe_city('sao pau... |
#Interfaz para Calculadora
#Importar funciones desde otro archivo
from funcionescalculadora import * #puedes seleccionar la funcion especifica
from raices import raices
print("Calculadora SAM\nIntroduce el numero de la operacion a hacer, o presiona Q para salir:")
print("[1.-Suma] [2.-Resta] [3.-Multiplicacion]\n[4.-D... |
#!/home/fode4cun/.local/share/virtualenvs/checkio-ufRDicT7/bin/checkio --domain=py run expand-intervals
# An interval of consecutive positive integers can be succinctly described as a tuple that contains first and last values. For example, the interval that contains the numbers 5, 6, 7, 8, 9 can be described as (5,9)... |
#!/home/fode4cun/.local/share/virtualenvs/checkio-ufRDicT7/bin/checkio --domain=py run follow-instructions
# You’ve received a letter from a friend whom you haven't seen or heard from for a while. In this letter he gives you instructions on how to find a hidden treasure.
#
# In this mission you should follow a given l... |
#!/home/fode4cun/.local/share/virtualenvs/checkio-ufRDicT7/bin/checkio --domain=py run caps-lock
# Joe Palooka has fat fingers, so he always hits the “Caps Lock” key whenever he actually intends to hit the key “a” by itself. (When Joe tries to type in some accented version of “a” that needs more keystrokes to conjure... |
#!/home/fode4cun/.local/share/virtualenvs/checkio-ufRDicT7/bin/checkio --domain=py run counting-tiles
# Stephan needs some help building a circular landing zone using the ice square tiles for their new Ice Base. Before he converts the area to a construction place, Stephan needs to figure out how many square tiles h... |
"""
622. Frog Jump
A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the riv... |
"""
544. Top k Largest Numbers
Given an integer array, find the top k largest numbers in it.
Example
Example1
Input: [3, 10, 1000, -99, 4, 100] and k = 3
Output: [1000, 100, 10]
Example2
Input: [8, 7, 6, 5, 4, 3, 2, 1] and k = 5
Output: [8, 7, 6, 5, 4]
"""
import heapq
class Solution:
def topk(self, nums, k)... |
"""
109. Triangle
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
Example
Example 1:
Input the following triangle:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
Output: 11
Explanation: The minimum path sum from top to bottom is 11 (i.e., ... |
"""
57. 3Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Example
Example 1:
Input:[2,7,11,15]
Output:[]
Example 2:
Input:[-1,0,1,2,-1,-4]
Output: [[-1, 0, 1],[-1, -1, 2]]
Notice
Elements in a triplet (a,b,... |
"""
153. Combination Sum II
Given an array num and a number target. Find all unique combinations in num where the numbers sum to target.
Example
Example 1:
Input: num = [7,1,2,5,1,6,10], target = 8
Output: [[1,1,6],[1,2,5],[1,7],[2,6]]
Example 2:
Input: num = [1,1,1], target = 2
Output: [[1,1]]
Explanation: The solu... |
"""
159. Find Minimum in Rotated Sorted Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
Example
Example 1:
Input:[4, 5, 6, 7, 0, 1, 2]
Output:0
Explanation:
The minimum value in an array is 0.
Example 2:
In... |
"""
71. Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
Example
Example 1:
Input:{1,2,3}
Output:[[1],[3,2]]
Explanation:
1
/ \
2 3
it will be se... |
"""
32. Minimum Window Substring
Given two strings source and target. Return the minimum substring of source which contains each char of target.
Example
Example 1:
Input: source = "abc", target = "ac"
Output: "abc"
Example 2:
Input: source = "adobecodebanc", target = "abc"
Output: "banc"
Explanation: "banc" is the m... |
"""
585. Maximum Number in Mountain Sequence
Given a mountain sequence of n integers which increase firstly and then decrease, find the mountain top.
Example
Example 1:
Input: nums = [1, 2, 4, 8, 6, 3]
Output: 8
Example 2:
Input: nums = [10, 9, 8, 7],
Output: 10
"""
from typing import List
class Solution:
"""
... |
"""
Given a string(Given in the way of char array) and an offset, rotate the string by offset in place. (rotate from left to right).
Example
Example 1:
Input: str="abcdefg", offset = 3
Output: str = "efgabcd"
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes "efgabcd".
Example 2... |
"""
115. Unique Paths II
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
Example
Example 1:
Input: [[0]]
Output: 1
Example 2:
Input: [[0,0,0],[0,1,0],[0,0,0]]
O... |
"""
685. First Unique Number in Data Stream
Given a continuous stream of data, write a function that returns the first unique number (including the terminating number) when the terminating number arrives. If the unique number is not found, return -1.
Example
Example1
Input:
[1, 2, 2, 1, 3, 4, 4, 5, 6]
5
Output: 3
Exa... |
"""
138. Subarray Sum
Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number.
Example
Example 1:
Input: [-3, 1, 2, -3, 4]
Output: [0, 2] or [1, 3].
Explanation: return anyone that the sum is 0.
Example 2:
Input... |
"""
86. Binary Search Tree Iterator
Design an iterator over a binary search tree with the following rules:
Elements are visited in ascending order (i.e. an in-order traversal)
next() and hasNext() queries run in O(1) time in average.
Example
Example 1
Input: {10,1,11,#,6,#,12}
Output: [1, 6, 10, 11, 12]
Explanation... |
"""
192. Wildcard Matching
Implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Example
Example 1
Input:
"aa"
"a"
Output: false
Exampl... |
"""
597. Subtree with Maximum Average
Given a binary tree, find the subtree with maximum average. Return the root of the subtree.
Example
Example 1
Input:
{1,-5,11,1,2,4,-2}
Output:11
Explanation:
The tree is look like this:
1
/ \
-5 11
/ \ / \
1 2 4 -2
The average of subtree of 11 is 4.3333, ... |
"""
545. Top k Largest Numbers II
Implement a data structure, provide two interfaces:
add(number). Add a new number in the data structure.
topk(). Return the top k largest numbers in this data structure. k is given when we create the data structure.
Example
Example1
Input:
s = new Solution(3);
s.add(3)
s.add(10)
s.to... |
"""
603. Largest Divisible Subset
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.
Example
Example 1:
Input: nums = [1,2,3],
Output: [1,2] or [1,3]
Example 2:
Input: nums = [1,2,4,8],
Output: [1,2,4,8]
... |
"""
539. Move Zeroes
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example
Example 1:
Input: nums = [0, 1, 0, 3, 12],
Output: [1, 3, 12, 0, 0].
Example 2:
Input: nums = [0, 0, 0, 3, 1],
Output: [3, 1, 0, 0, 0].
Notice
You must do... |
"""
495. Implement Stack
Implement a stack. You can use any data structure inside a stack except stack itself to implement it.
Example
Example 1:
Input:
push(1)
pop()
push(2)
top() // return 2
pop()
isEmpty() // return true
push(3)
isEmpty() // return false
Example 2:
Input:
isEmpty()
"""
class Stack:
stack ... |
# anthor: zhangwei time:2020/11/26
# 内置函数range()
r = range(10)
print(r)
print(list(r))
r = range(1, 10) # 不包含10
print(list(r))
r = range(1, 10, 3)
print(list(r))
print(10 in r)
print(7 in r)
# 关于range类型的优点:不管range对象表示的整数序列有多长,所有对象占用的内存空间都是相同的,只需要最多存储3个数据
# 只有当用到range对象时,才会去计算序列中的相关元素 |
# -*- coding: utf-8 -
#
# This file is part of offset. See the NOTICE for more information.
import multiprocessing
import os
import time
def getmaxthreads():
if 'OFFSET_MAX_THREADS' in os.environ:
return int(os.environ['OFFSET_MAX_THREADS'])
n = 0
try:
n = multiprocessing.cpu_count()
... |
import time
# MERGE SORT
def metricas_mergesort(vetor, ordem):
inicio = time.time()
mergesort(vetor)
fim = time.time()
print("Tempo (ms) vetor " + ordem + ": " + str(round(fim-inicio, 6)))
def mergesort(vetor):
if len(vetor)>1:
meio = len(vetor)//2
esquerda = vetor[:meio]
... |
def avg(x):
total = 0
try:
for i in range(0, len(x)):
total = total + x[i]
return total / len(x)
except ZeroDivisionError:
return "No values."
except:
return "Error, not all numbers"
|
import numpy as np
from l5_data_prep import features, targets, features_test, targets_test
def sigmoid(x):
"""
Calculate sigmoid
"""
return 1 / (1 + np.exp(-x))
# Use to same seed to make debugging easier
np.random.seed(42)
n_records, n_features = features.shape
last_loss = None
# Initialize weight... |
"""
Odd or Even?
https://www.codewars.com/kata/5949481f86420f59480000e7/train/python
Given a list of integers, determine whether the sum of its elements is odd or even.
Give your answer as a string matching "odd" or "even".
If the input array is empty consider it as: [0] (array with a zero).
Input: [0]
Output: "even"... |
"""
Grasshopper- Grade book
https://www.codewars.com/kata/55cbd4ba903825f7970000f5/train/python
Complete the function so that it finds the mean of the three scores passed to it and returns the letter value associated with that grade.
Numerical Score Letter Grade
90 <= score <= 100 'A'
80 <= score < 90 'B'
70 <= score... |
"""
The Old Switcheroo
https://www.codewars.com/kata/55d410c492e6ed767000004f/train/python
Write a function vowel_2_index
that takes in a string and replaces all the vowels [a,e,i,o,u] with their respective positions within that string.
E.g:
vowel_2_index('this is my string') == 'th3s 6s my str15ng'
vowel_2_index('Co... |
"""
Highest and Lowest
https://www.codewars.com/kata/554b4ac871d6813a03000035/train/python
In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
Example:
high_and_low("1 2 3 4 5") # return "5 1"
high_and_low("1 2 -3 4 5") # return "5 -3"
high_... |
"""
Return Odd No Matter What
https://www.codewars.com/kata/5f882dcc272e7a00287743f5/train/python
Given the integer n return odd numbers as they are, but subtract 1 from even numbers.
Note: Your solution should be 36 or less characters long.
"""
# Question: what is a shorter way to check odd/even numbers?
"""
bitwise... |
"""
Recursion 101
https://www.codewars.com/kata/5b752a42b11814b09c00005d/train/python
You are given two positive integers a and b.
Your task will be to apply the following operations:
i) If a = 0 or b = 0, return [a,b]. Otherwise, go to step (ii);
ii) If a ≥ 2*b, set a = a - 2*b, and repeat step (i). Otherwise, go to... |
"""
Quarter of The Year
https://www.codewars.com/kata/5ce9c1000bab0b001134f5af/train/python
Given a month as an integer from 1 to 12, return to which quarter of the year it belongs as an integer number.
For example: month 2 (February), is part of the first quarter; month 6 (June), is part of the second quarter; and mo... |
class Node(object):
def __init__(self, value, index=0):
self.value = value
self.children = []
self.index = index
class SetSuffixTree(object):
"""
From Skiena on Data Structures, given a reference string S
this is useful for finding all the places where an
arbitrary query string q is a substring... |
def is_matched(expression):
from collections import deque
open_b = deque()
if len(expression)%2 != 0:
return False
for s in expression:
try:
if s =='}':
a = open_b.pop()
if a != '{':
return False
elif s ==')':
... |
from collections import deque
class Vertex(object):
def __init__(self, id_, parent=None):
self.id_ = id_
self.neighbours = []
self.discovered = False
self.parent = parent
self.distance = 0
class Graph(object):
def __init__(self, N):
self.vertices = {}
se... |
def lonely_integer(a):
while a:
test = a.pop()
try:
a.remove(test)
except ValueError:
return test
def lonely_integer(a):
"""
XOR will evaluate to 0 if two identical numbers are present bit wise
in the list, other wise 0000000^number = number.
"""
lonely_integer = reduce(lambda ... |
class Node(object):
def __init__(self, price):
self.id_ = 0
self.price = price
self.right_child = None
self.left_child = None
def build_tree(seq):
if len(seq) == 0:
return None
med = len(seq)//2
left = seq[:med]
right = seq[med+1:]
node = Node(seq[med])
node.left_ch... |
# PhotoFolderFinder.py
"""
Prints an absolute path to a folder that appears to be a photo-folder.
A folder is considered a photo-folder if the number of photos inside
is greater that the number of files.
"""
import os
from PIL import Image
for dirpath, dirnames, filenames in os.walk('C:\\'):
photo_counter = 0
... |
cont_impar = 0
cont_par = 0
num = int(input("Entre com um número [999 para encerrar]: "))
while (num != 999):
num = int(input("Entre com um número [999 para encerrar]: "))
if (num % 2 == 0):
cont_par += 1
else:
cont_impar += 1
print('Contagem dos pares:', cont_par)
print('Contagem dos impare... |
def fibonacci():
l = []
n = 1
n1 = 1
l.append(n)
l.append(n1)
x = int(input('Digite o numero:'))
for i in range(2, x):
l.append(n + n1)
n1 = l[i]
n = l[i - 1]
return(l)
print(fibonacci()) |
texto = input("Digite seu nome;")
print("Seu nome tem {0} letras".format(len(texto)))
|
titulo = 'Jogo da Advinhação!'
linha = '-' * 28
linha1 = "_" * 40
linha2 = '—' * 50
y = 1
print(linha)
print(titulo.center(25))
print(linha)
print()
usuario = input('\t\tDigite seu nome: ')
print('\t\tBem Vindo {0} ao Jogo!'.format(usuario))
print()
print(linha1.center(20))
print('Digite (0) FACIL (1) MEDIO (2) DIFIC... |
quantidade = 0
codigo = 0
p = 0
while True:
n = int(input("Digite o codigo:"))
a = int(input("Digite a quantidade:"))
quantidade = a + quantidade
if n == 1:
p = p + 0.50
p = p * a
if n == 2:
p = p + 1.00
p = p * a
if n == 3:
p = p + 4.00
p = p * a
... |
#MEDIA IFPA
linha = '-' * 60
titulo = 'INSTITUTO FEDERAL DE EDUCAÇÃO, CIÊNCIA E TECNOLOGIA DO PARÁ \nCampus Altamira\nAUTOR: Jobs-TI'
print(linha)
print(titulo.center(60))
print(linha)
linha = '-' * 60
titulo = 'MÉDIA DE APROVAÇÃO'
print(linha)
print(titulo.center(60))
print(linha)
nota1 = float(input('Digite sua prime... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
#文件或目录创建脚本
import os
#用户选择新建目录还是文件
def panDuan():
b = int(input('1.创建文件 2.创建文件夹 [1/or/2]'))
#接收用户的输入如果文件运行函数creatFile,如果是文件夹运行函数creatDir
if b == 1:
creatFile()
elif b == 2:
creatDir()
else:
print("别闹!")
def creatDir():
a = inp... |
# -*- coding: utf-8 -*-
"""
@author: Saras
Problem Set 1 for MITx: 6.00.1x Introduction to Computer Science and Programming Using Python
"""
'''
Problem 2
10.0/10.0 points (graded)
Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s. For example... |
# READ ME:
# Input file: create a possible state by swapping pieces (even swaps) and eliminate pieces by writing 0
# Start by checking what the input cube state looks like using inpstate()
# Use listates([draw]) to output all the possible cube states (listates(1) to output images)
################################... |
def square(x):
return x * x
print square(2) # 4
print type(square) # <type 'function'>
squareLambda = lambda x: x * x
print squareLambda(2) # 4
print type(squareLambda) # <type 'function'>
list = range(5)
print list # [0, 1, 2, 3, 4]
print map(squareLambda, list) # [0, 1, 4, 9, 16]
|
file = open("test.txt", "r")
lines = file.readlines()
for line in lines:
str = line
arr1 = (str.split("//"))
if len(arr1)==2:
print ( arr1[1], "- is a comment")
if len(arr1)==1:
str.split()
arr2 = arr1[0].split("/*")
arr3 = arr1[0].split("*/")
if arr2[0]=='':
print ("Comment starts at line-", arr2[... |
fruit1=input("whats your favorite fruit?\n")
veg1=input("whats your favorite vegetable?\n")
sweet1=input("whats your favorite sweet?\n")
print(f"\n\r{fruit1}\n{veg1}\n{sweet1}\nare your favorites?") |
print('\tHello World\n') #\t creates
#an indent, \n makes a new line, and
#using \ before a character will
#treat it differently, for example:
print("This is a double quote \", yet still in a double \nquoted print because of the backslash.")
print("""There once was a movie star icon
who preferred to sleep with the lig... |
import turtle
import random
#set up screen for drawing
my_screen = turtle.Screen()
my_turtle = turtle.Turtle()
my_screen.colormode(255)
screenwidth, screenheight = my_screen.screensize()
# this function draws mountains
def mountains (radius):
my_turtle.pu ()
my_turtle.color ("green", "green")
my_tu... |
from cs50 import get_float
while True:
change_float = get_float("Change owed: ")
if change_float > 0:
break
change = change_float * 100
total_coins = 0
# quarters = 0
# dimes = 0
# nickels = 0
# pennies = 0
while change >= 25:
change -= 25
# quarters += 1
total_coins += 1
while chang... |
KG=input('請輸入你的體重,單位是公斤')
M=input('請輸入你的身高,單位視公尺')
BMI=float(KG)/(float(M)*float(M))
if float(BMI)<18.5:
print('體重不足')
elif float(BMI)<24:
print('正常')
elif float(BMI)<27:
print('過重')
elif float(BMI)<30:
print('輕度肥胖')
elif float(BMI)<35:
print('中度肥胖')
else:
print('重度肥胖')
|
#Accept an integer n and compute n+nn+nnn
a=int(input("Enter the integer : "))
n1=int("%s" %a)
n2=int("%s%s" %(a,a))
n3=int("%s%s%s" %(a,a,a))
print("value of n+nn+nnn is : ",n1+n2+n3)
|
#Count the occurence of each word in a line of text.
def wordoccur(n,p):
x=n.split(" ")
c=0
for i in range(0,len(x)):
if(p==x[i]):
c=c+1
return c
print("Enter the string:")
n=str(input())
print("Enter the word to count the occurence:")
p=str(input())
print("The occurence ... |
#program to display fibonacci series
t=int(input("Enter the number of terms:"))
n1=0
n2=1
count=0
if t<=0:
print("please enter a positive integer")
elif t==1:
print("fibonacci sequence upto",t)
print(n1)
else:
print("Fibonacci sequence:")
while count < t:
print(n1)
n=n1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.