mercredi 26 octobre 2016

Guessing random number game python

My program is supposed to ask the user to guess a number between 0 and 100 however I can't seem to get the output right. At the moment if the the User number is greater than the random number, it prints out an infinite amount of "Your number is too high." Also if the first UserGuess is low, then all the following numbers will have the same prompt: ("Your number is too low") despite them being actually bigger than the random number. I have no idea what I am doing wrong. Any help would be greatly appreciated. Thank you!

from random import randint

def main():

guessesTaken = 0

randomNumber = randint(0,100)
#print(randomNumber)
giveUp = -1
UserGuess = int(input("Take a guess" + "(The random number is: " + str(randomNumber) + "): "))

while UserGuess != randomNumber:

    guessesTaken += 1

    if UserGuess < randomNumber:
        print("Your guess is too low.")

    elif UserGuess > randomNumber:
        print("Your guess is too high.")

    elif UserGuess == randomNumber or UserGuess == giveUp:
        break

if UserGuess  == randomNumber:
    guessesTaken = str(guessesTaken)
    print("Yes, that is right!")
    print("It took you " + guessesTaken +  " guesses")
if UserGuess == giveUp:
    guessesTaken = str(guessesTaken)
    randomNumber = str(randomNumber)
    print("Better luck next time.")
    print("You tried"+ guessesTaken +  " guesses")


return
print (main())

if __name__ == "__main__":
     main()    




Random ints with more specific range python

I'm trying to design a basic Battleships style game, where the ship takes up 2 spaces on a 5x5 board.

I am randomly generating one of the co-ordinates and trying to randomly generate 2nd co-ordinate to be within 1 space of the last number. Here is my code

coordinate1x = random.randint(0,4)
coordinate1y = random.randint(0,4)
coordinate1 = [coordinate1x, coordinate1y]

coordinate2x = random.randint(coordinate1x, coordinate1x + 1)
coordinate2y = random.randint(coordinate1y, coordinate1y + 1)
coordinate2 = [coordinate2x, coordinate2y]

battleship_location = [coordinate1, coordinate2]

I am struggling to find the logic to get the correct numbers.

Any help is greatly apprecaited




How can i set a string to zero after an expired time?

I am creating a login/registration-script where a user hast to activate his account with a token. Now i have a function that calls a random string.

class.functions.php

public static function generateRandomString($length = 200) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

this will output something like this: jTq7tH4dKy66dmnhRev5EjbZDZygN1...

now my question is, how can i set this string empty after 24h, so that the user has to activate his account again.

my thought was about an update query in my database like this:

$statusN = "N" and $statusY = "Y"

the table field from the database:

`user_status` ENUM('Y','N') NOT NULL DEFAULT 'N',

the sql statment:

$sql = "UPDATE formular SET user_status='" . $statusY . "' WHERE user_status='" . $statusN . "'";

but i dont know how to handel it with the time

Here is the inserting of the userdata and the activation_token

register.php

$activationToken = functions::generateRandomString();
    $stmt = $conn->prepare("INSERT INTO formular (firstname, second_firstname, lastname, zipcode, city, street, additionaladdress, country_id_from_apps_countries, username, email, hash, dday, dmonth, dyear, religion, housenumber, activation_token) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssisssssssssssss", $firstname, $secondFirstname, $lastname, $zipcode, $city, $street, $additionaladdress, $country, $username, $email, $hash, $DOB, $MOB, $YOB, $religion, $houseNumber, $activationToken);
    $stmt->execute();
    if ($stmt->affected_rows) {

    }




Show 4Tab of 12Tab random and Hide another tab

I need a code for show tabs exmapls: i use 12tabs and now need just show 4tab random show on my page and hide another tab for user example tab1 tab2 ... tab12

i need show random this tabs tab1 tab8 tab11 tab4 and hide another tab




Java UUID generation

I am trying to generate UUID's and have found some useful info. I am able to generate them now, but now what I want to do is create like my own function, where by if I type in lets say something like the word create, then it will generate the random UUID. I am using the standard code I found online and appreciate any advise. Thank you. This is what I have so far :

