text stringlengths 37 1.41M |
|---|
n1=int(input('Enter Base Value))
n2=int(input(Enter Power value ))
int('Value of ',n1,'**',n2, 'is',n1**n2) |
##คำสั่ง print คำตอบจะอยู่แถวเดียวกันและติดกัน
for i in range(3):
print(i,end="")
##คำสั่ง print ธรรมดา คำตอบจะขึ้นทีละแถว
for i in range(3):
print(i)
##คำสั่ง print คำตอบจะอยู่แถวเดียวกันและห่างกัน 1 วรรค
for i in range(3):
print(i,end=" ")
##คำสั่ง print คำตอบจะอยู่แถวเดียวกันและมี -
for i in range(3):... |
from tkinter import *
def sayHelloWorld():
print("Hello world")
def sayNo():
print("Bye Bye")
mainWindow = Tk()
button = Button(mainWindow,text = "Click me",command = sayHelloWorld)
button.place(x = 20, y = 10)
button2 = Button(mainWindow,text = "Click me2",command = sayNo)
button2.place(x = 120, y = 10)
main... |
n=int(input())
if(n&n-1==0):
print("power of two")
else:
print("not a power of two")
|
from math import atan
x = int(input("Введите значение Х"))
y = int(input("Введите значение Y"))
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
def to_polar (self):
self.r = ((self.x**2)+(self.y**2))**0.5
self.f = atan(self.x/self.y)
return (self.r,se... |
import random
import os
import re
def lets_play(name):
# Use a breakpoint in the code line below to debug your script.
print('Let\'s play- {0}'.format(name))
""" Rock Paper Scissors
----------------------------------------
"""
os.system('cls' if os.name == 'nt' else 'clear')
while 1 < 2:
... |
from Token import *
import sys
class Instream(object):
'''A extremely barebones wrapper for the input stream'''
backlog = []
def getvisible(self):
'''Get a single non-whitespace character from the input stream'''
while True:
result = self.getchar()
if result !=... |
import pandas as pd
import numpy as np
from pandas import DataFrame, Series
csv = pd.read_csv('C:\\Users\\asus\\PycharmProjects\\untitled\\imbd_superhero.csv',
header=None,
names=['An', 'Titlu', 'Organizatia', 'IMBD', 'AltRating', 'DataX', 'UnknownColumn', 'PretMediulaBilet', 'NrDeS... |
class Freqlettre: #classe qui retourne la liste des tuples (freq, letre)
def __init__(self, fichier): #constructeur
self.fichier = fichier #fichier à ouvrir
self.liste_lettre = [] #liste contenant les lettres du fichier
self.liste_freq_et_lettre = self.parcours_fichier() #liste avec ... |
import math
def cc_iou(circle1, circle2):
"""
Intersection over Union (IoU) between two circles.
Parameters
----------
circle1 : tuple of floats
first circle parameters (x_pos, y_pos, radius)
circle2 : tuple of floats
second circle parameters (x_pos, y_pos, radius)
Return... |
"""Clustering predictions.
Predictions have two columns: event_id and cluster_id. event_id
comes from the first column of X when test is called. See
``rampwf.workflows.clustering``.
The predictions are used in "supervised" clustering where the data
consists of a set of events ad each event has an unknown number of
cl... |
def fine_license_ratio(license_data, fine_data, column_name1=None, column_name2=None,year=None):
"""Get ratio of fines to licenses issued in a given year
Parameters:
-----------
license_data: DataFrame
Any subset of the Professional and Occupational Licensing dataframe
fine_data: DataFrame
Any subset of... |
# -*- coding: utf-8 -*-
# Data Source: https://jamesmccaffrey.wordpress.com/2018/03/14/datasets-for-binary-classification/
from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense
# load the dataset
dataset = loadtxt('data_banknote_authentication.csv', delimiter=',')
# split into... |
import numpy as np
def calculate():
target=10
num_to_test=0
while True:
num_to_test += target
if all(num_to_test % j == 0 for j in range(1,target+1)):
return num_to_test
return -1
print calculate()
|
from plus import plus
from minus import minus
from multifly import multifly
from divide import divide
a = input("Enter your number : ")
a = int(a)
b = input("Enter your number : ")
b = int(b)
print("=========")
plus(a, b)
minus(a, b)
multifly(a, b)
divide(a, b) |
"""Requwsts first name and last name.
The main functions are in the class woker"""
from worker import Employee
while True:
first = input("\nPlease give me a first name: ")
last = input("Please give me a last name: ")
annual_salary = input("Annual salary: $")
name = input("Enter 'q' at any time to quit... |
""" Displays a list of cats and dogs and
handles an error if the file does not exist."""
def cat_dog(filename):
try:
with open(filename) as f_obj:
animals = f_obj.read()
except FileNotFoundError:
pass
# msg = "Sorry, the file " + filename + " does not exist."
# print(ms... |
#
# @lc app=leetcode.cn id=5 lang=python3
#
# [5] 最长回文子串
#
# https://leetcode-cn.com/problems/longest-palindromic-substring/description/
#
# algorithms
# Medium (31.19%)
# Likes: 2490
# Dislikes: 0
# Total Accepted: 328.2K
# Total Submissions: 1.1M
# Testcase Example: '"babad"'
#
# 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 ... |
#
# @lc app=leetcode.cn id=153 lang=python3
#
# [153] 寻找旋转排序数组中的最小值
#
# https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/description/
#
# algorithms
# Medium (50.16%)
# Likes: 212
# Dislikes: 0
# Total Accepted: 60.2K
# Total Submissions: 117.8K
# Testcase Example: '[3,4,5,1,2]'
#
# 假设按照升序排序... |
with open("weather_data.csv") as data_file:
data = data_file.readlines()
print(data)
import csv
temperatures = []
with open("weather_data.csv") as data_file:
data = csv.reader(data_file)
for row in data:
if row[1] != "temp":
temperatures.append(int(row[1]))
print(temperatures)
i... |
class Solution(object):
#sort array, even numbers in the front and odd in the end
#sort even and odd in ascending order
def sortArrayByParity(self, A):
#create even and odd array and store respective numbers into array
even = []
odd = []
for num in A:
if num % 2 == 0... |
'Given an integer n, write a function to determine if it is a power of two.'
def isPowerOfTwo(n) :
while n >= 1:
if n == 1:
return True
n = n / 2
return False
print(isPowerOfTwo(2))
print(isPowerOfTwo(3))
print(isPowerOfTwo(16)) |
# Assign numbers to x, y, and z.
# Calculate the sum of x, y, and z in s.
# Print out the value of s.
x = 5.9
y = 10.1
z = 15
s = x + y + z
print(s) |
import string
# This is the "compute_tweets" function as described in the assignment.
def compute_tweets(tfile, tkeys):
# Creating final (currently empty) list to contain tuples and be returned.
returnList = []
# creating lists to hold the tuples for each timezone
pacific_tweets = []
mountain_twee... |
"""
https://adventofcode.com/2017/day/8
"""
from typing import NamedTuple, List, Dict
from collections import defaultdict
import re
class Condition(NamedTuple):
register: str
comparison: str
target: int
class Instruction(NamedTuple):
register: str
operation: str
amount: int
condition: Cond... |
"""
http://adventofcode.com/2017/day/5
"""
from typing import List
def steps_to_exit(jump_offsets: List[int]) -> int:
jump_offsets = jump_offsets[:]
curr = 0
num_steps = 0
while curr >= 0 and curr < len(jump_offsets):
offset = jump_offsets[curr]
jump_offsets[curr] += 1
curr +=... |
if __name__ == '__main__':
'''imprime de una lista de corredores el runner-up
osea el segundo'''
n = int(input())
arr = map(int, input().split())
lista = list(set(arr))
lista.sort(reverse=True)
print(lista[1])
|
import random
def lotto():
winner = [1, 15, 19, 23, 28, 42]
bonus = [6]
# random.sample([배열], 뽑을 개수)
lotto = sorted(random.sample(range(1, 46), 6))
# set(배열) → 집합(중복원소 제거, 집합 연산자)
set(lotto)
# python은 .length 대신 len함수가 있다.
num = len(set(lotto) & set(winner))
# 조건문을 사용할 때 python은 ... |
def game(player_1, player_2):
if player_1 == player_2:
return 'tie'
elif str(player_1) == "rock" and str(player_2) == "scissors" or str(player_1) == "scissors" and str(player_2) == "paper" or str(player_1) == "paper" and str(player_2) == "rock":
return "player_1"
else:
return "playe... |
# While loop in python
# Initialization
# Terminate condition
# Execution
# Increment/Decrement
i = 0
while i < 5:
print('Python ', end='')
j = 0
while j < 5:
print('Programming ', end='')
j = j + 1
i = i + 1
print()
|
# For loop in python
# for in range(initialization, termination, increment/decrement). Increment like 1, 2 ,3 , 4, ....
# For loop can handle any data types of sequence
numbers = [2, 4, 'python', 5, 'programming', 8]
for i in numbers:
print(i, '', end='')
print()
# string with python
string = 'programming'
for ... |
# Array in python
from array import *
# import array as arr
names = array('i', [3, 4, 5, 6, 7])
# len() returns size of array size
print(len(names))
# buffer_info() returns address and array size
print(names.buffer_info())
# typecode property returns array type
print(names.typecode)
# reverse() use for getting a... |
import turtle
ball_speed = 40
left_player_score = 0
right_player_score = 0
# screen
screen = turtle.Screen()
screen.title("Pong Game")
screen.setup(width=1200, height=700)
# left paddle
left_paddle = turtle.Turtle()
left_paddle.hideturtle()
left_paddle.speed(15)
left_paddle.shape('square')
left_paddle.shapesize(stre... |
def monopolyworp():
dubbel = 0
import random
while dubbel < 2:
steen1 = random.randrange(1, 7)
steen2 = random.randrange(1, 7)
totaal = steen1 + steen2
if steen1 == steen2:
print('{} + {} = {} dubbel'.format(steen1,steen2,totaal))
dubbel += 1
... |
def partiton(lst):
for name in lst:
if name[0] in 'ABCDEFGHIJKLM':
print(name)
namelist=['Elenor','Evelyn','Sammy','Owen','Gavin']
partiton(namelist) |
def inlezen_beginstation(stations):
inlst = False
while inlst == False:
invoer = input("geef uw beginstation op: ") #vraagt het beginstation op
if invoer in stations:
inlst == True #geeft aan dat het station gevonden is en beindigd de loop
return invoer #geeft het begins... |
pets = ['dog','cat','fish', 'rabbit']
for i in range(len(pets)):
print(pets[i])
print()
i=0
while i < len(pets):
print(pets[i])
i += 1
|
getallenrij = [23, 35, 31, 26, 73, 75, 84, 29, 42, 46]
oneven = 0
deel2_3 = 0
for getal in getallenrij:
if getal%2 > 0:
oneven +=1
if getal%3 == 0 and getal%2 == 0:
deel2_3 += 1
print("het aantal even getallen is:",oneven)
print("het aantal getallen deelbaar door 2 en 3 is:",deel2_3) |
flowers = ['rose', 'bougainvillea', 'yucca', 'marigold', 'daylilly', 'lilly of the valley']
thorny = flowers[:3]
poisonous = flowers[5]
dangerous = [thorny, poisonous]
print(flowers)
print('potato' in flowers)
print(thorny)
print(poisonous)
print(dangerous) |
naam = input("wat is uw naam: ")
leeftijd = eval(input('wat is uw leeftijd: '))
print(naam + ', volgend jaar ben je' , leeftijd + 1)
|
def pay(hours,wage):
loon = 0
if hours <= 40:
loon = hours*wage
else:
loon = 40*wage
overwerk = (hours-40)*1.5*wage
loon = loon+overwerk
return loon
uren = eval(input("voor het aantal uren in: "))
tarief = eval(input("voer het uurloon in: "))
print(pay(uren,tarief)) |
class Stack:
def __init__(self):
self.storage = []
def push(self, item):
self.storage.append(item)
def pop(self):
self.storage.pop()
def peek(self):
return self.storage[len(self.storage) - 1]
class Queue:
def __init__(self):
self.size = 0
self.storage = []
def enqueue(self,... |
import numpy as np
import cv2 as cv
img1 = cv.imread('2.png')
img2 = cv.imread('3.png')
add = img1 + img2
#this is another method which adds all the pixel values by that image produce somuch of white color so by that we cant even see the image.
####### add = cv.add(img1,img2) #########
# addWighted... |
num = list()
for i in range(10):
n = int(input())
if(not(n%42 in num)):
num.append(n%42)
print(len(num))
|
input_file = 'Day 14\\Input.csv'
# input_file = 'Day 14\\Test.csv'
text_file = open(input_file)
lines = text_file.read().split('\n')
def calc_dist(speed, time, rest, seconds):
elapsed = 0
dist = 0
flag = 0
while flag == 0:
i = 1
while i <= time:
elapsed += 1
... |
import re
from json import loads
input_file = 'Day 12\\Input.csv'
text_file = open(input_file)
lines = text_file.read()
sum_p1 = 0
numbers = re.findall(r"\-?\d+",lines)
for i in range(0,len(numbers)):
sum_p1 += int(numbers[i])
print("Part 1: " + str(sum_p1)) # Correct!
def n(inp):
if type(i... |
# Goal: write the simplest explicit Python program to solve the pendulum probelm
import pylab as pl
def acc(x,g,l):
"""Pendulum'sangular acceleration"""
return (-g/l)*pl.sin(x)
def update(x,v,a,g,l,dt):
"""Velocity Verlet integrator"""
x += v*dt + 0.5 *a*dt**2
v += 0.5* (acc(x, g, l)+acc(x, g, l))*dt
retu... |
import numpy as np
from datetime import datetime
#Diferencia de tiempo de procesamiento de 1 millón de elementos
#Con listas normales en python
py_list = [i for i in range(1000000)]
start = datetime.now()
py_list = [i+3 for i in py_list]
end = datetime.now()
print(end - start)
#Con numpy
np_arr = np.array([i for i in... |
# Author: Michael Lazeroff
# Solution To: Problem L "Umm Code" ICPC Mid Central USA Programming Contest 2019
import string
def get_valid_words(txt: list):
"""
Returns a single string of the valid um words
"""
um_index = [] # holds the indices of the valid code words
# get an individual word... |
string = input()
alphabet = [0] * 26
# there is another way to do it without sorting, just keep track of the two
# max frequencies
for letter in string:
alphabet[ord(letter) - 97] += 1
alphabet.sort()
print(len(string) - (alphabet[25] + alphabet[24]))
|
from mcts_node import MCTSNode
from random import choice
from math import sqrt, log
num_nodes = 1000
explore_faction = 2.
def traverse_nodes(node, board, state, identity):
""" Traverses the tree until the end criterion are met.
Args:
node: A tree node from which the search is traversing.
... |
#!/usr/bin/python
# encoding: utf-8
# Programa que lee dos numeros introducidos, los suma, los resta y los multiplica
import sys
def escribe(s):
print s
def suma(x,y):
print "Haciendo suma..."
sum= x+y
return sum
def resta(x,y):
print "Haciendo resta..."
sum= y-x
return sum
def mult(x,y):
print "Haciendo mu... |
def knapsack(weights, values, W):
N = len(weights)
memo = [[None] * N for _ in range(W + 1)]
return knapsack_recursive(weights, values, W, len(weights), memo)
def knapsack_recursive(weights, values, W, N, memo):
if N == 0 or W == 0:
return 0
if weights[N - 1] > W:
return knapsack_... |
# counting the ways to get a sum given an array of numbers
# ie s = 5, a = [1, 2, 3], given the denominations find how many ways
# are there to make 5
# TODO, generate the arrays that cointain the numbers that sum up to s
def waysToGetNum(s, numbers):
result = [0]*(s+1)
result[0] = 1
for num in nu... |
# check if an integer is a palindrome
# same check that is applied to strings
# trick is getting the first digit in the number
import math
def isIntPalindrome(n):
if n<0:
return False
elif n == 0:
return True
# find the # of digits
d = int(round(math.log(n, 10))) + 1
# grabbing... |
# evaluate an expression in reverse polish notation
# ie. 3, 4, +, 2, x, 1, +
# translates to (3+4) x 2 + 1
# approach, use a stack, push values in
# compute if an operator is seen and push back to stack
def evaluateRPN(exp):
# assumes a vaild RPN exp
exp = exp.split(',')
operators = ['+', '-', 'x',... |
# given an array of words and a set of words
# find the smallest subarray that contains all the words in the set
# approach, move right until we have a subarray that contains all words in the set
# the move left until it is lost and look right again, do this till the end
def smallestSubarray(paragraph, words):
p... |
# finding the least common ancestor for two nodes that have parent pointers
# approach is to first find the depths of each node and bring them to the same height
# from there, go up until they land on the same parent
# O(h), worse case traversal is the height of tree
# O(1), no additional space
from BinaryTreeNode i... |
# given a binary tree, return a list of lists
# each list containing the nodes at that height
# ie
# 5
# 4 3
# 1 6 9 8
# output should be, [[5], [4, 3], [1, 6, 9, 8]]
# approach is use a queue to hold the nodes at each level
# and a size variable indicating the number of nodes at that level
# as we move throu... |
# reversing a sublist in a linked list
from LinkedListNode import Node, printList
def reverseSublist(l, start, end):
# needs work, handling edge cases
# what if start is the head of the list?
# assume the list count start at 1
head = l
dummy_head = l
# move predecessor to the ... |
# delete duplicate items from a sorted array
# approach, step through and compare current idx with prev value
# if equal, go to next, if not, write to the next available slot
# O(n) time, one pass
# O(1) space
def deleteDuplicates(values):
write_idx = 1
length = len(values)
for i in range(1, length):
... |
# given a number, reverse the digits
# ie. 456 -> 654, -1235 -> -5321
# approach is to use modulo to slowly get the last digit
# O(n) time, n is the length of the number
# O(1) space
def reverseDigits(number):
neg = False
result = 0
remainingNum = number
# using module on a negative number gets rea... |
# implementing the height balance check for binary trees
# height balance is when the height on the left and the height on the right do not differ by more than 1
class BinaryTreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
de... |
##Converting excel file to CSV and also printing one column from the excel file in python
import pandas as pd
read_file = pd.read_excel (r'C:\Users\Owner PC\AppData\Local\Programs\Python\Python39\COVID19_03242020_ByCounty.xls')
read_file.to_csv (r'C:\Users\Owner PC\AppData\Local\Programs\Python\Python39\NEW_COVI... |
'''
El empleador esta celebrando aniversario y ofrecera a sus clientes una serie
de ofertas que se traduciran en incremeno de sus ventas. Las reglas de la
ofertas se basan en un porcentaje de descuento sobre el total de compra, que
estarian variando dependiendo del monto adquirido:
por un monto mayor o igual a $500 des... |
class Programa:
def __init__(self, nome, ano):
self._nome = nome.title()
self.ano = ano
self._likes = 0
@property
def likes(self):
return self._likes
@property
def nome(self):
return self._nome
@nome.setter
def nome(self, novo_nome):
self._n... |
# -*- coding: utf-8 -*-
# @Time : 17:39 2020/3/27 2020
# @Author : chuqiguang
# @FileName: 820.py
# @Software: PyCharm
class Solution(object):
def minimumLengthEncoding(self, words):
"""
:type words: List[str]
:rtype: int
"""
words.sort(key=lambda word: word[::-1])
... |
import os
import re
from datetime import datetime
import pandas as pd
def cleanData(filename, source, stopwords = []):
"""
Cleans up news in text-files
:param filename: file name
:param source: news source (investopedia/seekingalpha)
:param stopwords: list of stopwords to be removed from each se... |
# Scrabble 3D
# ------------------------------------------
# Author: Jake Kirsch
# Module: Helper Functions
# The purpose of this module is to hold some helper functions
# that make other modules more readable
def list_to_dict(letter_list):
'''
Helper function to quickly convert a string to a list
Parameters:
... |
li=[{"Product_id":"101",
"Name":"Laptop",
"Category":"ELectronics",
"Brand":"HP",
"Cost":500000,
"Rating":8.9,
"Discount":30
},
{"Product_id":"102",
"Name":"Mobile",
"Category":"Electronics",
"Brand":"Oneplus",
"Cost":30000,
"Rating":9.1,
"Discount":20},
{"Product_id":"103",
"Name":"Dress",
"Category":"Clothing",
"Bran... |
import numpy
class DataframeNumSummarizer():
def summary (df):
for colname, coltype in df.dtypes.iteritems():
if (coltype=="int64"):
print("Column " + colname + ":")
print("the minimum value is " + str(numpy.min(df[colname])))
print("the mean valu... |
# Initializing out blockchain list
blockchain = []
def get_last_blockchain_value():
""" Returns last value of current blockchain """
if len(blockchain) < 1:
return None
return blockchain[-1]
def add_transaction(transaction_amount, last_transaction=[1]):
""" Append a new value as well as the... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import random
versuche = 10
meine_zahl = random.randint(0, 100)
deine_zahl = 0
print("Ich habe mir eine Zahl zwischen 1 und 100 ausgedacht.")
print("Welche?")
# != bedeutet ungleich
while versuche > 0 and deine_zahl != meine_zahl:
# Eine Anweisung in Klammern kann üb... |
from typing import Dict, List, Union
from skyward_api.assignment import Assignment
class SkywardClass():
"""Object for class with grades.
Parameters
----------
name : str
Skyward name of class (e.g. "CLASS NAME (Period #) TEACHER NAME").
grades : List[Assignment]
Grades in the clas... |
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.linear_model import LogisticRegression
satisfaction_level = input('pls enter employee satisfaction based on a scale of 0.00 to 1.00: ')
last_eval... |
import pandas as pd
#the encoder module helps change the data in the table into numbers since ml doesnt understand words
from sklearn.preprocessing import LabelEncoder
from sklearn import tree
#opening data
df = pd.read_csv('google job data.csv')
#dropping the target column
inputs = df.drop('salary_more_than... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# define a variable with string but embedded with {} character to hold variables
formatter = "{} {} {} {}"
# print the variable formatter with values that contain integers, by introducing .format syntax
print(formatter.format(1, 2, 3, 4))
# like the previous one, but va... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from sys import argv
script, file1 = argv
weather_dict = {} # create a dict variable
with open(file1) as data_file:
for line in data_file:
key, value = line.strip().split(',')
# create a tuple and assign them with the strings splitted by ","? There is a pr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# python3 Py104_Ch2_realtime_weather.py
from sys import argv, exit
import requests, json
# testing blocks
#weather_dict = {'q':'city_name', 'APPID':'33f65ff60f2eb1575caa188775e86c28'}
#r = requests.get('https://api.openweathermap.org/data/2.5/weather', params=weather_dic... |
#https://www.kaggle.com/chapagain/titanic-solution-a-beginner-s-guide/notebook
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os, sys
#sns.set()
sys.__stdout__=sys.stdout
os.chdir(r'C:\Users\Thierry\Desktop\titanic')
#identify train & test sets
train=... |
import random
inventario = []
def start():
while True:
print(" Bem Vindo á MASMORRA DA MORTE")
print("\nComo the chamas?")
nome = input(">")
print("Bem vindo, ", nome)
print("\nNa tua frente tens uns portões ferruguentos que aparentam ter centenas de anos desde que foram abe... |
terbesar = []
while True:
n = int(input("Masukkan Bilangan N: "))
terbesar.append(n)
if n == 0:
break
print("Nilai Terbesar adalah : {}".format(max(terbesar))) |
##Count the number of words in a string, the words are separated by " "
def numberWord(string):
print(len(string.split()))
case1 = "Hi my name is Benny"
case2 = "Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression."
numberWord(case1)
numberWord(case2)
|
# Complete the solution so that it returns true if the first argument(string) passed in ends
# with the 2nd argument (also a string).
# Examples:
# solution('abc', 'bc') # returns true
# solution('abc', 'd') # returns false
def solution(string, ending):
endL = len(ending)
stringCompare = string[-endL:]... |
# In this Kata, you will be given a string that may have mixed uppercase and lowercase letters
# and your task is to convert that string to either lowercase only or uppercase only based on:
# make as few changes as possible.
# if the string contains equal number of uppercase and lowercase letters,
# convert the strin... |
# Your goal in this kata is to implement a difference function,
# which subtracts one list from another and returns the result.
# It should remove all values from list a, which are present in list b.
# array_diff([1,2],[1]) == [2]
# If a value is present in b, all of its occurrences must be removed from the other:
... |
# A pangram is a sentence that contains every single letter of the alphabet at least once.
# For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because
# it uses the letters A-Z at least once (case is irrelevant).
# Given a string, detect whether or not it is a pangram. Return True ... |
#Jun Kim CMDA CS 3654 Fall 2015
#Inclass4 Part 2
"""What does the code below do? Run the code in iPython.
For each line of code, add an explanation
through a comment."""
#PART I
#Prints a String
print "I will now count my chickens:"
#Prints number of hens and roosters are through the equation
print "Hens", 2... |
def revword(word):
return word[::-1]
def countword():
counter = 0
file = open(r'text.txt')
index = 0
for sentence in file:
if index == 0:
word = sentence.lower().rstrip()
index = index +1
counter = counter + 1
else:
sentence = sentence... |
# 1) Escreva um programa em python que conte as vogais que a música ‘Faroeste Caboclo’
# tem em sua letra. Armazena a letra da música em um arquivo do tipo txt.
# Dica: Não se esqueça de considerar as letras maiúsculas, minúsculas e com acentuação.
def contar_vogais():
pass
#vogais = {
# 'a': 0,
# ... |
###################################################
# Author: Dlambros #
# Date: Sun, Dec 28, 2014 #
# #
# Given: A file containing at most 1000 lines. #
# #
# Return: A file containing all the even-numbered #
# lines from the original file. Assume #
# 1-based numbering of lines. #
#... |
from sys import argv
# Get file name from argument passed while running the file
script, filename = argv
# Print the file name
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit ENTER.")
input("?")
print("Opening the file...")
# Open the file... |
from Tkinter import *
root = Tk ()
drawpad = Canvas(root, width=800,height=600, background='purple')
drawpad.grid(row=0, column=0)
circle = drawpad.create_oval(20, 20, 100, 100, fill='green')
direction = 1
def animate():
global direction
x1, y1, x2, y2 = drawpad.coords(circle)
if y2 > drawpad.winfo_heigh... |
result = []
def binary(A, n):
if (n<1):
result.append( ', '.join([ str(x) for x in A]))
else:
A[n-1] = 0
binary(A, n-1)
A[n-1] = 1
binary(A, n-1)
A = [ None ] * 3
print (A)
binary(A, 3)
print(result)
|
class HashTable:
def __init__(self):
self.size = 11;
self.slots = [None] * self.size
self.data = [None] * self.size
def hash(self, key):
return key % self.size
def rehash(self, oldhash):
return (oldhash+1) % self.size
def put(self, key, value):
hashva... |
from collections import Counter as mset
words1='hello yyyyyyy yzyzyzyzyzyz mellow well yo kellow lellow abcdefhijkl hi is yellow just here to add strings fellow lellow llleow'.split()
letters1='l e l o h m f y z a b w'.replace(' ','')
words2='sad das day mad den foot ball down touch pass play'.split()
letters2='z a d... |
import pandas as pd
from tkinter import *
from tkinter import filedialog
root = Tk()
file_name = filedialog.askopenfilename(title='choose an excel file',
initialdir='C:/Users',
filetypes=(('excel files', '*.xlsx'),
... |
#finput = input ("Enter the filename:")
fopen= open ("Your filename.txt")
tree=list() #define a empty list
for piece in fopen:
x=piece.split()
for individual in x:
if individual in tree:
continue
else:
tree.append(individual)
tree.sort()
print (tree)
|
# Neo has a complex matrix script. The matrix script is a X
# grid of strings. It consists of alphanumeric characters, spaces and symbols (!,@,#,$,%,&).
# To decode the script, Neo needs to read each column and select only the alphanumeric characters and connect them.
# Neo reads the column from top to bottom and start... |
import numpy as np
class first_n(object):
def __init__(self, n):
self.n = n
self.num = 0
def __iter__(self):
return self
def __next__(self):
return self.next()
def next(self):
if self.num < self.n:
cur, self.num = self.num, self.num+1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.