## algorithm – First non-repeating Character, with a single loop in Python

As has been pointed out in the comments and @Kraigolas’s answer, the existing algorithm doesn’t work. Here’s why.

In the string `"xxy"`:

1. The algorithm first considers the third character, `"y"`. It finds it has not encountered it before, so records it as a preliminary `out` value. It adds it to `smap` with value `1`.
2. The algorithm next considers the second character, `"x"`. It finds it has not encountered this character before, either. It discards its previous preliminary `out` value, `"y"`, and adopts `"x"` as its new preliminary `out` value. It adds `"x"` to the dictionary with value `1`.
3. The algorithm now moves on to the first character, `"x"`. It realises that it has seen this one before, so adds `1` to the associated value in `smap`.
4. The algorithm has now finished iterating through the loop. Its current `out` value is `"x"`, but when it looks it up in the dictionary, it finds it has encountered `"x"` more than once. As a result, it assumes that there are 0 characters that it has seen only once, and returns `None`.

It is impossible to fix the current implementation of the algorithm while keeping to the condition that there should be “only a single loop”. If you were to relax this restriction, you could fix your current algorithm like this:

``````def first_non_repeater(string):
smap = {}

for i in range((len(string) - 1), 1, -1):
char = string(i)

if char in smap:
smap(char) += 1
else:
smap(char) = 1

while True:
try:
key, val = smap.popitem()
# KeyError is raised  it you try to do .popitem()
# on an empty dictionary
except KeyError:
return None
else:
if val == 1:
return key
``````

But at I say, this breaks the condition that only one loop is allowed.

I like @FMc’s answer using `collections.Counter` a lot; I think this is probably the most pythonic way of doing this.
The following solution, however, would be my attempt at a solution that only uses builtin data structures (nothing from `collections`), and that only uses a single loop. The solution only works on python 3.6+, as it relies on `dict`s being ordered. Feedback welcome:

``````from typing import TypeVar, Union, Optional

T = TypeVar('T')

def first_non_repeating_char(
string: str,
default: Optional(T) = None
) -> Union(str, T, None):
"""Return the first non-repeating character in a string.

If no character in the string occurs exactly once,
the function returns  the default value.

Parameters
----------
string: str
The string to be searched.
default: Any, optional
The value that is returned if there is no character
in the string that occurs less than twice,
by default None

Returns
------
Either a string of length 1, or the default value.
"""

# Using a dictionary as an ordered set,
# for all the characters we've seen exactly once.
# The values in this dictionary are irrelevant.
uniques: dict(str, None) = {}

# a set for all the characters
# that we've already seen more than once
dupes: set(str) = set()

for char in string:
if char in dupes:
continue

try:
del uniques(char)
except KeyError:
uniques(char) = None
else:

# return the first key in the dictionary
# if the dictionary isn't empty.
# If the dictionary is empty,
# return the default.
return next(iter(uniques.keys()), default)
``````

Posted on

## php – Loop for recently (updated_post_meta) posts?

I’m trying to create a simple loop for recently updated post meta_key.

Basically, let’s say someone liked a post.

When like was clicked, that updated post `meta_key` ‘like’ value.

I want to display on the sidebar a loop with newest liked posts.

Is that possible?

Any help would be appreciated.

P.S. I know how to create a function action that does something, when post meta data was updated.

But I don’t need that. I want to show a simple loop with recently liked (meta updated) posts.

## Optimization of for loop

I am trying to build a model that allows me to estimate the spread of disease in the population. The setup is similar to the SIR model, with the difference that this model includes the stochastic component.

I have written an algorithm to carry out the simulation, but the lead times are really high. Could you please help me optimize the code? Below is the code.

``````Population = 100000
Time = 365
r_0 = 0.02
start_positive = 100
min_positive_days = 5
max_positive_days = 15

Pop_over_time <- matrix("S", ncol = Time, nrow = Population, dimnames = list(1:Population, paste0("T",1:Time)))
I0 <- sample(Population, start_positive)

for (i in I0) {
Pop_over_time(i, 1) <- "I"
nr <- trunc(runif(1, min_positive_days, max_positive_days))
Pop_over_time(i, 1:nr) <- "I"
Pop_over_time(i, (nr):(Time)) <- "R"
}