static UUID uuid;
    public static void main(String[] args) {
        int i = 0;
        while(i < 10) {
            uuid = UUID.randomUUID();
            System.out.println("Random UUID value: "+uuid);
            System.out.println("Random UUID value: "+uuid.version());
            i++;
        }

        uuid = UUID.fromString("60288f72-9778-11e6-ae22-56b6b6499611");
        System.out.println("String UUID value: "+uuid);
        System.out.println("String UUID version: "+uuid.version());

// I want it to be if I type in the word create, then this method will be called and generate the random UUID....




Random selection of variables from a dictionary and print on a GUI in python

I am stuck in a code of making a "Food Quiz" GUI on python 3 using the tkinter and init method. As I am a newbie I am having difficulties in this program. The aim is to make a GUI program which will take various keys from a dictionary and set them randomly on the GUI. Please refer to the attached image. The Big Mac and Whopper are the keys (name) and they have to appear randomly on the buttons and then in the body of the GUI as shown. Currently, the data is in the .txt file and we have to import it as well. The other key attribute to be selected is from a list of variables namely cholesterol, fat, protein and etc. as shown in the image. Please help me with the random selection of these after importing them from the .txt file and then printing it on the GUI.

from tkinter import Tk, LEFT, RIGHT, BOTH, RAISED, END
from tkinter import * 
from tkinter.ttk import Frame, Button, Style
import tkinter.messagebox
from tkinter import Label
import random
import json
class foodquiz(Frame):  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
        self.parent = parent
        self.label = Label(parent, text="Which has one more....\n Cholestrol")
        self.label.place(x = 50, y = 70)
        self.initUI()
    def initUI(self):
        self.parent.title("Food Quiz")
        self.style = Style()
        self.style.theme_use("default")
        frame = Frame(self, relief=RAISED, borderwidth=1)
        frame.pack(fill=BOTH, expand=True)
        self.pack(fill=BOTH, expand=True)
        def leftoption():
            tkinter.messagebox.showinfo("Correct Option!", "You got it right.")
        closeButton = Button(self, text="Whopper", command = leftoption)
        closeButton.place(x = 165, y = 154)
        def rightoption():
            tkinter.messagebox.showinfo("Incorrect!", "You got it wrong.")
        okButton = Button(self, text="Big Mac", command = rightoption)
        okButton.place(x = 0, y = 154)
        def middleoption():
            tkinter.messagebox.showinfo("Incorrect!", "You got it wrong.")
        midButton = Button(self, text = "Roughly Equal", command = rightoption)
        midButton.place(x = 71.5, y = 154)
def main():
    root = Tk()
    root.geometry("230x180+300+300")
    app = foodquiz(root)
    root.mainloop()  
if __name__ == '__main__':
    main()

The random varibles must not change until the user enters the answer. Dictionary in .txt file:

[
 {
  "carbohydrates": 45,
  "calories": 540,
  "sodium": 1040,
  "fat": 29,
  "protein": 25,
  "name": "Big Mac",
  "cholesterol": 75
 },
 {
  "carbohydrates": 53,
  "calories": 760,
  "sodium": 1410,
  "fat": 47,
  "protein": 33,
  "name": "Whopper",
  "cholesterol": 100
 },
 {
 "carbohydrates": 85,
 "fat": 5,
 "sodium": 45,
 "calories": 50,
 "protein": 50,
 "name": "Icecream'",
 "cholesterol": 96
 } 
]

Ideal output of the GUI and random variables:

enter image description here




mardi 25 octobre 2016

Can Random.nextDouble() ever return the inclusive value?

I was playing around with the Random class's nextDouble() method as shown below. I expected nextDouble() to return a pseudorandom double value on the interval [-50.0, 50.0), however, after running the loop 1 billion times the output came out to maximum: 49.99999995014588 minimum: -49.99999991024878. I ran the loop without my manipulations of the output interval, and I got maximum: 0.9999999998979311 minimum: 0.0. I find this strange, because all I have done to the 0.0 that was returned is multiply it by 100.0 and subtract 50.0 from it. Why does this code snippet below never return exactly 50.0?

import java.util.Random;

public class randomTest{

public static void main(String[] args) {

    double max = 0;
    double min = 0;
    Random math = new Random();
    for(int a = 0; a < 1000000000; a++) {
        double rand = math.nextDouble() * 100.0 - (100.0 / 2.0);
        max = Math.max(max, rand);
        min = Math.min(min, rand);
    }
    System.out.println("maximum: " + max + " minimum: " + min);
}
}