hackerrank(python)

 ####第0天:你好,世界。


# Read a full line of input from stdin and save it to our dynamically typed variable, input_string.
input_string = input()

# Print a string literal saying "Hello, World." to stdout.
print('Hello, World.')

# TODO: Write a line of code here that prints the contents of input_string to stdout.
print(input_string)

第1天:数据类型 

i = 4
d = 4.0
s = 'HackerRank '
# Declare second integer, double, and String variables.
n = int(input())
do = float(input())
st = input()
# Read and save an integer, double, and String to your variables.

# Print the sum of both integer variables on a new line.
print(n + i)
# Print the sum of the double variables on a new line.
print(d + do)
# Concatenate and print the String variables on a new line
# The 's' variable above should be printed first.
print(s + st)

 第2天:运营商


import math
import os
import random
import re
import sys

# Complete the solve function below.
def solve(meal_cost, tip_percent, tax_percent):
   tip = meal_cost * (tip_percent/100)
   tax = meal_cost * (tax_percent/100)
   total = meal_cost + tip + tax
   return round(total)

if __name__ == '__main__':
    meal_cost = float(input())

    tip_percent = int(input())

    tax_percent = int(input())

    print(solve(meal_cost, tip_percent, tax_percent))

 第3天:有条件陈述的介绍

import math
import os
import random
import re
import sys

if __name__ == '__main__':
    N = int(input())
    if N%2 == 1:
        print("Weird")
    else:
        if (N>2 and N <5) or N > 20:
            print("Not Weird")
        else:
            print("Weird")

第4天:课程与实例

class Person:
    def __init__(self,initialAge):
        
        if initialAge<0:
            print("Age is not valid, setting age to 0.")
            self.age = 0
        else:
            self.age = initialAge
        # Add some more code to run some checks on initialAge
    def amIOld(self):
        if self.age < 13:
            print("You are young.")
        elif self.age>= 13 and self.age <18:
            print("You are a teenager.")
        else:
            print("You are old.")
        # Do some computations in here and print out the correct statement to the console
    def yearPasses(self):
        self.age +=1
        # Increment the age of the person in here

t = int(input())
for i in range(0, t):
    age = int(input())         
    p = Person(age)  
    p.amIOld()
    for j in range(0, 3):
        p.yearPasses()       
    p.amIOld()
    print("")

第5天:循环

import math
import os
import random
import re
import sys

if __name__ == '__main__':
    n = int(input())
    i = 0
    while i < 10:
        i += 1
        print("%d x %d = %d" % (n,i,n*i))
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
N = int(raw_input().strip())
for i in range(1, 10 + 1):
    print N, "x", i, "=", N*i

第6天:让我们回顾一下 

t = int(raw_input())
for _ in range(t):
    line = raw_input()
    first = ""
    second = ""

    for i, c in enumerate(line):
        if (i & 1) == 0:
            first += c
        else:
            second += c
    print first, second
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
t = int(input())
while t > 0:
    n = input()
    print(n[::2], n[1::2])
    t = t-1

第7天:阵列

if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().rstrip().split()))
    for i in arr[::-1]:
        print(i,end=" ")

第8天:词典和地图

# Enter your code here. Read input from STDIN. Print output to STDOUn = int()
n = int(input())
dic = {}
for i in range(n):
    k,v=(i for i in input().split())
    dic[k]=v
while True:
    n = input()
    if n in dic:
        print('%s=%s' % (n,dic[n]))
    else:
        print("Not found")
 #########################################
n = int(input())
phoneBook = {}
for i in range(n):
    contact = input().split(' ')
    phoneBook[contact[0]] = contact[1]

# Process Queries
lines = sys.stdin.readlines()
for i in lines:
    name = i.strip()
    if name in phoneBook:
        print(name + '=' + str( phoneBook[name] ))
    else:
        print('Not found')

第9天:递归3 

def factorial(n):
    arr = [1]
    for i in range(1,n):
        arr.append(arr[-1]*(i+1))
    return arr[-1]

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    result = factorial(n)

    fptr.write(str(result) + '\n')

    fptr.close()

第10天:二进制数

if __name__ == '__main__':
    n = int(input())
    max = 0
    li = 0
    while n >0:
        if n%2 == 1:
            li += 1
            if li > max:
                max = li
        else:
            li = 0
        n = n//2
    print(max)

第11天:2D阵列

import math
import os
import random
import re
import sys
if __name__ == '__main__':
    arr = []
    for i in range(6):
        arr.append(list(map(int, input().rstrip().split())))
    max = -9999
    li = 0
    for i in range(4):
        for j in range(4):
            li = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]
            if li > max:
                max = li
    print(max)    

第12天:继承 

