logo
down
shadow

Ensure positive difference of two numbers


Ensure positive difference of two numbers

By : Lilly
Date : October 25 2020, 07:10 AM
this one helps. You can actually use the built-in absolute value function
code :
abs(x-y) # will return x - y if x >= y, y - x otherwise
for i in range(min(x, y), max(x, y) + 1):
    do_something()


Share : facebook icon twitter icon
Difference Between two numbers without positive or negative in Ruby

Difference Between two numbers without positive or negative in Ruby


By : Nyjel John Garcia
Date : March 29 2020, 07:55 AM
will be helpful for those in need You should simply return absolute value:
code :
def diff(a, b)
  (a - b).abs
end

diff(2, 5)
# => 3
Converting negative numbers to positive numbers but keeping positive numbers unchanged

Converting negative numbers to positive numbers but keeping positive numbers unchanged


By : Jean
Date : March 29 2020, 07:55 AM
I wish this help you I want to apply a bitmask to a number that will mimic the absolute value function for 2's complement encoded signed 32 bit integers. So far, I have , The last part
code :
negated = (~x + 1) & sign;
#include <stdio.h>

// assuming 32bit, 2 complement
int sign_inverse(int n)
{
    int mask = ~n & 0x80000000U;

    if(n == 0)
        mask = 0;

    return (~n + 1) | mask;
}

int main(void)
{
    int a = 5;
    int b = -4;
    int c = 54;
    int d = 0;

    printf("sign_inverse(%d) = %d\n", a, sign_inverse(a));
    printf("sign_inverse(%d) = %d\n", b, sign_inverse(b));
    printf("sign_inverse(%d) = %d\n", c, sign_inverse(c));
    printf("sign_inverse(%d) = %d\n", d, sign_inverse(d));

    return 0;
}
$ ./b 
sign_inverse(5) = -5
sign_inverse(-4) = 4
sign_inverse(54) = -54
sign_inverse(0) = 0
Generate random numbers where the difference is always positive

Generate random numbers where the difference is always positive


By : Kim Thylstrup
Date : March 29 2020, 07:55 AM
hope this fix your issue Even when @forpas solution is fine, it still runs in O(n log n) because of the final sorting. My solution just generates the increasing intervals where to generate random numbers (for uniformity distribution), and then map each interval to a random number in that range, hence avoiding the need to sort the final list. Complexity is O(n)
I chose to use Stream to avoid mutation or explicit recursion, but is not mandatory.
code :
fun main(args: Array<String>) {
    val count = 20L
    val digits = 5

    val min =  pow(10.0, digits.toDouble() - 1).toLong()
    val max = min*10 - 1
    val gap = (max - min)/count + 1

    val numbers =
        Stream.iterate(Pair(min, min + gap)) { (_, prev) -> Pair(prev, prev + gap) }
            .map { (start, end) -> Random.nextLong(start, end) }
            .limit(count)
            .collect(Collectors.toList()) 

    numbers.forEach(::println)
}
11298
16284
20841
26084
31960
35538
37208
45325
46970
52918
57514
59769
67689
70135
75338
78075
84561
86652
91938
99931
generate N random numbers with X digits such that the difference(the numbers subtracted from top to bottom) is positive

generate N random numbers with X digits such that the difference(the numbers subtracted from top to bottom) is positive


By : user2280460
Date : March 29 2020, 07:55 AM
should help you out You could just generate a number with a random method based on Fibonacci sequence.
In Fibonacci sequence you generate a number based on the previous ones. If you want a random positive number, just generate a random number and add it to the last one, this will always fulfill your requirements.
code :
import random

number_list=[]
r_number=0
while(r_number < 100):
    b_number=random.randint(1,10)
    r_number += b_number
    if r_number<100:
        number_list.append(r_number)
print(number_list)
[4, 14, 22, 24, 26, 28, 29, 34, 35, 36, 46, 48, 51, 56, 64, 72, 79, 89, 98]
[7, 13, 19, 27, 34, 35, 39, 43, 45, 48, 52, 58, 68, 74, 83, 86, 88, 93, 99]
import random

number_list = []
r_number = random.randint(1, 10)
LIMIT=1000

while r_number < LIMIT:
    sum_ = sum(number_list)
    r_number = random.randint(sum_, sum_ + 10)
    number_list.append(r_number)

if number_list[-1] > LIMIT:
    del number_list[-1]

print(number_list)
print("Last element minus the rest equals",number_list[-1] - (sum(number_list) - number_list[-1]))
[3, 4, 7, 21, 37, 72]
0

[9, 19, 38, 74]
8

[4, 4, 11, 20, 47, 96]
10

[4, 5, 10, 26, 55]
10
Last element minus the rest equals 7

real    0m0,023s
user    0m0,020s
sys     0m0,000s
./test.py |wc -c
17109
Write a C program that read 5 numbers and counts the number of positive numbers and print the average of all positive va

Write a C program that read 5 numbers and counts the number of positive numbers and print the average of all positive va


