text stringlengths 37 1.41M |
|---|
import math
from collections import defaultdict
# Part 1
with open('day-1-input.txt') as f:
frequencies = [int(line.strip()) for line in f]
sum_frequencies = sum(frequencies)
print(sum_frequencies)
# Part 2
"""
from the n frequencies {f1, ... fn} we get sums {S1, ... Sn}
iterated = {S1, ... Sn, S1 + SUM, ... Sn ... |
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
Segment = namedtuple('Segment', ['point1', 'point2'])
Intersection = namedtuple('Intersection', ['wire1_segment', 'wire2_segment', 'point'])
with open('day-3-input.txt') as f:
wire_descriptions = [line.strip().split(',') for line in f]
wi... |
#Elizabeth Lin
#Word Jumble Program
#This game will give a random word(the order is random)from a list of words
#Then user need to guess the word
import random
#save some words which are chosen from the topic meteorology(Here use a tuple)
WORDS=("atmosphere","tornado","precipitation",
"convection","avalanche")
... |
import pandas as pd
class Order:
id = 0
def __init__ (self, quantity, price,buy = True):
self.quantity = quantity
self.price = price
self.buy = buy
self.ID = Order.id
Order.id += 1
def __repr__ (self):
return "Order(%s, %s, %s)" % (self.quantity, self.price... |
class Road:
__v = 25
def ves(self, _a, _l, _h):
print(f'Вес покрытия: {int(_a) * int(_l) * self.__v * int(_h)} тон')
Road_1 = Road()
z = input(' Введите параметры: ширина(м), длина(м), толщина(см): ').split(' ')
[_a, _l, _h] = z
Road_1.ves(_a, _l, _h)
|
from Calculator.Calculator import *
class Median:
@staticmethod
def median(data):
length = len(data)
s_data = sorted(data)
if length % 2 == 0:
median1 = s_data[length // 2]
median2 = s_data[length // 2 - 1]
median = Division.quotient(Addition.sum(med... |
import sys
import unittest
from lootbag import LootBag
# Items can be added to bag, and assigned to a child.
# Items can be removed from bag, per child. Removing ball from the bag should not be allowed. A child's name must be specified.
# Must be able to list all children who are getting a toy.
# Must be able to list... |
songs = {
('Nickelback', 'How You Remind Me'),
('Will.i.am', 'That Power'),
('Miles Davis', 'Stella by Starlight'),
('Nickelback', 'Animals')
}
# Set Comprehension: Correct Solution
good_songs = {(song[0], song[1]) for song in songs if song[0] != 'Nickelback'}
print(good_songs)
print(type(good_songs... |
#data önişlemleri için
import pandas as pd
#arraylerde işlemler yapmak için
import numpy as np
#dataseti yükledik
dataset = pd.read_csv('Social_Network_Ads.csv')
#id numarası gereksiz olduğu için atıyoruz
dataset =dataset.drop(['User ID'],axis=1)
#editting column name
dataset.rename(columns={'Ge... |
'''
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown b... |
'''
Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.
Example 1:
Input: A = "ab", B = "ba"
Output: true
Example 2:
Input: A = "ab", B = "ab"
Output: false
Example 3:
Input: A = "aa", B = "aa"
Output: true
Example 4:
Input: A = "a... |
'''
In a group of N people (labelled 0, 1, 2, ..., N-1), each person has different amounts of money, and different levels of quietness.
For convenience, we'll call the person with label x, simply "person x".
We'll say that richer[i] = [x, y] if person x definitely has more money than person y. Note that richer may o... |
# 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 largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if ... |
'''
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello"
Output: "holle"
Example 2:
Input: "leetcode"
Output: "leotcede"
Note:
The vowels does not include the letter "y".
'''
class Solution(object):
def reverseVowels(self, s):
"""
:type ... |
import collections
# 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 findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int... |
'''
Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.
Example 1:
Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, both strings are equa... |
'''
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
'''
# Definit... |
'''
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self... |
'''
Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.
Example 1:
Input:
"bbbab"
Output:
4
One possible longest palindromic subsequence is "bbbb".
Example 2:
Input:
"cbbd"
Output:
2
One possible longest palindromic subsequence is "bb".
'''
|
'''
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Exampl... |
# Uses python3
import sys
def get_optimal_value(capacity, weights, values):
value = 0.
for (v, w) in sorted([(v / w, w) for (w, v) in zip(weights, values)], reverse=True):
value += min(capacity, w) * v
capacity -= w
if (capacity <= 0):
break
return value
if __name__ =... |
weight = int(input("weight: "))
unit = input("lbs or kgs:choose L or K ")
if unit.upper() == "L":
conversion_1 = weight / 2.2
print(f'You are {conversion_1} kgs')
else:
conversion_2 = weight * 2.2
print(f'You are {conversion_2} lbs') |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
"""Several planned features that are under discussion / not implemented yet."""
from __future__ import annotations
from .annotation import MutableAnnotation
from .mutable import LabeledMutable, MutableSymbol, Categorical, Numerical
def randin... |
"""
Hello, NAS!
===========
This is the 101 tutorial of Neural Architecture Search (NAS) on NNI.
In this tutorial, we will search for a neural architecture on MNIST dataset with the help of NAS framework of NNI, i.e., *Retiarii*.
We use multi-trial NAS as an example to show how to construct and explore a model space.
... |
import datetime
def today():
now = datetime.datetime.now()
return now.strftime('%Y%m%d')
days = ['20180422', '20180423', '20180424','20180425', '20180426', '20180427', '20180428']
def td(t=0):
day = today()
td = '19700101'
for i,d in enumerate(days):
if d >= day:
... |
# Core Modules
import datetime
from datetime import date
today=date.today()
#today=datetime.date.today()
print(today)
import time
from time import time
timestamps=time()
#timestamps=time.time()
print(timestamps)
# ------------------------
# -----------------------
##pip module
from camelcase import CamelCase
c=Came... |
# A Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
# Create dict
person1={
'name':'bob smith',
'email':'bob@gmail.com',
'city':'boston',
'age':22
}
print(type(person1),person1)
# Use constructor
person2=dict(name='john doe',email='john@gmail.com',city='lo... |
#!/usr/bin/env python
def miles(kilometers: float) -> float:
"""
:param kilometers: float
:return: float
"""
return kilometers * 1.6
print(miles(2))
print(miles(3))
print(miles(4))
|
#!/usr/bin/env python
ph = float(input('Enter pH number: '))
if ph < 7.0:
print(ph, 'It is acidic')
if ph > 7.0:
print(ph, 'it is basic')
|
#!/usr/bin/env python
population = input("Please enter population value: ")
print("You have entered: ", population)
|
#!/usr/bin/env python
def average(grade1, grade2, grade3):
"""
Specify the grade between 0 and 100
:param grade1: number
:param grade2: number
:param grade3: number
:return: number
"""
return (grade1 + grade2 + grade3) / 3
print(average(30, 30, 30))
print(average(20,17,38))
|
#!/usr/bin/env python
rat_1 = [111, 112, 113, 114, 115, 116, 117, 118, 119, 120]
rat_2 = [101, 122, 117, 104, 110, 126, 137, 108, 109, 102]
if rat_1[0] > rat_2[0]:
print("Rat 1 weighed more than rat 2 on day 1")
else:
print("Rat 1 weighed less than rat 2 on day 1.")
if rat_1[0] > rat_2[0] and rat_1[9] > rat... |
"""Genetic algorithms methods for the travelling salesman problem."""
import random
import handies as hf
from collections import OrderedDict
cities = OrderedDict()
# cities_names = []
# cities_indices = []
EARTH_RADIUS = 6371
class Salesman(object):
"""salesman travelling around European Union.
Attr.:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 14 10:01:23 2019
@author: saurabh
"""
import random
cond=True
count=0
t=(random.randint(1,100))
while(cond):
user=int(input("Enter number : "))
if t>user:
print("enter greater number")
count+=1
elif t<user:
print... |
# Needed modules will be imported and configured.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# Output pin declaration for the LEDs.
LED_Red = 2
LED_Green = 3
GPIO.setup(LED_Red, GPIO.OUT, initial= GPIO.LOW)
GPIO.setup(LED_Green, GPIO.OUT, initial= GPIO.LOW)
print("LED-Test [press ctrl+c to e... |
#!/usr/bin/env python3
import itertools
def example():
data = """1721
979
366
299
675
1456""".splitlines()
a, b = list(
filter(
lambda p: p[0] + p[1] == 2020,
itertools.combinations((int(s) for s in data), 2),
)
)[0]
print(f"example: {a*b == 514579}")
def pr... |
# Your team is scrambling to decipher a recent message, worried it's a plot to break into a major European National Cake Vault.
# The message has been mostly deciphered, but all the words are backward! Your colleagues have handed off the last step to you.
# Write a function reverse_words() that takes a message as a li... |
from csp.variables import Variable
class Problem:
"""Class that represents a csp problem."""
def __init__(self):
self.variables = []
self.constraints = []
def add_variable(self, to_add):
"""Adds one or more variables to this problem.
It... |
from abc import ABC, abstractmethod
class DomainOrderingStrategy(ABC):
"""Abstract class for a variable domain ordering strategy."""
def __init__(self):
self.var = None
def setup(self, problem, propagator):
"""Called to initialize this ordering strategy with problem data.
:param... |
"write a pattern for recognizing a string which must contain at least two of the following words: legal, Trump, policy"
import re
def check_orangeman(text:str)->bool:
# Trump=r"Trump"
# legal=r"Legal"
# policy=r"policy"
words="(Trump|legal|policy).*(?!\1)(Trump|legal|policy)"
if(re.search... |
class Node:
"""
Class which represent a tree as a node, it use more or less the same notation as we used in prolog,
the only difference is that here we omit the nil value when there is an empty node.
"""
def __init__(self, value, left=None, right=None):
"""
Constructor for a node, t... |
#Program 9 Chapter 1
#Name: string rotation
# #Runtime: O(n)
#Date: 4/2/2019
#Notes: Given s1 (the unrotated string) and s2 (the rotated string), s2 will always be a substring of s1s1.
def rotation(str1, str2):
if len(str1) == len(str2):
str1str1 = str1 + str1
if str2 in str1str1:
ret... |
#Program 5 Chapter 1
#Name: One Away
#Runtime: O(n)
#Date: 4/1/2019
#Notes: The removed letter may not be duplicated in a row. For example, bye and byee will not work, since you can remove either one of the e's.
#However, it will work if they are separated by at least one other char, like bye and beye.
def oneAway(... |
# Implement a class to hold room information. This should have name and
# description attributes.
class Room:
"""Room object has a name and text"""
possible_moves = ["n_to", "s_to", "e_to", "w_to"]
def __init__(self, name, text, items=None):
self.name = name
self.text = text
if it... |
# !/user/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2021/6/8 11:27
# @Author : 王俊
# @File : hashmap.py
# @Software : PyCharm
"""
Entry表示一个Key-value键值对节点,在Python中的dict里面叫做items。
"""
class Entry():
def __init__(self, hash=0, key=0, value=0, next=None):
self.hash = hash
self.key =... |
def quicksort(array):
# print(array)
if len(array) < 2:
return array #Base case: arrays with 0 or 1 element are already “sorted.”
else:
pivot = array[0] #Recursive case
less = [i for i in array[1:] if i <= pivot] #Sub-array of all the elements less than the pivot
greater = [i for i in array[1:] if i > pivot]... |
class LinkedList:
def __init__(self, list = None):
self.head = None
if list is not None:
self.__create_linked_list_from_list(list)
def __create_linked_list_from_list(self, list):
'''
Creates a linked list from the elements in the list parameter
'''
if... |
from collections import deque
from TreeNode import *
class Solution:
# @param {TreeNode} root
# @return {TreeNode}
def invertTree(self,root):
if root is None:
return
self._invert_tree(root)
return root
def _invert_tree(self, node):
if node is None:
... |
from collections import OrderedDict
from typing import Dict, List, NewType, Optional, Tuple
from random import getrandbits
SquareParity = NewType('SquareParity', int)
SquareColor = NewType('SquareColor', int)
FillStrategy = NewType('FillStrategy', int)
BLACK = SquareParity(0)
WHITE = SquareParity(1)
NO_COLOR = Squa... |
from Simulation import Simulation # This class contains the major methods required.
# Arguement carries population size
s1 = Simulation(100000) # This initiated the variable for population size.
s1.generatePopulation() # This generates the population as per the desired size.
s1.playSimulation() # This m... |
#3-1
names = ['toni', 'john', 'nipsey']
for name in names:
print(name)
#3-2
for name in names:
print(f"Wassup {name.title()} how you doing")
#3-3
cars = ['bmw','benz','audi']
for car in cars:
print(f"I would like to own a {car}")
|
#3-8
locations = ['jozi', 'kapa', 'durban']
print(locations)
print(sorted(locations))
print(locations)
print(sorted(locations, reverse=True))
print(locations)
locations.reverse()
print(locations)
locations.reverse()
print(locations)
locations.sort()
print(locations)
locations.sort(reverse =True)
print(locations)
#3-9
... |
#8-3
def make_shirt(size,text):
print(f"Shirt size is: {size} \nShirt text is: {text}")
#8-4
def make_shirt(size = 'large',text = 'i love python'):
print(f"Shirt size is: {size} \nShirt text is: {text}")
make_shirt(text = 'life is good')
#8-5
def make_cities(city, country = 'South Africa'):
print(f"{city} is in {c... |
from random import choice
questions = ["why do we need nice cars?: ", "why do we need to relieve?: "]
question = choice(questions)
awnser = input(question).strip().lower()
while awnser != "just because":
awnser= input("why?: ")
|
#2-3
name = "Thonipho"
print(f"Hello {name}, would you like to learn today?")
#2-4
print(name.lower())
print(name.upper())
print(name.title())
#2-5
print("Nipsey Hussle once said, im the type to go and go get it")
#2-6
famous_person = "Nipsey Hussle"
message = "im the type to go and go get it"
print(f"{famous_person... |
#!/usr/bin/env python3
# Copyright (c) 2016 Anki, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License in the file LICENSE.txt or at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... |
import numpy as np
#Start_probability is for if it rain or not today given the last day
#Transition is the probability for rain or sun, given umberella.
rain = [True, False] #different state it can be, in this case it is rain or not rain.
start_prob = np.array([0.5, 0.5]) #Start probability P(X1) = 0.5
transition... |
class Car:
# constructor
def __init__(self, name, year):
self.name = name
self.year = year
def describe(self):
print('The car is a', self.name)
def move(self, direction):
print('The class', self.__class__.__name__, 'is moving towards the', direction)
if __name__ == '... |
higher_order_func = lambda x, func: x + func(x)
if __name__ == '__main__':
sum_func = (lambda x, y: x + y)
_sum = sum_func(7, 3)
print(_sum)
print(higher_order_func(2, lambda x: x**2))
print(higher_order_func(3, lambda x: x + 3)) |
# Problem Set 4C
# Name: Matthew Vogel
# Collaborators:
# Time Spent: x:xx
import string
from ps4a import get_permutations
import re
### HELPER CODE ###
def load_words(file_name):
'''
file_name (string): the name of the file containing
the list of words to load
Returns: a list of valid words... |
import math
digit = raw_input('What digit to go to?')
digit = int(digit)
if digit < 40:
print(float(round(math.pi, digit)))
else:
print("Sorry, digit is too large")
|
#!/usr/bin/env python2
# CodeEval Challenge - Reverse Words
# https://www.codeeval.com/open_challenges/8/
import sys
with open(sys.argv[1], 'r') as f:
lines = open(sys.argv[1], 'r').readlines()
for line in lines:
words = line.split()[::-1]
if len(words) == 0: # line is empty
continue
for... |
#!/usr/bin/env python2
# CodeEval - Stack Implementation
# https://www.codeeval.com/open_challenges/9/
import sys
def push(list_x, int_y):
'''Append int to list'''
list_x.append(int_y)
def pop(list_x):
'''Remove and return last item in list'''
last_int = list_x[-1]
del(list_x[-1])
return las... |
#!/usr/bin/env python2
# CodeEval - Penultimate Word
# https://www.codeeval.com/open_challenges/92/
from sys import argv
with open(argv[1], "rt") as f:
lines = f.readlines()
for line in lines:
words = line.strip().split()
print(words[-2])
|
#!/usr/bin/env python2
# CodeEval - Text Dollar
# https://www.codeeval.com/open_challenges/52/
from sys import argv
single_digits = ("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine")
teens = ("Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "N... |
#!/usr/bin/env python2
# Rightmost Char
# https://www.codeeval.com/open_challenges/31/
import sys
with open(sys.argv[1], "r") as f:
file_contents = f.readlines()
for line in file_contents:
string_s, t = line.strip().split(",")
if t in string_s:
print( string_s.index(t) )
else:
print(-... |
#!/usr/bin/env python2
"""
- CodeEval: Filename Pattern
- https://www.codeeval.com/open_challenges/169/
"""
from fnmatch import fnmatch
from sys import argv
def match_filenames(pattern, file_names):
match_filenames = []
for i in file_names:
if fnmatch(i, pattern):
match_filenames.append(i... |
#!/usr/bin/env python2
# CodeEval - Reverse and Add
# https://www.codeeval.com/open_challenges/45/
from sys import argv
def reverse_add(interger_str):
reverse_str = interger_str[::-1]
sum_ = int(interger_str) + int(reverse_str)
return str(sum_)
def is_palindrome(interger_str):
if interger_str == int... |
#!/usr/bin/python3
import sys
nombre_marches = int( sys.argv[1] )
print(nombre_marches)
for i in range(nombre_marches):
string = ' ' * (nombre_marches + 1 - i) + '#' * (i + 1)
print (string)
|
from math import *
import random
class matrix:
def __init__(self, value):
self.value = value
self.dimx = len(value)
self.dimy = len(value[0])
if value == [[]]:
self.dimx = 0
def zero(self, dimx, dimy):
# verificar dimensiones
if dimx < 1 or di... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author: Chris Berardi
Solution to Week 2 Assignment for Stat656 Spring 2018
Uses Python to preprocess and clean data
"""
import pandas as pd
import numpy as np
from sklearn import preprocessing
file_path = 'C:/Users/Saistout/Desktop/656 Applied Analytics/Data/'
cre... |
#we will represent a sudoku grid with a list of lists
# the first list represents the first row and so forth
# any empty places are represented with a 0
# a sudoku puzzle is usually 9 x 9
# valid returns true if the current puzzle is in a valid state, and false otherwise
# we consider a state valid if there ... |
n1 = int(input('Digite o primeiro numero '))
n2 = int(input('Digite o segundo numero '))
n3 = int(input('Digite o terceiro numero '))
if n1 > n2 and n1 > n3:
maior = n1
elif n2 > n3:
maior = n2
else:
maior = n3
if n1 < n2 and n1 < n3:
menor = n1
elif n2 < n3:
menor = n2
else:
menor = n3
print... |
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
media = (n1 + n2) / 2
if media >= 7.0:
print(f'Sua media foi {media} e você esta aprovado')
elif media >= 5.0:
print(f'Sua media foi {media} e você esta de recuperação')
else:
print(f'Sua media foi {media} e você esta... |
import random
pc = random.randint(1, 5)
jogador = int(input('Digite um numero: '))
if pc == jogador:
print(f'Parabens você ganhou, eu tambem pensei no numero {pc}')
else:
print(f'Eu ganhei, pensei no numero {pc}')
|
numero = int(input('Digite um numero '))
u = numero // 1 % 10
d = numero // 10 % 10
c = numero // 100 % 10
m = numero // 1000 % 10
print(f'Unidade {u}')
print(f'Dezena {d}')
print(f'Centena {c}')
print(f'Milhar {m}')
|
nome = str(input('Digite seu nome completo ')).strip()
maisculas = nome.upper()
minusculas = nome.lower()
letras = len(nome) - nome.count(' ')
primeiro = nome.find(' ')
print(f'Seu nome em maiusculas é {maisculas}')
print(f'Seu nome em minusculas é {minusculas}')
print(f'Seu nome tem ao todo {letras} letras')
print(f'S... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 5 20:36:03 2018
8 二叉树的下一个结点
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。
注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
@author: situ
"""
tin = {8,6,10,5,7,9,11}
pNode = 8
#对应输出应该为:9
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.r... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 9 22:50:00 2018
17 打印从1到最大的n位数
@author: situ
"""
def Print1ToMaxOfNDigits_1(n):
Max = int("9"*n)
for i in range(1,Max+1):
print(i) |
# -*- coding: utf-8 -*-
"""
Created on Sun May 6 16:59:50 2018
12 矩阵中的路径
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。
路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。
如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,
因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
@author: situ
""... |
import math
import numpy
#PARAMS:
# seen: list of 2 dictionaries, corresponding to female and male respectively
# Each dict of the form {word:count},
# where all of the words are associated
# with their respective counts of appearence
# aggregated over all of that gender's blog posts
#
# n:... |
string = list(input())
up = 0
lo = 0
for i in string:
if i.isupper():
up += 1
#print("IN upper")
else:
lo += 1
# print("In lower")
if up > lo:
string = ''.join(string)
string = string.upper()
else:
string = ''.join(string)
string = string.lower()
print(string) |
#Let's assume that a song consists of some number of words.
# To make the dubstep remix of this song, Vasya inserts a certain number of words "WUB"
# before the first word of the song (the number may be zero), after the last word (the number may be zero),
# and between words (at least one between any pair of neighbo... |
#Chef has a number D containing only digits 0's and 1's.
# He wants to make the number to have all the digits same.
# For that, he will change exactly one digit, i.e. from 0 to 1 or from 1 to 0.
# If it is possible to make all digits equal (either all 0's or all 1's) by flipping exactly 1 digit then output "Yes", else ... |
#You are given a string.
# Your task is to determine whether number of occurrences of some character in the string is equal to the sum of the numbers of
# occurrences of other characters in the string.
for i in range(int(input())):
s = input()
c = []
flag = 1
st = list(set(s))
for j in st:
... |
print("Enter the elements")
li = [int(x) for x in input().split()]
unique = set(li)
print("Maximum element in the set:",max(unique))
print("Minimum element in the set:",min(unique)) |
for i in range(int(input())):
salary = int(input())
if salary < 1500:
gross = salary + ((10 * salary) + (90 * salary))/100
else:
gross = salary + 500 + (98*salary)/100
print('%.2f'%gross) |
#Program to obtain a number and print how many digits number is it
def digitCount(number):
digits = 0
while(number > 0):
digits += 1
number //= 10
return digits
number = int(input())
print("the number of digits in the number are:",digitCount(number)) |
def split_and_join(line):
line = line.split(" ")
newline = '-'.join(line)
return newline
line = input()
result = split_and_join(line)
print(result) |
import gym
import numpy as np
env = gym.make("MountainCar-v0")
LEARNING_RATE = 0.1
DISCOUNT = 0.95
# how important future rewards are, compared to current rewards
EPISODES = 25000
# measure of how often to do a 'random' action and explore
epsilon = 0.5
# we dont want to always do a random action. decay lowers the amo... |
class HTNode(object):
def __init__(self, item, next):
self.item = item
self.next = next
class hash_table(object):
def __init__(self, table_size):
self.size = 0
self.table = [None] * table_size
# hash function using the first letter in each word to place words
d... |
"""
Basic console application that allows the user to guess
the outcome of a random coin flip or dice roll
"""
import time, random
def coin_flip():
global correct
global total
global start
print(f"Your score is {correct} out of {total}")
guess_coin = input("Heads or tails? >>> ").lower().replac... |
#!/usr/bin/env python3
import sys
import math
from collections import namedtuple as t
######################Helping definitions##########################
Planet = t('Planet', [
'name',
'parent',
'child'
])
Orbit = t('Orbit', [
'center',
'child'
])
Traversal = t('Traversal', [
'seen',
... |
#Write a program which will: Ask for two numbers. Then offers a menu to the user giving them a choice of operator e.g. – Enter “a” if you want to add “b” if you want to subtract Etc. Include +, -, /, *, **(to the power of) and square.
#define my function
def calculator():
#cast inputs to floats to get two float inp... |
#Define method which takes number and returns depending if even or odd a return value
def collatz(number):
calculatedNumber = 0
if number%2 == 0:
calculatedNumber = number//2
else:
calculatedNumber = number * 3 + 1
print(calculatedNumber)
return calculatedNumber
#User input
t... |
'''
https://open.kattis.com/problems/icpcteamselection
'''
import sys
def test():
assert(solve([9, 8, 10, 9, 6, 8], 2) == 17)
assert(solve([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) == 18)
assert(solve([1, 100, 51], 1) == 51)
assert(solve([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3], 4) == 21)
print("All Tests Passed... |
# Задача-1:
# Дан список, заполненный произвольными целыми числами, получите новый список,
# элементами которого будут квадратные корни элементов исходного списка,
# но только если результаты извлечения корня не имеют десятичной части и
# если такой корень вообще можно извлечь
# Пример: Дано: [2, -5, 8, 9, -25, 25, 4] ... |
# Задача-2:
# Даны два произвольные списка.
# Удалите из первого списка элементы, присутствующие во втором списке.
a=[1,2,3,3,4,4,5,6,10,12]
b=[3,4,5,6,7,8]
a = list(set(a) - set(b))
print(a)
|
class Program:
def __init__(self, name, weight, sub):
self.name = name
self.weight = weight
self.cum_weight = weight
# A leaf is balanced
self.balanced = True
# Construct the sub nodes
self.sub = []
for i in sub:
self.sub.append(Program(*t... |
from __future__ import print_function, unicode_literals
"""
1a. Create an ssh_conn function. This function should have three parameters: ip_addr, username,
and password. The function should print out each of these three variables and clearly indicate which
variable it is printing out.
Call this ssh_conn function u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.