class Person:
	def __init__(self, firstName, lastName, idNumber):
		self.firstName = firstName
		self.lastName = lastName
		self.idNumber = idNumber
	def printPerson(self):
		print("Name:", self.lastName + ",", self.firstName)
		print("ID:", self.idNumber)
class Student(Person):
    def __init__(self, firstName, lastName, idNumber, scores):
        Person.__init__(self, firstName, lastName, idNumber)
        self.scores = scores
    #   Class Constructor
    def calculate(self):
        average = 0
        for i in self.scores:
            average +=i
        average = average / len(self.scores)
        
        if(average >= 90):
            return 'O' # Outstanding
        elif(average >= 80):
            return 'E' # Exceeds Expectations
        elif(average >= 70):
            return 'A' # Acceptable
        elif(average >= 55):
            return 'P' # Poor
        elif(average >= 40):
            return 'D' # Dreadful
        else:
            return 'T' # Troll

line = input().split()
firstName = line[0]
lastName = line[1]
idNum = line[2]
numScores = int(input()) # not needed for Python
scores = list( map(int, input().split()) )
s = Student(firstName, lastName, idNum, scores)
s.printPerson()
print("Grade:", s.calculate())
##########################################################
class Student(Person):
    def __init__(self, firstName, lastName, idNumber, scores):
        Person.__init__(self, firstName, lastName, idNumber)
        self.testScores = scores
		
    def calculate(self):
        average = 0
        for i in self.testScores:
            average += i

        average = average / len(self.testScores)
		
        if(average >= 90):
            return 'O' # Outstanding
        elif(average >= 80):
            return 'E' # Exceeds Expectations
        elif(average >= 70):
            return 'A' # Acceptable
        elif(average >= 55):
            return 'P' # Poor
        elif(average >= 40):
            return 'D' # Dreadful
        else:
            return 'T' # Troll

第13天:抽象类

from abc import ABCMeta, abstractmethod
class Book(object, metaclass=ABCMeta):
    def __init__(self,title,author):
        self.title=title
        self.author=author   
    @abstractmethod
    def display(): pass
class MyBook():
    def __init__(self,title,author,price):
        self.title = title
        self.author = author
        self.price = price
    def display(self):
        print("Title:",self.title)
        print("Author:",self.author)
        print("Price:",self.price)
title=input()
author=input()
price=int(input())
new_novel=MyBook(title,author,price)
new_novel.display()

第14天:范围

class Difference:
    def __init__(self, a):
        self.__elements = a
    def computeDifference(self):
        ele = sorted(self.__elements)
        arr = []
        for i in range(len(self.__elements)):
            for j in range(i,len(self.__elements)):
                arr.append(abs(ele[i] - ele[j]))
        self.maximumDifference = max(arr)

    def maximumDifference(self):
        p = max(arr)
        return p
###找出啊最大最小值相减也可
# End of Difference class

_ = input()
a = [int(e) for e in input().split(' ')]

d = Difference(a)
d.computeDifference()

print(d.maximumDifference)

第15天:链接列表

class Node:
    def __init__(self,data):
        self.data = data
        self.next = None 
class Solution: 
    def display(self,head):
        current = head
        while current:
            print(current.data,end=' ')
            current = current.next

    def insert(self,head,data):
        if head == None:
            head = Node(data)
            return head
        else:
            lis = head
            while lis.next:
                lis = lis.next
            lis.next = Node(data)
            return head
    #Complete this method

mylist= Solution()
T=int(input())
head=None
for i in range(T):
    data=int(input())
    head=mylist.insert(head,data)    
mylist.display(head); 

第16天:异常 - 字符串到整数

S = input().strip()
try:
    print(int(S))
except:
    print("Bad String")

第17天:更多例外

#Write your code here
class Calculator():
        
    def power(self,n,p):
        self.n = n
        self.p = p
        if n<0 or p<0:
            raise Exception("n and p should be non-negative")
        else:
            return n**p
myCalculator=Calculator()
T=int(input())
for i in range(T):
    n,p = map(int, input().split())
    try:
        ans=myCalculator.power(n,p)
        print(ans)
    except Exception as e:
        print(e)   

第18天:队列和筹码

class Solution:
    # Write your code here
    def __init__(self):
        self.push = []
        self.en = []
        return(None)
    def pushCharacter(self,s):
        self.push.append(s)
    def enqueueCharacter(self,s):
        self.en.append(s)
    def popCharacter(self):
        return(self.push.pop(0))
    def dequeueCharacter(self):
        return(self.en.pop(-1))
# read the string s
s=input()
#Create the Solution class object
obj=Solution()   

l=len(s)
# push/enqueue all the characters of string s to stack
for i in range(l):
    obj.pushCharacter(s[i])
    obj.enqueueCharacter(s[i])
    
