How to make my if statement simpler and more elegant - if-statement

I am a new learner to python programming. I'm just making pizza order program but I feel like I could make it better - what can I improve?
if size == "S" and add_pepperoni == "Y" and extra_cheese == "Y":
total += 18
elif size == "S" and add_pepperoni == "N" and extra_cheese == "Y":
total += 16
elif size == "S" and add_pepperoni == "N" and extra_cheese == "N":
total += 15
elif size == "S" and add_pepperoni == "Y" and extra_cheese =="N":
total += 17

you are essentially asking how you can simplify your logic for calculating the price ? If that is the case, i feel some more information would be needed to optimize this. But in general it could be simpler if you can break it down into separate decisions and add an amount to the total based on the outcome of each decision. For example:
if size == "S":
total += 15
end
if add_pepperoni == "Y":
total += 2
end
if extra_cheese == "Y":
total += 1
end
essentially you only add to the total if something is selected.
It's just another of doing it, there can be even better ways to write any logic as such. To generalise, break it down and solve it 1 by 1.

Related

Evaluating boolean with two char variables in c++

Apologies, a bit of a beginner here:
I'm working on a practice program to determine cost of a long distance call based on hour of the day and day of the week...and I've gotten to my do-while loop and am attempting to use nested branches to split up weekdays with the weekend.
However, when I compile and run, both the if and else if nested statements are skipped no matter if I put in the Chars corresponding to the booleans I'm attempting to evaluate. I'm struggling to understand what I'm missing here. The instructions clearly state that the days of the week should be stored in two char variables: Mo Tu We Th Fr Sa Su.
do
{
//have user input day of week of call
printf("\nOn what day was the call made? (Mo, Tu, We, Th, Fr, Sa, or Su) ");
scanf("%c%c", &day1, &day2);
//branch for weekday vs weekend vs invalid input
if (((day1 == 'M') && (day2 == 'o')) || ((day1 == 'T') && (day2 == 'u')) || ((day1 == 'W') && (day2 == 'e')) || ((day1 == 'T') && (day2 == 'h')) || ((day1 == 'F') && (day2 == 'r')))
{
//determine if phone call was made at hi or low rate times
printf("At what time was your call made? (HH MM - with 08 00 representing 8:00 AM and 18 30 representing 6:30 PM) ");
scanf("%f %f", &call_time_hour, &call_time_minute);
call_time_hour = call_time_hour + (call_time_minute / 60);
printf("%f", call_time_hour);
}
else if (((day1 == 'S') && (day2 == 'a')) || ((day1 == 'S') && (day2 == 'u')))
{
printf("What was the duration of your call? ");
scanf("%d", &call_duration);
//calculate total cost of call
cost_of_call = call_duration * 0.15;
printf("%s %.2lf", "The cost of this call was $", cost_of_call);
}
calls_made--;
printf("%d", calls_made);
}while (calls_made > 0);
So, for example, when I compile and run the program and enter "Sa" as the day that the call was made, it then moved directly to the 'calls_made--' step.
The problem is because previous scanf. Debug and look what characters are really scanned. I'm sure that day1 would be '\n'.
In this case clear the input stream before scanning the day of week:
while (getchar() != '\n');

Print, loop, Indentation, Python

I need a pit of help. I am currently learning python, and I have python 2.7.8
I am looking to build a simple program that will help to count the vowels in my word.
Here is the code:
count = 0
total = 0
for v in "bonbon":
count += 1
if v == 'e' or v == 'o' or v == 'u' or v == 'a':
print('the number of vowel in your word is ' +str(total))
Why does it print twice?
1- the number of my vowel is 0
and then the number of my is 2
Could someone help me please?
Thanks guys
It's printing twice because you have the print inside of the for loop. You should instead increment total inside the for loop and then print it afterwards. If you do:
count = 0
total = 0
for v in "bonbon":
count += 1
if v == 'e' or v == 'o' or v == 'u' or v == 'a':
total += 1
print('the number of vowel in your word is ' + str(total))
It should work.

How could you write the "if - then" logic for the game Yacht?

https://en.wikipedia.org/wiki/Yacht_(dice_game)
I created 5 dice in my c++ program and they each roll random numbers from 1-6.
So if you get all 1's its really simple. It's just:
if (dice1 == 1 && dice2 == 1 && dice3 == 1 && dice4 == 1 && dice5 == 1)
{
int total = 50;
}
Also, summing all the dice is easy too. But how could you write the if-statement for "if two to four dice are the same then sum up those dice"? Is there a simple way you could do that?
Try to use tables and make variable which count 1 in table. Then u can compare it.

