Rudimentary Python/ArcPy skills at work here, not sure where I'm going wrong.
Trying to do a simple random selection of 10 features from a layer to be indicated by the placement of a "1" in another attribute set aside for this purpose. Basic concept is is to use random.sample() to generate a random list of 10 FID's, and then check to see if each FID is in the list. NewID is an attribute containing FID's values. This is what I have in the code block:
import random
def randSelTen():
featurecount = arcpy.GetCount_management("layer_name")
linecount = int(str(featurecount))
lst_oids = range(0, linecount)
rand_lines = random.sample(lst_oids, 10)
if !NewID! in rand_lines:
return 1
else:
return 0
I keep getting a syntax error on the conditional containing !NewID!, and no matter what I do I can't fix it. If I replace !NewID! with an integer, the script runs, but of course the output is bad. Any help is appreciated... thanks!
If you are putting this code in the "Codeblock" of the field calculator then the reason you are getting a syntax error is because you can not access fields like that from the codeblock. You must pass in the field as an argument to the function. So you would have to do this:
# -----Codeblock---------
import random
def randSelTen(NewID):
featurecount = arcpy.GetCount_management("layer_name")
linecount = int(str(featurecount))
lst_oids = range(0, linecount)
rand_lines = random.sample(lst_oids, 10)
if NewID in rand_lines:
return 1
else:
return 0
# ----- Expression (goes in bottom text box of the field calculator if using GUI) -----
randSelTen(!NewID!)
Related
I am kind of new to python and I am facing a lot of trouble because for some reason this value within my class method is updating by it self even though I didn't touch it. I can't even make it constant... Here is the relevant piece of code that does it.
the method that is called:
def swapping(self,pos,puzzle):
print('Old puzzle \n',puzzle)
# Getting Zero point index
zero = obj.null_pos(puzzle)
# Getting Index of varied position
var = puzzle[pos[0]][pos[1]]
#Swappping values
puzzle[zero[0,0],zero[0,1]] = var
puzzle[pos[0], pos[1]] = 0
new_puzzle = puzzle
print('New_puzzle \n',new_puzzle)
return new_puzzle
# The code has been snipped into relevant parts only
for i in range(len(child_node)):
# Check the hn of each node
print(child_node[i])
#where it occurs:
num_mispl = obj.misplaced_tiles(nod.swapping(child_node[i],new_puz))
# <-- new_puz #value changes and i didn't assign it to anything
temp_stor.append(num_mispl)
I'm attempting to create a game similar to battleship, and I'm having trouble figuring out how I would initialize the board by having each cell begin with an 'O' and displaying it to the user. A requirement for the function player_board() is that it's supposed to take in a grid representing the player's game board as an argument and output it to the user's screen. This is a portion of my code that I'm struggling with. I'm also not sure why it keeps printing out an extra 'O' at the end. Any help or feedback would be appreciated!
import random
sizeof_grid = 9
chance = 10
def mines():
grid = [{("M" if random.randint(0, chance) == 0 else " ") for i in
range(sizeof_grid)} for i in range(sizeof_grid)]
return grid
def initialize_board():
start_board=[["O" for i in range(sizeof_grid)] for i in range(sizeof_grid)]
return start_board
def players_board():
for r in initialize_board():
for c in r:
print (c, end="")
print()
return c
print(players_board())
You get the extra "O: because of the last line of code. You call the function with print(players_board) and in the function itself you return c (which has the value of one "O"). This means you print out the return value of the function which is "O".
You can execute the function with players_board() and remove the print().
Also you can remove the return c at the bottom of the function.
new to Python - struggling with functions. - Image of code attached.
It inputs the name & scores just fine with the validation checks.
I need to use the scores input by the user and total them.
However, when I've tried to sum(score) it doesn't like it.
I can't work out how to sum the 4 total scores.
Please help :) Also would love any feedback on the style of coding etc.
Thanks in advance x
Image: Code in Python
I would rewrite the main function to be something like:
def GetStudentInput():
score = 0
for i in range (4):
print("Mrs Pearson's Class Test Score Data")
name = CheckStringInput("What's Your Name: ")
score += CheckNumericInput("What's Your Score: ")
print(score)
This eliminates the need for an extra function and avoids using a list since you don't appear to need the individual values elsewhere -- only the sum total.
In the absense of code for people to see, we have something like
def get_stuff():
for i in rnage(4):
name = input("Name?")
score = int(input("Score?"))
and another function
def TotalScore():
pass
How do we call total score?
Answer: Make sure we don't forget the user inputs and return them:
def get_stuff():
names = []
scores = []
for i in range(4):
names.append(input("Name?"))
scores.append(int(input("Score?")))
return names, scores
and take the scores in the summing function:
def TotalScore(scores):
return sum(scores)
This, of course, changes the calling code.
For example, you need to capture the returns when you call get_stuff:
names, scores = get_stuff()
total = TotalScores(scores)
I've been write this practice program for while now, the whole purpose of the code is to get user input and generate passwords, everything almost works, but the replace statements are driving me nuts. Maybe one of you smart programmers can help me, because I'm kinda new to this whole field of programming. The issue is that replace statement only seems to work with the first char in Strng, but not the others one. The other funcs blower the last run first and then the middle one runs.
def Manip(Strng):
#Strng = 'jayjay'
print (Strng.replace('j','h',1))
#Displays: 'hayjay'
print (Strng.replace('j','h',4))
#Displays: 'hayhay'
return
def Add_nums(Strng):
Size=len(str(Strng))
Total_per = str(Strng).count('%')
# Get The % Spots Position, So they only get replaced with numbers during permutation
currnt_Pos = 0
per = [] # % position per for percent
rGen = ''
for i in str(Strng):
if i == str('%'):
per.append(currnt_Pos)
currnt_Pos+=1
for num,pos in zip(str(self.ints),per):
rGen = Strng.replace(str(Strng[pos]),str(num),4);
return rGen
for pos in AlphaB: # DataBase Of The Positions Of Alphabets
for letter in self.alphas: #letters in The User Inputs
GenPass=(self.forms.replace(self.forms[pos],letter,int(pos)))
# Not Fully Formatted yet; you got something like Cat%%%, so you can use another function to change % to nums
# And use the permutations function to generate other passwrds and then
# continue to the rest of this for loop which will generate something like cat222 or cat333
Add_nums(GenPass) # The Function That will add numbers to the Cat%%%
print (rGen);exit()
I'm trying to do a simple declaration of an inputted variable to an integer, but am receiving an error:
Bargle. We hit an error creating a run python. :-( Error:
Your code had an error! Traceback (most recent call last): File "/tmp/tmpXq4aAP/usercode.py", line 7, in the_function num = int(input['managers']) KeyError: 'num'
The following is the code i'm using:
num = int(input['num'])
if num >= 100 :
big_num = true
else:
big_num = false
return {'big_num': big_num}
Your error is right here:
num = int(input['num'])
Change those square brackets for round brackets:
num = int(input('num'))
If you are on Python 2 you should use raw_input
num = int(raw_input('num'))
In Zapier, the code:
input['varname']
refers to the variable that is passed in the "Code by Zapier" Action.
The error you are getting sounds to me like you have not defined the num variable prior to your code.
Also, True and False need to be capitalized.
Otherwise, see below, this setup works...
num = int(input['num'])
if num >= 100 :
big_num = True
else:
big_num = False
return {'big_num': big_num}
Many of these answers reference the input() built in - we override that in Code by Zapier (since it literally makes zero sense to have user input on an automated script). In it's place is a dictionary defined by some fields above.
Definitely confusing for folks unfamiliar with the context of Zapier - we'll look into renaming it and just nulling the input build.
Input is a kernel method and it can't be subscriptable , there is an syntax error change the code to like this.
num = int(input('num'))
Within Zapier, the proper way to convert Input Data (every input into a Code Step is a String) to Integers is as follows:
num = int(input.get('num'))
or
num = int(input['num'])
If the number comes attached with a decimal, strip the unwanted characters from the String before converting to an Integer. For a number like 80.0 this would look like:
num = int(input['num'][:-2])