isPalindrome=True
'''
pop the top character from stack
dequeue the first character from queue
compare both the characters
''' 
for i in range(l // 2):
    if obj.popCharacter()!=obj.dequeueCharacter():
        isPalindrome=False
        break
#finally print whether string s is palindrome or not.
if isPalindrome:
    print("The word, "+s+", is a palindrome.")
else:
    print("The word, "+s+", is not a palindrome.") 

第19天:界面

class AdvancedArithmetic(object):
    def divisorSum(n):
        raise NotImplementedError

class Calculator(AdvancedArithmetic):
    def divisorSum(self, n):
        return sum([i for i in range(1,n+1) if(n%i==0)])
        pass

n = int(input())
my_calculator = Calculator()
s = my_calculator.divisorSum(n)
print("I implemented: " + type(my_calculator).__bases__[0].__name__)
print(s)

第20天:排序

import sys

n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
# Write Your Code Here
num = 0
for i in range(len(a)):
    for j in range(len(a)-1):
        if a[j]>a[j+1]:
            a[j],a[j+1] =a[j+1],a[j]
            num += 1
print("Array is sorted in %d swaps." % num)
print("First Element: %d" % a[0])
print("Last Element: %d" % a[-1])

第21天:泛型

import java.util.*;

class Printer  {

    /**
    *    Method Name: printArray
    *    Print each element of the generic array on a new line. Do not return anything.
    *    @param A generic array
    **/
    
    // Write your code here
public static  void printArray(E[] generic){
    for(E element : generic) {
        System.out.println(element); 
    }
}
}

public class Generics {
    
    public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        Integer[] intArray = new Integer[n];
        for (int i = 0; i < n; i++) {
            intArray[i] = scanner.nextInt();
        }

        n = scanner.nextInt();
        String[] stringArray = new String[n];
        for (int i = 0; i < n; i++) {
            stringArray[i] = scanner.next();
        }
        
        Printer intPrinter = new Printer();
        Printer stringPrinter = new Printer();
        intPrinter.printArray( intArray  );
        stringPrinter.printArray( stringArray );
        if(Printer.class.getDeclaredMethods().length > 1){
            System.out.println("The Printer class should only have 1 method named printArray.");
        }
    } 
}

第22天:二进制搜索树

class Node:
    def __init__(self,data):
        self.right=self.left=None
        self.data = data
class Solution:
    def insert(self,root,data):
        if root==None:
            return Node(data)
        else:
            if data<=root.data:
                cur=self.insert(root.left,data)
                root.left=cur
            else:
                cur=self.insert(root.right,data)
                root.right=cur
        return root
    def getHeight(self,root):
        if root==None:
            return -1
        else:
            left = self.getHeight(root.left)
            right = self.getHeight(root.right)
            if left >right:
                return left +1
            else:
                return right +1
T=int(input())
myTree=Solution()
root=None
for i in range(T):
    data=int(input())
    root=myTree.insert(root,data)
height=myTree.getHeight(root)
print(height) 
###############################################
    def getHeight(self, root):
        if root == None:
            return -1
        else:
            return 1 + max( self.getHeight(root.left), self.getHeight(root.right) )      

第23天:BST级别订单遍历

import sys

class Node:
    def __init__(self,data):
        self.right=self.left=None
        self.data = data
class Solution:
    def insert(self,root,data):
        if root==None:
            return Node(data)
        else:
            if data<=root.data:
                cur=self.insert(root.left,data)
                root.left=cur
            else:
                cur=self.insert(root.right,data)
                root.right=cur
        return root
    def levelOrder(self,root):
        p = []
        p.append(root)
        while p:
            print(p[0].data,end=" ")
            if p[0].left:
                p.append(p[0].left)
            if p[0].right:
                p.append(p[0].right)
            p.pop(0)

T=int(input())
myTree=Solution()
root=None
for i in range(T):
    data=int(input())
    root=myTree.insert(root,data)
myTree.levelOrder(root)
###############################################################
    def levelOrder(self, root):
        traversal = ''
        
        if root != None:
            queue = [root]
            while len(queue) != 0:
                traversal += str(queue[0].data) + ' '
                if queue[0].left != None:
                    queue.append(queue[0].left)
                if queue[0].right != None:
                    queue.append(queue[0].right)
                queue.pop(0)
        print(traversal)

第24天:更多链接列表

class Node:
    def __init__(self,data):
        self.data = data
        self.next = None 
class Solution: 
    def insert(self,head,data):
            p = Node(data)           
            if head==None:
                head=p
            elif head.next==None:
                head.next=p
            else:
                start=head
                while(start.next!=None):
                    start=start.next
                start.next=p
            return head  
    def display(self,head):
        current = head
        while current:
            print(current.data,end=' ')
            current = current.next

    def removeDuplicates(self,head):
        if head == None:
            return head
        p = head
        while p.next:
            if p.data == p.next.data:
                p.next = p.next.next
            else:
                p = p.next
        return head
        