for (i in 2:Time) {
r_s <- r_0 * sqrt(2 + sin(500 + i * 2 * pi / 365)) / 2

for (j in 1:Population) {
if (Pop_over_time(j, i - 1) == "I") {
for (z in (1:k(j))) {
if (Pop_over_time(Link(j, z), i - 1) == "S") {
Pop_over_time(Link(j, z), i) <- rbinom(1, 1, r_s)

if (Pop_over_time(Link(j, z), i) == 1) {
nr <- trunc(runif(1, min_positive_days, max_positive_days))
nr_min <- min((i + nr - 1), Time)
rep(1, length(i:nr_min))

}
}
}
}

}
Pop_over_time(, i)(Pop_over_time(, i) == 1) <- "I"
Pop_over_time(, i)(Pop_over_time(, i) == 0) <- "S"

}
``````

In a first part I create a matrix (Link) that defines all the links within the population.
So first I define variables, then I create a matrix that saves, for each day, the situation of the population.
Then I define the first 100 cases (with a sampling) and after that the heaviest part of the code starts. r_s (the probability of contagion) is defined in a seasonal way. So, for each member of the population that I infect I generate a binomial variable for each of his contacts: if the number generated is 1 then the infection has occurred, vice versa not.

I would be very grateful for your help.
Greetings

Posted on Tags ,

## php – Erro no loop, o botão exibe a informação errada

Não importa o botão que eu clique, sempre exibe o primeiro resultado.

Como posso fazer para que ao clicar em cada botão seja exibido o seu respectivo número?

``````        <p id="informativo">Digite um número abaixo</p>

<form method="post" action="">
<input id="cpf_processo" type="text" size="50" name="num_usuario" required="required"
placeholder="Digite aqui">
<input id="consultar" type="submit" name="vis_numero" value="CONSULTAR">
</form>

<script type="text/javascript">
function visTabela(id) {
var numero = document.getElementById("numero");
var informativo = document.getElementById("informativo");
if (numero.style.display === "none") {
numero.style.display = "revert";
} else {
numero.style.display = "none";
informativo.style.display = "revert";
}
}
</script>

<?php
\$numUsuario = filter_input(INPUT_POST, 'num_usuario', FILTER_SANITIZE_STRING);
\$visNumero = filter_input(INPUT_POST, 'vis_numero', FILTER_SANITIZE_STRING);

if (\$visNumero == true) {

for (\$i = 0; \$numUsuario > \$i; \$i++) {

\$infor = "<div id='informativo' style='display: block'> clique no botão acima</div> <br>";
\$mosNum = "<div id='numero' style='display: none'>O número do botão: \$i </div>";
\$botao = "<button style='margin-top: 4%' onclick='visTabela()'>Mostrar número</button> ";

echo "\$botao";
echo "\$infor";
echo "\$mosNum";
}
}
``````

## java – Meu método volta com resultado nulo toda vez que envio para um loop

``````import java.util.*;

class Main {
public static void main(String() args) {
int num = 0;

System.out.println("nInsira um número:");

perfeito(num);
int soma = perfeito(num);

if(soma == num){
}
else{
System.out.println("nO número informado não é perfeito!");
}
}

public static int perfeito(int num) {
int soma = 0;

for(int n = 0;n < num;++n){
if(num % 'n' == 0) {
soma = (soma + num);
}
}
return soma;
}
}
``````

Ele roda o programa normal, não dá nenhum erro, porém o valor só volta igual a ‘0’, o problema é no loop? O que posso fazer pra contornar esse erro?
Ah, além disso, todos os meus outros programas envolvendo métodos funcionaram normal, só os que envolvem o loop que tem dado esse problema.

## recovery mode – Analyzing boot loop Root cause from console-ramoops-0 ( & logcat)

`Boot-looped` and got stuck in powered by android logo. `Logcat` hasnt been much useful. Wanna know what’s causing the stuck.
All I have is this from `/sys/fs/pstore/console-ramoops-0`

``````'android.frameworks.sensorservice@1.0::ISensorManager/default': No such file or directory
``````

I am attaching Entire /sys/fs/pstore/console-ramoops-0

what seems the issue ?
I have TWRP backups of `vendor system boot` that i tinkered restores with. No Luck. This is stock `MIUI ROM` with `TWRP as recovery base` so after flashing dm-verify-no encrypt.zip ( cant recall the exact name ) + certification.zi & permssiver I get past `MIUI` logo but now looping at powered by `android` logo

Posted on

## turing machines – Complexity of the language that enters an infinite loop

A few days ago I had a test that I failed to pass, and it had a question that I failed to do.

This is the question

Let’s look at the language $$L_loop =$${
$$left langle M,w right rangle$$ | When M is activated on the input w, the machine M enters an infinite loop }

We will mark our input length: $$|left langle M,w right rangle| = n$$. Determine which of the claims is correct:

1. The language is in $$P$$
2. The language is not in $$NP$$ or $$CoNP$$.
3. The language is in $$NP$$ but not in $$NPC$$.
4. The language belongs to $$CoNP$$.
5. None of the above claims are true.