By : Papvlieg
Date : October 01 2020, 06:00 AM
like below fixes the issue While there is nothing wrong with repetitive lines of code, it's certainly not literature. If you are faced with doing the same thing 5 times and the only thing changing is an index or two in the output -- you should be thinking loop. Here you can expand the loop you have to include the prompting for input as well as handling the summing of positive numbers, and it can all be done without having to store the input values in an array.
All you need to maintain within the loop is the sum of the positive values. The after you exit the loop you can compute the average based on the number of positive values input.
code :
#include <stdio.h>

#define NNUM 5      /* if you need a constant, #define one (or more) */

int main (void) {

    int n = 0,      /* no. of positive value counter */
        sum = 0,    /* sum of all positive values */
        val;        /* each input value */
    double avg;     /* floating-point number to hold average */

    for (int i = 0; i < NNUM; i++) {    /* loop NNUM times */
        printf ("enter no. %d: ", i+1); /* prompt for input */
        if (scanf ("%d", &val) != 1) {  /* validate EVERY user input */
            fputs ("error: invalid integer input.\n", stderr);
            return 1;
        }
        if (val > 0) {      /* check if val is positive */
            sum += val;     /* add val to sum */
            n++;            /* increment pos value count */
        }
    }
    avg = (double)sum / n;  /* compute average (note cast) */

    printf ("\nThe number of positive numbers       : %d\n"
            "The average of all positive value is : %.2f\n", n, avg);
}
$ ./bin/avgposnum
enter no. 1: 14
enter no. 2: 63
enter no. 3: 78
enter no. 4: 45
enter no. 5: 21

The number of positive numbers       : 5
The average of all positive value is : 44.20
$ ./bin/avgposnum
enter no. 1: -10
enter no. 2: 10
enter no. 3: 0
enter no. 4: 20
enter no. 5: -20

The number of positive numbers       : 2
The average of all positive value is : 15.00
Related Posts Related Posts :
  • Percent signs in windows path
  • How to add a random number to a subsection of a numpy array?
  • How to generate all the values of an iterable besides the last few?
  • Searching by both class and range in XPath
  • Python code execution in Perl interpreter
  • Best Way to Include Variable in Python3
  • Serialize the @property methods in a Python class
  • What is the most platform- and Python-version-independent way to make a fast loop for use in Python?
  • Good way to edit the previous defined class in ipython
  • Bounced email on Google App Engine
  • Search jpeg files using python
  • Dynamically create class attributes
  • python unichr problem
  • Python beginner, strange output problem
  • Python: Finding a value in 1 list and finding that corresponding index in another list
  • can't install mysqlclient on mac os x mojave
  • Error indicates flattened dimensions when loading pre-trained network
  • how to replace underlines with words?
  • Adding through iteration
  • Use OpenCV on deployed Flask app (Heroku)
  • How to skip interstitial in a django view if a user hits the back button?
  • Any Naive Bayesian Classifier in python?
  • Python 2.5.2: remove what found between two lines that contain two concrete strings
  • Python 2.5.2 script that add "The function starts here" to all the functions of the files of a directory
  • HttpResponseRedirect question
  • Python socket error on UDP data receive. (10054)
  • Encoding issues with cloud ml
  • numpy.where - Weird behaviour: new elements spawning from nowhere?
  • I can't move my player in pygame, can you figure why?
  • Weird error I receive from Tkinter in Python
  • Using a Zapier Custom Request Webhook with JSON Web Tokens
  • Keras: Use categorical_crossentropy without one-hot encoded array of targets
  • Does python's httplib.HTTPConnection block?
  • Do alternate python implementation version numbers imply that they provide the same syntax?
  • Searching for specific HTML string using Python
  • python sax error "junk after document element"
  • MySql: How to know if an entry is compressed or not
  • Return a list of imported Python modules used in a script?
  • Returning a list in this recursive coi function in python
  • Python2.6 Decimal to Octal
  • Appengine Apps Vs Google bot web crawler
  • Changing models in django results in broken database?
  • Global variable functions
  • Using lambda inside a function
  • How to open a file, replace some strings, and save updates to the same file?
  • How to move the beginning of an input to the and?
  • If else fill variable if empty list
  • Pandas: Find and print all floats in column
  • sqlite3.OperationalError: database is locked - non-threaded application
  • How to implement mib module in net-snmp with python?
  • Does Python/Scipy have a firls( ) replacement (i.e. a weighted, least squares, FIR filter design)?
  • sorl-thumbnail and file renaming
  • Python -- what is NOT in 2.7 that IS in 3.1? So many things have been back-ported, what is NOT?
  • How to make a Django model fields calculated at runtime?
  • Django - Threading in views without hanging the server
  • Python: Why is my POST requests not working?
  • Tried to add a value to a while condition, but it doesn't go back
  • How do I exit a while-true loop after 5 tries?
  • win python3 Multithreading
  • Compare 2 dictionaries in python
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk