I've never done neural network development before, but it just so happens that I HAVE to do it before January 23, inclusive, or I will miss a huge number of opportunities. I get a huge bunch of mistakes that I don't know what to do with. Be so kind-correct my code and explain to me what I'm doing wrong) thank You all
UPD code:
import numpy as np
def Sigmoid(x):
return 1/(1+np.exp(-x))
trn_inp=np.array([[1],[2],[3]]) #Массив 3 на 1. 3 строки и 1 столбец
trn_out=np.array([[1,2,3]]).T #Ожидаемые выходные данные
print("trn_inp now: \n"+str(trn_inp))
print("trn_inp matrix: "+str(np.shape(trn_inp)))
print("trn_out now: \n"+str(trn_out))
print("trn-out matrix: \n"+str(np.shape(trn_out)))
np.random.seed(1)
syn_wei=2*np.random.random((1,1))-1 #Создается массив размером x на y, который заполняется рандомными значениями от -1 до 1
#print(syn_wei)
o=1
for i in range(100):
print("Try # "+str(o))
out=Sigmoid(np.dot(trn_inp, syn_wei))
err=trn_out-out
adj=np.dot(trn_inp.T,err*(out*(1-out)))
syn_wei+=adj
o+=1
print("=="*10)
print("New weights: ")
print(syn_wei)
print("=="*10)
print("Out after refresh: ")
print(out)
new_inp=np.array([[8,2,3]]).T #Введение нового значения для сравнения
out=Sigmoid(np.dot(new_inp, syn_wei))
print("New out: "+str(out))
print(out)
#out_str="".join(str(x) for x in out)
#print(out_str)
out_flt=0
for k in range(0,len(out)):
out_flt=out[k]
#print(out_flt)
if out_flt==0:
print("No matches")
elif out_flt>=0.5:
print("May have matches")
elif out_flt>=0.8:
print("Match")
else:
print("ERROR")
#out_flt=float(out_str)
#out_int=int(out_str)
#print("Results for new situation : "+out_str)
Related
There were a lot of people in our contest today, we numbered each of them separately, ie the first person 2, the second person 3, etc. In this order, 5, 7, 11, 13,… you understood the sequence.
Your task is to find the number of the N-person.
For example: User enters the value of N = 3.
Desired output: 5
The length of the value entered by the user is 10^9
The code I wrote. this number cannot be deduced
import math
def is_prime(n, div=2):
if div> int(math.sqrt(n)): return True
if n% div == 0:
return False
else:
div+=1
return is_prime(n,div)
a =int(input())
if a == 1:
print('2')
else:
primelist=[]
i=1;
while len(primelist)<999:
if is_prime(i):
primelist.insert(0,i)
i+=1
else: i+=1
print(primelist[-a-1])
Kindly advise.
I want to use the function serial_circuit with three different inputs (1,2,3). The function is suppose to accept multiple inputs from user until
user hits return, end program and sums up all inputs. The program only takes one input and display it.
def serial_circuit(num1):
num = 0
while(True):
try:
num += num1
except:
break
return num
print("1.Solve for serial resistance: ")
print("2.Solve for serial coils: ")
print("3.Solve for parallel capacitors: ")
choice = input("Enter choice: ")
if choice == '1':
num1 = float(input("Enter resistor value: "))
num = serial_circuit(num1)
print(f"Total resistance = {(num)} ohms")
elif choice == '2':
num1 = float(input("Enter coil value: "))
num = serial_circuit(num1)
print(f"Total inductance = {(num)} henrys")
elif choice == '3':
num1 = float(input("Enter capacitor value: "))
num = serial_circuit(num1)
print(f"Total capacitance = {(num):.6f} farads")
One of your problems is that you have the return statement inside the loop - notice your indentation - during the first iteration of the loop the last thing that will happen within the loop is returning from the serial_circuit function.
Another problem is that you are asking for the input only once - outside of the loop.
Take a look at this solution:
def serial_circuit(text):
num = 0
finishedEntering = False
while(not finishedEntering):
try:
received_input = input(text)
if received_input == "":
finishedEntering = True
else:
num1 = float(received_input)
num += num1
except:
break
return num
print("1.Solve for serial resistance: ")
print("2.Solve for serial coils: ")
print("3.Solve for parallel capacitors: ")
choice = input("Enter choice: ")
if choice == '1':
num = serial_circuit("Enter resistor value or hit enter to finish: ")
print(f"Total resistance = {(num)} ohms")
elif choice == '2':
num = serial_circuit("Enter coil value or hit enter to finish: ")
print(f"Total inductance = {(num)} henrys")
elif choice == '3':
num = serial_circuit("Enter capacitor value or hit enter to finish: ")
print(f"Total capacitance = {(num):.6f} farads")
I'm pretty much brand new to coding and decided to start with Python. I have been working on a simple "Number Guessing Game" and have evolved it a bit more each iteration.
I decided that I want to make it a little bit more robust that just finishing after the number is guessed.
I want the user/player to enter their name, have that name stored, and then used throughout... until the end, when they're asked if they want to play again and if it's the 'same user?" and if they say, "No.", I want it to append a new name to the list and then go through the game again.
This is what I've got so far... please be gentle... I know there's some errors :(
import sys
import os
import random
global player
while True:
def GuessingGame():
player = []
player.append(input("Please Enter Your Name:\n")),
# player_name = input("Please enter your name: \n")
print(f"Hello, {player[0]}! Let's get started!\n")
number = 500
count = 1
guess = int(input("Guess a number between 1 and 1000: \n"))
while guess != number:
count += 1
if guess > (number + 10):
print("TOO HIGH, a little lower...")
elif guess < (number - 10):
print("TOO LOW... guess higher!")
elif guess > (number + 5):
print("You're getting warmer, but still TOO HIGH, a little lower...")
elif guess < (number - 5):
print("You're getting warmer, but still TOO LOW... higher!")
elif guess < number:
print("You're REALLY warm, but still a bit TOO LOW")
elif guess > number:
print("You're REALLY, but still a bit TOO HIGH")
guess = int(input("Try again...\n"))
if guess == number:
print(f"You got it!!! It took you {count} tries to guess {number}\n")
response1 = str(input("Would you like to try again? Y or N\n"))
if response1 == ("y" or "Y"):
sameplayer = str(input("Is this still {player[0]}? Y1 or N1\n"))
if sameplayer == ("y1" or "Y1"):
GuessingGame()
else:
newplayer = player.extend(str(input("Please Enter New Player's Name:\n")))
print(f"Hello, {player[1]}!, Let's Get Started!")
return
GuessingGame()
Again, this is the first time I'm sharing anything I've done... so please don't just wreck me :)
Here i copy the same code you wrote, but with a little bit of modifications that i felt were needed to be made.
from random import randint
player = None
def GuessingGame():
global player
if player is None:
player = input("Please Enter Your Name:\n")
print(f"Hello, {player}! Let's get started!\n")
number = randint(1, 1000)
guess = int(input("Guess a number between 1 and 1000: \n"))
count = 1
while guess != number:
if guess > (number + 10):
print("TOO HIGH, a little lower...")
elif guess < (number - 10):
print("TOO LOW... guess higher!")
elif guess > (number + 5):
print("You're getting warmer, but still TOO HIGH, a little lower...")
elif guess < (number - 5):
print("You're getting warmer, but still TOO LOW... higher!")
elif guess < number:
print("You're REALLY warm, but still a bit TOO LOW")
elif guess > number:
print("You're REALLY, but still a bit TOO HIGH")
if guess == number:
break
else:
count += 1
guess = int(input("Try again...\n"))
print(f"You got it!!! It took you {count} tries to guess {number}\n")
response1 = str(input("Would you like to try again? Y or N\n"))
if response1.lower() == 'y':
sameplayer = str(input(f"Is this still {player}? Y or N\n"))
if sameplayer.lower() == 'n':
player = None
return
else:
return
while True:
GuessingGame()
Let me know if you got any questions.
5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
print(num)
print("Maximum", largest)
and the output must be like this
Invalid input
Maximum is 10
Minimum is 2
somebody please help me with this????? enter image description here
I think this will do your work,
With simple if conditions
# Defining two variables to None.
largest = None
smallest = None
# starting an infinite loop
while True:
num = input("Enter a number: ")
# try block to capture ValueError
try:
if num == "done":
break
# assign the values of largest and smallest to num if its None ( on first iteration)
if largest is None:
largest = int(num)
if smallest is None:
smallest = int(num)
# changing the values of it greater or smaller
if int(num) > largest:
largest = int(num)
if int(num) < smallest:
smallest = int(num)
# capture the type error and ignores.
except ValueError:
print("ignored.")
continue
print("Maximum: " + str(largest))
print("Minimum: " + str(smallest))
By making use of list and it's methods
# Defining an empty list.
myList = []
# starting an infinite loop
while True:
num = input("Enter a number: ")
# try block to capture ValueError
try:
if num == "done":
break
# append the entered number to list if valid
myList.append(int(num))
# catches value error and ignores it
except ValueError:
print("ignored.")
continue
# prints maximum and min
if len(myList) > 0:
print("Maximum: " + str(max(myList)))
print("Minimum: " + str(min(myList)))
else:
print("List is empty")
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
num = int(num)
if largest is None or largest < num:
largest = num
elif smallest is None or smallest > num:
smallest = num
except ValueError:
print("Invalid input")
print ("Maximum is", largest)
print ("Minimum is", smallest)
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
n = int(num)
except:
print ('Invalid input')
continue
if largest is None or n > largest:
largest = n
if smallest is None or n < smallest:
smallest = n
print("Maximum is", largest)
print("Minimum is", smallest)
#Print out largest and smallest number
largest=None
smallest=None
while True:
n = input('Enter a number: ')
if n == "done":
break
try:
num=int(n)
if largest is None:
largest = num
elif num > largest:
largest = num
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
except:
print("Invalid input")
print('maximum:', largest)
print('Minimum:', smallest)
I want to add two matrcies in python 3 but the problem comes when I add input to the program
Here is my code
def addmatrix(a,b):
d=[]
n=0
while n < len (a):
c = []
k = 0
while k < len (a[0]) :
c.append(a[n][k]+b[n][k])
k += 1
n += 1
d.append (c)
return d
def main():
a = input("Enter a Matrix: ")
b = input("Enter another Matrix: ")
print (addmatrix(a,b))
main()
If the input is
Enter a Matrix: [[5,6], [1,2], [2,4]]
Enter another Matrix: [[2,3], [-6,0], [-2, 4]]
The output comes out as [['[['], ['[['], ['52'], [',,'], ['63'], [']]'], [',,'], [' '], ['[['], ['1-'], [',6'], ['2,'], [']0'], [',]'], [' ,'], ['[ '], ['2['], [',-'], ['42'], ['],'], ['] ']]
But if I take out the input from the program and make it so that
def main():
a = [[5,6], [1,2], [2,4]]
b = [[2,3], [-6,0], [-2, 4]]
print (addmatrix(a,b))
main()
The output then comes out as [[7, 9], [-5, 2], [0, 8]] which is correct.
Is there a way I can make my program work so that when a person inputs two matrices they add together? I'm new at python so any help will be appreciated :)
You will have to convert the user input into a Python object. Right now, it's a string.
You can use eval (which should not be used if you don't know what your users will input. I can type in __import__('os').system('rm /some/file.txt') and Python will delete a file):
a = eval(input("Enter a Matrix: "))
Or you can use ast.literal_eval, which is safe:
from ast import literal_eval
...
a = literal_eval(input("Enter a Matrix: "))
Try this:
import ast
def addmatrix(a,b):
return [map(sum, zip(*x)) for x in zip(a,b)]
def main():
a = ast.literal_eval(raw_input("Enter a Matrix: "))
b = ast.literal_eval(raw_input("Enter another Matrix: "))
print addmatrix(a,b)
main()