mylist= Solution()
T=int(input())
head=None
for i in range(T):
    data=int(input())
    head=mylist.insert(head,data)    
head=mylist.removeDuplicates(head)
mylist.display(head); 

第25天:运行时间和复杂性

import math

def isPrime(n):
    if n == 2:
        return True
    elif n == 1 or (n & 1) == 0:
        return False
        
    for i in range(2, math.ceil(math.sqrt(n)) + 1):
        if (n % i) == 0:
            return False
    
    return True

p = int(input())
for i in range(0, p):
    x = int(input())

    s = "Prime" if (isPrime(x)) else "Not prime"
    print(s)
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
import math
n = int(input())

for i in range(n):
    num = int(input())
    flag = 1
    if num < 2 or num%2 == 0:
        flag = 0
    if num == 2:
        flag = 1
    for j in range(3,int(math.sqrt(num)+1),2):
        if num%j == 0:
            flag = 0
            break
    if flag == 1:
        print("Prime")
    else:
        print("Not prime")
#######
素数,偶数肯定不是;质因子存在于n/2以下,且一定不大于开方n

第26天:嵌套逻辑

b = list(map(int, input().strip().split(' ')))
a = list(map(int, input().strip().split(' ')))
if b[0]<=a[0] and b[1]<=a[1] and b[2]<=a[2]:
    print(0)
elif b[2]a[0] and b[1]==a[1] and b[2]==a[2]:
    print(15*(b[0]-a[0]))
elif  b[1]>a[1] and b[2]==a[2]:
    print(500*(b[1]-a[1]))
else:
    print(10000)

第27天:测试

def minimum_index(seq):
    if len(seq) == 0:
        raise ValueError("Cannot get the minimum value index from an empty sequence")
    min_idx = 0
    for i in range(1, len(seq)):
        if seq[i] < seq[min_idx]:
            min_idx = i
    return min_idx
from random import randint

class TestDataEmptyArray(object):  
    @staticmethod
    def get_array():
        # complete this function
        return []
class TestDataUniqueValues(object):
    data = set()
    while len(data) < 10:
        data.add(randint(0, 100))

    @staticmethod
    def get_array():
        # complete this function
        data = TestDataUniqueValues.data
        return list(data)

    @staticmethod
    def get_expected_result():
        # complete this function
        data = TestDataUniqueValues.get_array()
        return data.index(min(data))

class TestDataExactlyTwoDifferentMinimums(object):
    data = set()
    while len(data) < 9:
        data.add(randint(0, 100))
    newData = list(data)
    newData.append(min(newData))

    @staticmethod
    def get_array():
        # complete this function
         data =  TestDataExactlyTwoDifferentMinimums.newData
         return data
    @staticmethod
    def get_expected_result():
        # complete this function
        data = TestDataExactlyTwoDifferentMinimums.get_array()
        return data.index(min(data))
def TestWithEmptyArray():
    try:
        seq = TestDataEmptyArray.get_array()
        result = minimum_index(seq)
    except ValueError as e:
        pass
    else:
        assert False
def TestWithUniqueValues():
    seq = TestDataUniqueValues.get_array()
    assert len(seq) >= 2

    assert len(list(set(seq))) == len(seq)

    expected_result = TestDataUniqueValues.get_expected_result()
    result = minimum_index(seq)
    assert result == expected_result

def TestiWithExactyTwoDifferentMinimums():
    seq = TestDataExactlyTwoDifferentMinimums.get_array()
    assert len(seq) >= 2
    tmp = sorted(seq)
    assert tmp[0] == tmp[1] and (len(tmp) == 2 or tmp[1] < tmp[2])

    expected_result = TestDataExactlyTwoDifferentMinimums.get_expected_result()
    result = minimum_index(seq)
    assert result == expected_result
TestWithEmptyArray()
TestWithUniqueValues()
TestiWithExactyTwoDifferentMinimums()
print("OK")

第28天:RegEx,模式和数据库简介

import math
import os
import random
import re
import sys



if __name__ == '__main__':
    N = int(input())
    li = []
    for N_itr in range(N):
        firstNameEmailID = input().split()

        firstName = firstNameEmailID[0]

        emailID = firstNameEmailID[1]
        firemailID = emailID.split("@")[1]
        if firemailID == "gmail.com":
            li.append(firstName)
    lie = sorted(li)
    for i in lie:
        print(i)

第29天:按位AND

import math
import os
import random
import re
import sys
from itertools import combinations
if __name__ == '__main__':
    t = int(input())
    for t_itr in range(t):
        nk = input().split()
        n = int(nk[0])
        k = int(nk[1])
        print(k-1 if (k-1) | k <=n  else k-2)
       #print (max([a&b for a,b in combinations(range(1,n+1), 2) if a&b < k]))

 

你可能感兴趣的:(python)