I am making a passport and it was done.
But the file was 7kb big. That was too much for me.
So I started to make it shorter. I had a problem and this (look code below) is a simplified version of it but it didn't work. Can I do this for loop in the print command?
C = ["A","B","C","D","E","F","G"]
print(C[N] for N in range(0,7))
Questions=["What's your last name?","What's your first name?","On what day are you born? (dd/mm/yyyy + hh:mm)","What's your place of birth?","What's your nationality?","What language(s) do you speak?","What's your sex? (W/M)"]
Data=[input(Questions[N]+"\n") for N in range(0,7)]
Keys = ["Last name","First name","Birthday","Birthplace","Nationality","Language(s)","Sex"]
for N in range(0,7):
print(repr(N+1)+") "+Keys[N]+": "+Data[N])
(Above) Total First it asks you 7 question: (see 'Questions' list) it stores the answers in the list 'Data' and then it tells you what you typed. it shoud look like this (below)
What's your last name?
A
What's your first name?
B
On what day are you born? (dd/mm/yyyy + hh:mm)
C
What's your place of birth?
D
What's your nationality?
E
What language(s) do you speak?
G
What's your sex? (W/M)
H
1) Last name: A
2) First name: B
3) Birthday: C
4) Birthplace: D
5) Nationality: E
6) Language: G
7) Sex: H
Question: Can I do the code(below) in 1 line
for N in range(0,7):
print(repr(N+1)+") "+Keys[N]+": "+Data[N])
`
Related
I need to do a progam in blockly code for translate numbers from arabigos to roman up to 4000,but I don't know what I am doing wrong .
I only can use functions ,variables ,maths and logic (attached html code ).
who can help me with this please ,I'll be thankful ;))
https://blockly-demo.appspot.com/static/demos/code/index.html#zq536j
Let me see if I can think of something :)
Perhaps an example can help me: n = 1234 I can start by dividing by 1000 and take the integer part:
M = Math.floor(n/1000)
now M is 1 Now I can remove 1000*M from n and continue:
n = n-1000*M -> so now n is only 234.
After that:
D = Math.floor(n/500)
n = n-500*D
so D is 0 and n is still 234, because 234 does not contain any 500-eds.
And so no:
C = Math.floor(n/100)
n = n-100*C
which gives that C is 2 and n is 34.
And so on:
L = Math.floor(n/50)
n = n-50*L
which gives that L is 0 and n is 34.
Then:
X = Math.floor(n/10)
n = n-10*X
which gives that X is 3 and n is 4.
And finally
I = n
So now:
M=1
D=0
C=2
L=0
X=3
I=4
so you just have to make a clever enough function that prints it like:
"M CC XXX IV"
and you are done ;)
PS I hope this was not homework :D
I have created a code that (should) be able to convert a string into an ascii 'code'. However, it doesn't output what i want it to. Here is the code concerned:
if Code_Decode=='C':
print("What is your 'Shift number'?")
SNum=int(input("> "))
print("What is your message?")
msg=input("> ")
code=[ord(c) for c in msg]
new_code=[x+(SNum) for x in code]
print(','.join(str(x) for x in code))
else:
print("What is your 'Shift number'?")
SNum=int(input("> "))
print("Type in your ASCII values, separated by a comma")
a = [int(x) for x in input().split(",")]
ans=[x-(SNum) for x in a]
ans2=[chr(i) for i in ans]
print(' '.join(str(x) for x in ans2))
The user should input a 'Shift Number', then a string, And it should be converted into ascii, with the Shift Number added to each individual value.
However, when I run the code, the shift number is not added. Ignore the if and else lines.
Example: (This is what happens when I run the code)
Do you want to Create(C) a message, or Decode(D) a message? (C/D)> C
What is your 'Shift number'?
> 2
What is your message?
> Hello World
72,101,108,108,111,32,87,111,114,108,100
Again? Y/N > Y
Do you want to Create(C) a message, or Decode(D) a message? (C/D)> D
What is your 'Shift number'?
> 2
Type in your ASCII values, separated by a comma
72,101,108,108,111,32,87,111,114,108,100
F c j j m U m p j b
As you can see, the program outputs with some jumbled-up letters. How do I fix it?
Wrong: print(','.join(str(x) for x in code))
Right: print(','.join(str(x) for x in new_code))
I need to write logic to break down a 4 digit number into individual digits.
On a reply here at SO to a question regarding 3 digits, someone gave the math below:
int first = 321/100;
int second = (321/10)-first*10;
int third = (321/1)-first*100-second*10;
Can someone help me?
Thank you in advance!
Well, using the sample you found, we can quite easily infer a code for you.
The first line says int first = 321/100;, which returns 3 (integer division is the euclidian one). 3 is indeed the first integer in 321 so that's a good thing. However, we have a 4 digit number, let's try replacing 100 with 1000:
int first = 4321/1000;
This does return 4 !
Let's try adapting the rest of your code (plus I put your four digit number in the variable entry).
int entry = 4321;
int first = entry/1000;
int second = entry/100 - first*10;
int third = entry/10 - first*100 - second*10;
int fourth = entry - first*1000 - second*100 - third*10;
second will be entry/100 (43) minus first*10 (40), so we're okay.
third is then 432 - 400 - 30 which turns to 2. This also works till fourth.
For more-than-four digits, you may want to use a for-loop and maybe some modulos though.
This snip of code counts the number of digits input from the user
then breaks down the digits one by one:
PRINT "Enter value";
INPUT V#
X# = V#
DO
IF V# < 1 THEN
EXIT DO
END IF
D = D + 1
V# = INT(V#) / 10
LOOP
PRINT "Digits:"; D
FOR L = D - 1 TO 0 STEP -1
M = INT(X# / 10 ^ L)
PRINT M;
X# = X# - M * 10 ^ L
NEXT
END
This question already has answers here:
How to write the Fibonacci Sequence?
(67 answers)
Closed 9 years ago.
A tutorial I am going through had the following program
# This program calculates the Fibonacci sequence
a = 0
b = 1
count = 0
max_count = 20
while count < max_count:
count = count + 1
old_a = a # we need to keep track of a since we change it
print(old_a,end=" ") # Notice the magic end=" " in the print function arguments that
# keeps it from creating a new line
a = b
b = old_a + b
print() # gets a new (empty) line
The code is perfect. However, I am not able to figure out how the sequence is calculated.
How are the values changed to create the sequence?
It'll make more sense if you remove all of that extraneous code:
while count < max_count:
old_a = a
a = b
b = old_a + b
The old_a is probably confusing you. It's the long way of writing this:
a, b = b, a + b
Which swaps a with b and (at the same time), b with a + b. Note that it isn't the same as writing:
a = b
b = a + b
Because by the time you re-define b, a already holds its new value, which is equal to b.
I'd also run through the code manually by writing it out on paper.
This code works fine:
a, b = 0, 1
for _ in range(20):
print a
a, b = b, a+b
Setup
I have a column of durations stored as a strings in a dataframe. I want to convert them to an appropriate time object, probably POSIXlt. Most of the strings are easy to parse using this method:
> data <- data.frame(time.string = c(
+ "1 d 2 h 3 m 4 s",
+ "10 d 20 h 30 m 40 s",
+ "--"))
> data$time.span <- strptime(data$time.string, "%j d %H h %M m %S s")
> data$time.span
[1] "2012-01-01 02:03:04" "2012-01-10 20:30:40" NA
Missing durations are coded "--" and need to be converted to NA - this already happens but should be preserved.
The challenge is that the string drops zero-valued elements. Thus the desired value 2012-01-01 02:00:14 would be the string "1 d 2 h 14 s". However this string parses to NA with the simple parser:
> data2 <- data.frame(time.string = c(
+ "1 d 2 h 14 s",
+ "10 d 20 h 30 m 40 s",
+ "--"))
> data2$time.span <- strptime(data2$time.string, "%j d %H h %M m %S s")
> data2$time.span
[1] NA "2012-01-10 20:30:40" NA
Questions
What is the "R Way" to handle all the possible string formats? Perhaps test for and extract each element individually, then recombine?
Is POSIXlt the right target class? I need duration free from any specific start time, so the addition of false year and month data (2012-01-) is troubling.
Solution
#mplourde definitely had the right idea w/ dynamic creation of a formatting string based on testing various conditions in the date format. The addition of cut(Sys.Date(), breaks='years') as the baseline for the datediff was also good, but failed to account for a critical quirk in as.POSIXct() Note: I'm using R2.11 base, this may have been fixed in later versions.
The output of as.POSIXct() changes dramatically depending on whether or not a date component is included:
> x <- "1 d 1 h 14 m 1 s"
> y <- "1 h 14 m 1 s" # Same string, no date component
> format (x) # as specified below
[1] "%j d %H h %M m %S s"
> format (y)
[1] "% H h % M %S s"
> as.POSIXct(x,format=format) # Including the date baselines at year start
[1] "2012-01-01 01:14:01 EST"
> as.POSIXct(y,format=format) # Excluding the date baselines at today start
[1] "2012-06-26 01:14:01 EDT"
Thus the second argument for the difftime function should be:
The start of the first day of the current year if the input string has a day component
The start of the current day if the input string does not have a day component
This can be accomplished by changing the unit parameter on the cut function:
parse.time <- function (x) {
x <- as.character (x)
break.unit <- ifelse(grepl("d",x),"years","days") # chooses cut() unit
format <- paste(c(if (grepl("d", x)) "%j d",
if (grepl("h", x)) "%H h",
if (grepl("m", x)) "%M m",
if (grepl("s", x)) "%S s"), collapse=" ")
if (nchar(format) > 0) {
difftime(as.POSIXct(x, format=format),
cut(Sys.Date(), breaks=break.unit),
units="hours")
} else {NA}
}
difftime objects are time duration objects that can be added to either POSIXct or POSIXlt objects. Maybe you want to use this instead of POSIXlt?
Regarding the conversion from strings to time objects, you could do something like this:
data <- data.frame(time.string = c(
"1 d 1 h",
"30 m 10 s",
"1 d 2 h 3 m 4 s",
"2 h 3 m 4 s",
"10 d 20 h 30 m 40 s",
"--"))
f <- function(x) {
x <- as.character(x)
format <- paste(c(if (grepl('d', x)) '%j d',
if (grepl('h', x)) '%H h',
if (grepl('m', x)) '%M m',
if (grepl('s', x)) '%S s'), collapse=' ')
if (nchar(format) > 0) {
if (grepl('%j d', format)) {
# '%j 1' is day 0. We add a day so that x = '1 d' means 24hrs.
difftime(as.POSIXct(x, format=format) + as.difftime(1, units='days'),
cut(Sys.Date(), breaks='years'),
units='hours')
} else {
as.difftime(x, format, units='hours')
}
} else { NA }
}
data$time.span <- sapply(data$time.string, FUN=f)
I think you will have better luck with lubridate:
From Dates and Times Made Easy with lubridate:
5.3. Durations
...
The length of a duration is invariant to leap years, leap seconds, and daylight savings time
because durations are measured in seconds. Hence, durations have consistent lengths and
can be easily compared to other durations. Durations are the appropriate object to use when
comparing time based attributes, such as speeds, rates, and lifetimes.
lubridate uses the difftime class from base R for durations. Additional difftime methods
have been created to facilitate this.
lubridate uses the difftime class from base R for durations. Additional difftime methods
have been created to facilitate this.
...
Duration objects can be easily created with the helper functions dyears(), dweeks(), ddays(), dhours(), dminutes(), and dseconds(). The d in the title stands for duration and distinguishes these objects from period objects, which are discussed in Section 5.4. Each object creates a duration in seconds using the estimated relationships given above.
That said, I haven't (yet) found a function to parse a string into a duration.
You might also take a look at Ruby's Chronic to see how elegant time parsing can be. I haven't found a library like this for R.