Saturday, March 30, 2024

Python Tutorial - Angka Random - 012

Hal umum. Python melakukan generating untuk data data random, apakah itu untuk tujuan simulasi, testing dan gaming. 


Image - Ayam Turkey salai

Fungsi "random()" menghasilkan angka diantara 0 dan 1, seperti [0, 0.1 .... 1].

Generating a random float antara 0 dan 1
from random import random
print(random())
output: 0.332587482267

Angka integer antara 1 dan 100
from random import randint
print(randint(1, 100))
Output : 55

Storing Integer di variabel
from random import randint
number = randint(1, 100)
print(number)
Output: 26


Angka Random Float antara 1 dan 10
Kita bisa memakai Fungsi "uniform()"
from random import uniform
print(uniform(1, 10))
Output : 9.7811


Manipulasi Lists dengan Randomness
from random import shuffle
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(numbers)
print(numbers)
Output: [5, 1, 4, 10, 7, 9, 6, 3, 8, 2]


Menyeleksi Hal Random dari List
from random import sample
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
single_item = sample(numbers, 1)[0]
print(single_item)
Output: 8

multiple_items = sample(numbers, 4)
print(multiple_items)
[7, 5, 10, 4]



Lists mengandung Strings
from random import sample
names = ['Alissa', 'Alice', 'Marco', 'Melissa', 'Sandra', 'Steve']
single_name = sample(names, 1)[0]  # Picks one random name from the list.
print(single_name)
Output: Alissa

multiple_names = sample(names, 4)
print(multiple_names)
Output: ['Alice', 'Marco', 'Steve', 'Melissa']

# Posting sebelumnya:

JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ

No comments:

Post a Comment