Год в век Функция
Проблема: если дан год, верните тот век, в котором он находится. Первый век охватывает период от 1 года до 100 года включительно, второй - от 101 года до 200 года включительно и т. Д.
Мой код:
def centuryFromYear(year):
century = year/100
decimal = int(str(century[-2:-1]))
integer = int(str(century)[:2])
if decimal > 0:
return integer + 1
else:
return integer
print(centuryFromYear(2017))
Это не похоже на работу в определенных случаях. например, когда год = 2001 или год = 2000.
Кто-нибудь сможет предоставить более простой кусок кода?
14 ответов
Вы можете использовать целочисленное деление, оператор //
в питоне 3:
def centuryFromYear(year):
return (year) // 100 + 1 # 1 because 2017 is 21st century, and 1989 = 20th century
print(centuryFromYear(2017)) # --> 21
Обратите внимание: это не относится к веку до нашей эры, и в нем используется дата Dec 31st xy99
где это иногда строго определяется как Dec 31st xy00
больше информации здесь
если вы хотите установить отсечение на Dec 31st xy00
, что более строгое, вы, вероятно, захотите сделать так:
def centuryFromYear(year):
return (year - 1) // 100 + 1 # 1 because 2017 is 21st century, and 1989 = 20th century
print(centuryFromYear(2017)) # --> 21
Простое однострочное решение Python и однострочное решение JavaScript
Используйте встроенные математические функции в javascript для однострочного ответа
Функция Math.ceil всегда округляет число до следующего по величине целого или целого числа.
// Python one-liner solution
def centuryFromYear(year):
return (year + 99) // 100
// Javascript one-liner solution
function centuryFromYear(year) {
return Math.ceil(year/100)
}
Вы можете использовать функцию потолка, доступную в модуле "математика", чтобы получить желаемое решение.
def centuryFromYear(year):
return math.ceil(year/100)
С целочисленным делением работает как на 2000, так и на 2017 год:
1 + (year - 1) // 100
def centuryFromYear(year):
return -(-year // 100)
это довольно старый, но это правильный вывод века. это отрицательное разделение пола
1700 // 100 = 17 1701 // 100 = 17 - (-1701 // 100) = 18
это делает деление пола на -1701 // 100, что составляет -18
работает на все годы и только 1 линия
Еще одна альтернатива, которая работает на 0-9999, которая больше соответствует вашим попыткам.
year = 2018
cent = int(str(year).zfill(4)[:2])+1
print(cent)
Возвращает:
21
a = int(input('Find the Century = '))
Разделите число на 100
century = a // 100
Проверьте, принадлежит ли год тому же веку
if(a%100 != 0):
century = century + 1
print(century)
Я решил эту проблему на PHP.
function centuryFromYear($year) {
if ($year % 100 == 0){
return $year/100;
}
else {
return ceil($year/100);
}
}
Примечание :-
- Функция ceil() округляет число до ближайшего целого.
- Чтобы округлить число ВНИЗ до ближайшего целого, посмотрите на функцию floor ().
- Чтобы округлить число с плавающей запятой, посмотрите на функцию round ().
def solution(year):
if (year % 100) == 0:
return (year) // 100
else:
return (year) // 100 + 1
На самом деле у меня есть один из самых элегантных кодов для этого, и я поделюсь с вами версией C.
#include<math.h>
#include<stdio.h>
int main() {
float x;
int y;
fscanf(stdin, "%f", &x);
x = x / 100;
y = ceil(x);
fprintf(stdout, "Century %d ", y);
return 0;
}
Сначала начните с вычитания 1 из year
в контексте
def centuryFromYear(year):
return (year - 1) // 100 + 1
Работает для реализации следующих примеров:
print(centuryFromYear(2000)) # --> 20
print(centuryFromYear(2001)) # --> 21
print(centuryFromYear(2017)) # --> 21
ЭТО Сработало для меня:
def whatCenturyIsX(x):
#turn our input into a string for modification
x = str(x)
#separate the characters of x into a list for further use
xlist = list(x)
#set a boolean to contatin negativity or positivity of the number
#if the "minus" sign is in x, set the boolean to true and remove the "minus" for easier handling of the variable
#(the minus doesn't tell us anything anymore because we already set the boolean)
negative = False
if "-" in xlist:
negative = True
xlist.remove("-")
for i in xlist:
x += i
#to define what century year x is in, we are going to take the approach of adding 1 to the first n characters, when N is the number of digits - 2. This is proved. So:
#also, we need the string to be at least 4 characters, so we add 0's if there are less
if len(xlist) >= 4:
pass
else:
if len(xlist) == 3:
xlist.insert(0, 0)
x = ""
for i in xlist:
x += str(i)
elif len(xlist) == 2:
xlist.insert(0, 0)
xlist.insert(1, 0)
x = ""
for i in xlist:
x += str(i)
elif len(xlist) == 1:
xlist.insert(0, 0)
xlist.insert(1, 0)
xlist.insert(2, 0)
x = ""
for i in xlist:
x += str(i)
n = len(xlist) - 2
#j is the number formed by the first n characters.
j = ""
for k in range(0, n):
#add the first n characters to j
j += str(xlist[k])
#finally form the century by adding 1 to j and calling it c.
c = int(j) + 1
#for the final return statement, we add a "-" and "B.C." if negative is true, and "A.C." if negative is false.
if negative:
xlist.insert(0, "-")
x = ""
for i in xlist:
x += str(i)
return(str(x) + " is en the century " + str(c) + " B.C.")
else:
return(str(x) + " is en the century " + str(c) + " A.C.")
year= int(input())
century = (year - 1) // 100 + 1
print(century)
Это правильный ответ:
def centuryFromYear(year):
if year % 100 == 0:
return year // 100
else:
return year // 100 + 1