From what I understand in the question, there is a language that accepts Turing machines that go into an endless loop.

1. It cannot be, if the machine works infinitely, it is impossible to know in polynomial time when we will get yes and when we will get no. It has no algorithm.
2. Probably can not either. A problem will be in NP if it has a non-deterministic guessing algorithm. If a witness gives input, it is not possible to say yes to the answer, because it is infinite.
3. Do not know about it, maybe he is right
4. Language should belong to Conp only when a guessing algorithm should say no. And I do not know if here should be said no and then it’s CoNP or say yes and then it’s NP.

I tried to figure out what the answer might be, but I could not figure out the answers to the question.

Maybe 5 is right, because I could not tell everyone else that they were right

Posted on

## Passing flask textbox value to an infinite while loop

Passing flask textbox value to an infinite while loop | Web Hosting Talk

‘);
var sidebar_align = ‘right’;
var content_container_margin = parseInt(‘350px’);
var sidebar_width = parseInt(‘330px’);
//–>

1. ## Passing flask textbox value to an infinite while loop

I’m running a flask server, with a textbox input and a while loop (in a different thread). I want to pass the input value from the textbox to the while loop.

This is the .py code:

Code:

```from flask import Flask, render_template, request
import time

def main():

while True:
time.sleep(5)
print "var = "+str(var)

@app.route("/")
def index():

templateData = {
'var': var

}
return render_template('index.html', **templateData)

@app.route("https://www.webhostingtalk.com/", methods=('POST'))
def post():

global var
var = 0
var = int(request.form('var'))
return str("var: " + str(var))

if __name__ == "__main__":
app.run(host='0.0.0.0', port=8083, debug=True)```

This is the .html code:

HTML Code:

```<!DOCTYPE html>
<title>POST</title>
<body>
<form method="POST">
var:<br>
<input name="var">
<br><br>
Current:    {{ var  }} <br><br>
<input type="submit">
</form>
</body>
</html>```

I don’t know what is the proper way to get the value to the while loop, because I’m getting mixed signals in the loop. If I for example write 3 in the textbox I’ll get…

Code:

```var = 0
var = 3
var = 0
var = 3
var = 0
var = 3
var = 0
var = 3```

…in the while loop, because it’s first reading var = 0 and then var = int(request.form(‘var’))

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

## python – sudden interruption of the loop

I continue to master the basics of programming by coming up with a game. The error is related to the interruption of the loop when the length of the list reaches 3 item. If lenght of my list == 3 the loop is interrupted.
I do not understand what’s the matter.part of the code is working. copy, press 2 to start the cycle and press 1 until the length of the list becomes 3

``````    class Hero():
def __init__(self, name, level, race, position):
self.name = name
self.level = level
self.race = race
self.position = position
self.maxhealth = 1000
self.health = 1000
self.damage = 300

def walk(self):
self.position += 1

def attack(self, name_enemy):
name_enemy.health = name_enemy.health - self.damage
if name_enemy.health <= 0:
name_enemy.health = 0
return name_enemy.health
class Enemy():
def __init__(self, health, damage, race):
self.health = health
self.damage = damage
self.race = race
self.position = 1
enemys = ()

for obj in range(5):
obj = Enemy(200, 50, "Орк")
enemys.append(obj)
for obj in range(5):
obj = Enemy(200, 50, "Человек")
enemys.append(obj)
for obj in range(5):
obj = Enemy(200, 50, "Гоблин")
enemys.append(obj)
Pers = Hero("test", 1, "Человек", 0)
def action():
if enemy.position == Pers.position and Pers.health > 0:
while Pers.health > 0:
_______________________________________

Нажми '1' Атаковать!!!n
_______________________________________
n Твой ответ?tt""")
if enemy.health > 0 and Pers.health > 0:
Pers.attack(enemy)
if Pers.health <= 0:
print("text for testing2")
break
if enemy.health > 0 and Pers.health > 0:
enemy.attack(Pers)
if enemy.health <= 0:
print(len(enemys))
for i in enemys:
print(i.race)
enemys.remove(enemy)
print(len(enemys))
for i in enemys:
print(i.race)
break
if len(enemys) == 0:
print("Врагов не осталось!!!")
print(f"{Pers.name} Ты победил!!!")
######################################START_GAME##############################################################
while len(enemys) > 0 and Pers.health > 0:
for enemy in enemys:
if len(enemys) > 0 and Pers.health > 0:
action()
if len(enemys) <= 0 or Pers.health <= 0:
print("text for testing1")
break