Use Python to implement any integer in reverse

Source: Internet
Author: User

This is a long time to learn C did a practice exercise, the topic of the request is probably the user input three-digit reverse output, such as user input 123, and then the program should output the result is 321. If you encounter user input 100, then the program should output 1. And then I'm going to extend this program to accommodate three-digit or three-digit numbers or less.

So in this problem, my first idea is to find a way to take the user input of the number to open him, and then put in the list inside. Then take it out and stitch it up again. So I wrote the front code as follows:

#!/usr/bin/env python#-*-coding:utf-8-*-number = Int (raw_input ("Please input a number:")) numlist = []while 1:    if Nu Mber = = 0: Break    numlist.append (number%) Number    = NUMBER/10

This time we print the value of numlist to get a list of the equal length and number of digits.

And then the stitching process, here I think of Python's higher order function, reduce (), the first parameter of the function receives a function for processing the list, and the second parameter receives the list to be processed.

This means:

Reduce (f, [X1, x2, X3, x4]) = f (f (f (x1, x2), x3), x4)

So the processing function writes this:

def f (x, y):    return x * ten + y

最终的代码:

#!/usr/bin/env python#-*-coding:utf-8-*-number = Int (raw_input ("Please input a number:")) numlist = []result = 0while 1:    if number = = 0: Break    numlist.append (number%) Number    = Number/10def f (x, y):    return x * + YP Rint reduce (f, numlist)

PS: Reprint please indicate the source of the article.

Use Python to implement any integer in reverse

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.