Choosing "a" or "an" before any digit beginning with 8

int roll = RANDOM(1, 100);
printf("You rolled %s %d.", (roll == 8 ? "an" : ((roll > 79 && roll < 90) ? "an" : "a")));
Potential output:
You rolled a 12.
You rolled an 8.
You rolled an 84.
You rolled a 97.
The inline logic for determining an "a" or "an" for numbers starting with an 8 between 1 and 100 works fine.
1: Is there a more elegant way to do this?
2: What's the best way to handle all integer value types that begin with 8?
Well (roll == 8 || roll > 79 && roll < 90 ? "an" : "a") is more concise, for starters.
You could have a solution based on a 2-character buffer buf and snprintf(buf, 2, "%d", roll), but that seems overkill. And as pointed out in the comments, just looking at the first digit is not enough for total grammatical correctness, so it is better to stick with the disjunction of special cases.
If you want to handle all numbers starting with 8 something along the lines of this should do
bool startsWithEight(int number){
while(number > 10){
number /= 10;
}
return number == 8;
}
Might not be the most efficient way.

Determining if a number is either a multiple of ten or within a particular set of ranges

I have a few loops that I need in my program. I can write out the pseudo code, but I'm not entirely sure how to write them logically.
I need -
if (num is a multiple of 10) { do this }
if (num is within 11-20, 31-40, 51-60, 71-80, 91-100) { do this }
else { do this } //this part is for 1-10, 21-30, 41-50, 61-70, 81-90
This is for a snakes and ladders board game, if it makes any more sense for my question.
I imagine the first if statement I'll need to use modulus. Would if (num == 100%10) be correct?
The second one I have no idea. I can write it out like if (num > 10 && num is < 21 || etc.), but there has to be something smarter than that.
For the first one, to check if a number is a multiple of use:
if (num % 10 == 0) // It's divisible by 10
For the second one:
if(((num - 1) / 10) % 2 == 1 && num <= 100)
But that's rather dense, and you might be better off just listing the options explicitly.
Now that you've given a better idea of what you are doing, I'd write the second one as:
int getRow(int num) {
return (num - 1) / 10;
}
if (getRow(num) % 2 == 0) {
}
It's the same logic, but by using the function we get a clearer idea of what it means.
if (num is a multiple of 10) { do this }
if (num % 10 == 0) {
// Do something
}
if (num is within 11-20, 31-40, 51-60, 71-80, 91-100) { do this }
The trick here is to look for some sort of commonality among the ranges. Of course, you can always use the "brute force" method:
if ((num > 10 && num <= 20) ||
(num > 30 && num <= 40) ||
(num > 50 && num <= 60) ||
(num > 70 && num <= 80) ||
(num > 90 && num <= 100)) {
// Do something
}
But you might notice that, if you subtract 1 from num, you'll have the ranges:
10-19, 30-39, 50-59, 70-79, 90-99
In other words, all two-digit numbers whose first digit is odd. Next, you need to come up with a formula that expresses this. You can get the first digit by dividing by 10, and you can test that it's odd by checking for a remainder of 1 when you divide by 2. Putting that all together:
if ((num > 0) && (num <= 100) && (((num - 1) / 10) % 2 == 1)) {
// Do something
}
Given the trade-off between longer but maintainable code and shorter "clever" code, I'd pick longer and clearer every time. At the very least, if you try to be clever, please, please include a comment that explains exactly what you're trying to accomplish.
It helps to assume the next developer to work on the code is armed and knows where you live. :-)
If you are using GCC or any compiler that supports case ranges you can do this, but your code will not be portable.
switch(num)
{
case 11 ... 20:
case 31 ... 40:
case 51 ... 60:
case 71 ... 80:
case 91 ... 100:
// Do something
break;
default:
// Do something else
break;
}
This is for future visitors more so than a beginner. For a more general, algorithm-like solution, you can take a list of starting and ending values and check if a passed value is within one of them:
template<typename It, typename Elem>
bool in_any_interval(It first, It last, const Elem &val) {
return std::any_of(first, last, [&val](const auto &p) {
return p.first <= val && val <= p.second;
});
}
For simplicity, I used a polymorphic lambda (C++14) instead of an explicit pair argument. This should also probably stick to using < and == to be consistent with the standard algorithms, but it works like this as long as Elem has <= defined for it. Anyway, it can be used like this:
std::pair<int, int> intervals[]{
{11, 20}, {31, 40}, {51, 60}, {71, 80}, {91, 100}
};
const int num = 15;
std::cout << in_any_interval(std::begin(intervals), std::end(intervals), num);
There's a live example here.
The first one is easy. You just need to apply the modulo operator to your num value:
if ( ( num % 10 ) == 0)
Since C++ is evaluating every number that is not 0 as true, you could also write:
if ( ! ( num % 10 ) ) // Does not have a residue when divided by 10
For the second one, I think this is cleaner to understand:
The pattern repeats every 20, so you can calculate modulo 20.
All elements you want will be in a row except the ones that are dividable by 20.
To get those too, just use num-1 or better num+19 to avoid dealing with negative numbers.
if ( ( ( num + 19 ) % 20 ) > 9 )
This is assuming the pattern repeats forever, so for 111-120 it would apply again, and so on. Otherwise you need to limit the numbers to 100:
if ( ( ( ( num + 19 ) % 20 ) > 9 ) && ( num <= 100 ) )
With a couple of good comments in the code, it can be written quite concisely and readably.
// Check if it's a multiple of 10
if (num % 10 == 0) { ... }
// Check for whether tens digit is zero or even (1-10, 21-30, ...)
if ((num / 10) % 2 == 0) { ... }
else { ... }
You basically explained the answer yourself, but here's the code just in case.
if((x % 10) == 0) {
// Do this
}
if((x > 10 && x < 21) || (x > 30 && x < 41) || (x > 50 && x < 61) || (x > 70 && x < 81) || (x > 90 && x < 101)) {
// Do this
}
You might be overthinking this.
if (x % 10)
{
.. code for 1..9 ..
} else
{
.. code for 0, 10, 20 etc.
}
The first line if (x % 10) works because (a) a value that is a multiple of 10 calculates as '0', other numbers result in their remainer, (b) a value of 0 in an if is considered false, any other value is true.
Edit:
To toggle back-and-forth in twenties, use the same trick. This time, the pivotal number is 10:
if (((x-1)/10) & 1)
{
.. code for 10, 30, ..
} else
{
.. code for 20, 40, etc.
}
x/10 returns any number from 0 to 9 as 0, 10 to 19 as 1 and so on. Testing on even or odd -- the & 1 -- tells you if it's even or odd. Since your ranges are actually "11 to 20", subtract 1 before testing.
A plea for readability
While you already have some good answers, I would like to recommend a programming technique that will make your code more readable for some future reader - that can be you in six months, a colleague asked to perform a code review, your successor, ...
This is to wrap any "clever" statements into a function that shows exactly (with its name) what it is doing. While there is a miniscule impact on performance (from "function calling overhead") this is truly negligible in a game situation like this.
Along the way you can sanitize your inputs - for example, test for "illegal" values. Thus you might end up with code like this - see how much more readable it is? The "helper functions" can be hidden away somewhere (the don't need to be in the main module: it is clear from their name what they do):
#include <stdio.h>
enum {NO, YES, WINNER};
enum {OUT_OF_RANGE=-1, ODD, EVEN};
int notInRange(int square) {
return(square < 1 || square > 100)?YES:NO;
}
int isEndOfRow(int square) {
if (notInRange(square)) return OUT_OF_RANGE;
if (square == 100) return WINNER; // I am making this up...
return (square % 10 == 0)? YES:NO;
}
int rowType(unsigned int square) {
// return 1 if square is in odd row (going to the right)
// and 0 if square is in even row (going to the left)
if (notInRange(square)) return OUT_OF_RANGE; // trap this error
int rowNum = (square - 1) / 10;
return (rowNum % 2 == 0) ? ODD:EVEN; // return 0 (ODD) for 1-10, 21-30 etc.
// and 1 (EVEN) for 11-20, 31-40, ...
}
int main(void) {
int a = 12;
int rt;
rt = rowType(a); // this replaces your obscure if statement
// and here is how you handle the possible return values:
switch(rt) {
case ODD:
printf("It is an odd row\n");
break;
case EVEN:
printf("It is an even row\n");
break;
case OUT_OF_RANGE:
printf("It is out of range\n");
break;
default:
printf("Unexpected return value from rowType!\n");
}
if(isEndOfRow(10)==YES) printf("10 is at the end of a row\n");
if(isEndOfRow(100)==WINNER) printf("We have a winner!\n");
}
For the first one:
if (x % 10 == 0)
will apply to:
10, 20, 30, .. 100 .. 1000 ...
For the second one:
if (((x-1) / 10) % 2 == 1)
will apply for:
11-20, 31-40, 51-60, ..
We basically first do x-1 to get:
10-19, 30-39, 50-59, ..
Then we divide them by 10 to get:
1, 3, 5, ..
So we check if this result is odd.
As others have pointed out, making the conditions more concise won't speed up the compilation or the execution, and it doesn't necessarily help with readability either.
It can help in making your program more flexible, in case you decide later that you want a toddler's version of the game on a 6 x 6 board, or an advanced version (that you can play all night long) on a 40 x 50 board.
So I would code it as follows:
// What is the size of the game board?
#define ROWS 10
#define COLUMNS 10
// The numbers of the squares go from 1 (bottom-left) to (ROWS * COLUMNS)
// (top-left if ROWS is even, or top-right if ROWS is odd)
#define firstSquare 1
#define lastSquare (ROWS * COLUMNS)
// We haven't started until we roll the die and move onto the first square,
// so there is an imaginary 'square zero'
#define notStarted(num) (num == 0)
// and we only win when we land exactly on the last square
#define finished(num) (num == lastSquare)
#define overShot(num) (num > lastSquare)
// We will number our rows from 1 to ROWS, and our columns from 1 to COLUMNS
// (apologies to C fanatics who believe the world should be zero-based, which would
// have simplified these expressions)
#define getRow(num) (((num - 1) / COLUMNS) + 1)
#define getCol(num) (((num - 1) % COLUMNS) + 1)
// What direction are we moving in?
// On rows 1, 3, 5, etc. we go from left to right
#define isLeftToRightRow(num) ((getRow(num) % 2) == 1)
// On rows 2, 4, 6, etc. we go from right to left
#define isRightToLeftRow(num) ((getRow(num) % 2) == 0)
// Are we on the last square in the row?
#define isLastInRow(num) (getCol(num) == COLUMNS)
// And finally we can get onto the code
if (notStarted(mySquare))
{
// Some code for when we haven't got our piece on the board yet
}
else
{
if (isLastInRow(mySquare))
{
// Some code for when we're on the last square in a row
}
if (isRightToLeftRow(mySquare))
{
// Some code for when we're travelling from right to left
}
else
{
// Some code for when we're travelling from left to right
}
}
Yes, it's verbose, but it makes it clear exactly what's happening on the game board.
If I was developing this game to display on a phone or tablet, I'd make ROWS and COLUMNS variables instead of constants, so they can be set dynamically (at the start of a game) to match the screen size and orientation.
I'd also allow the screen orientation to be changed at any time, mid-game - all you need to do is switch the values of ROWS and COLUMNS, while leaving everything else (the current square number that each player is on, and the start/end squares of all the snakes and ladders) unchanged.
Then you 'just' have to draw the board nicely, and write code for your animations (I assume that was the purpose of your if statements) ...
You can try the following:
// Multiple of 10
if ((num % 10) == 0)
{
// Do something
}
else if (((num / 10) % 2) != 0)
{
// 11-20, 31-40, 51-60, 71-80, 91-100
}
else
{
// Other case
}
I know that this question has so many answers, but I will thrown mine here anyway...
Taken from Steve McConnell's Code Complete, 2nd Edition:
"Stair-Step Access Tables:
Yet another kind of table access is the stair-step method. This access method isn’t as direct as an index structure, but it doesn’t waste as much data space. The general idea of stair-step structures, illustrated in Figure 18-5, is that entries in a table are valid for ranges of data rather than for distinct data points.
Figure 18-5 The stair-step approach categorizes each entry by determining the level at which it hits a “staircase.” The “step” it hits determines its category.
For example, if you’re writing a grading program, the “B” entry range might be from 75 percent to 90 percent. Here’s a range of grades you might have to program someday:
To use the stair-step method, you put the upper end of each range into a table and then write a loop to check a score against the upper end of each range. When you find the point at which the score first exceeds the top of a range, you know what the grade is. With the stair-step technique, you have to be careful to handle the endpoints of the ranges properly. Here’s the code in Visual Basic that assigns grades to a group of students based on this example:
Although this is a simple example, you can easily generalize it to handle multiple students, multiple grading schemes (for example, different grades for different point levels on different assignments), and changes in the grading scheme."
Code Complete, 2nd Edition, pages 426 - 428 (Chapter 18).