"The Minion Game" challenge This is an implementation of the minion game, which takes in string input and declares a winner between two pre-determined players.

The logic is player 1 gets all sequenced words not starting with a vowel and player 2 gets all sequenced words starting with vowel in the input string.

Objective: performance optimisation. The code passed all the test cases, but I am very unsure where to tune the performance.

For a 1000 letter word, here are the time stats:

real 0m10.142s
user 0m6.386s
sys 0m0.743s

import string
import sys
import itertools

def minion(str):
    person_a_name = 'Stuart'
    person_b_name = 'Kevin'
    letter_list = [a for a in str]
    l = len(letter_list)
    vowel = ['A','E','I','O','U']
    consonants = ['Q','W','R','T','Y','P','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M']
    all_word = []
    person_a_words = []
    person_b_words = []
    all_word = [letter_list[start:end+1] for start in xrange(l) for end in xrange(start, l)]
    for array in all_word:
        if array[0] in vowel:
            person_b_words.append(array)
    for array in all_word:
        if array[0] in consonants:
            person_a_words.append(array)
    if len(person_a_words) == len(person_b_words):
        print 'Draw'
    if len(person_a_words) > len(person_b_words):
        print person_a_name, len(person_a_words)
    if len(person_b_words) > len(person_a_words):
        print person_b_name, len(person_b_words)

def main():
    str = raw_input()
    minion(str.upper())

if __name__ == '__main__':
    main()

Sample input / output:

banana
Stuart 12

guavaisanotherfruit
Kevin 98

The big performance hit probably comes in this block of code, where you don a bunch of array manipulations and looping:

all_word = [letter_list[start:end+1] for start in xrange(l)
                                     for end in xrange(start, l)]
for array in all_word:
    if array[0] in vowel:
        person_b_words.append(array)
for array in all_word:
    if array[0] in consonants:
        person_a_words.append(array)
if len(person_a_words) == len(person_b_words):
    print 'Draw'
if len(person_a_words) > len(person_b_words):
    print person_a_name, len(person_a_words)
if len(person_b_words) > len(person_a_words):
    print person_b_name, len(person_b_words)

Appending to an array is a (relatively) expensive operation, as is looping over a list. I can see a number of optimisations here. [Edit: I wrote these in the order I thought of them; the big performance gain comes on the last item. I'm leaving the remaining items because they're still instructive, even if not directly applicable here.]

Only loop over all_word once. You can check for starting with a consonant and vowel in the same iteration of the loop:

for array in all_word:
    if array[0] in vowel:
        person_b_words.append(array)
    elif array[0] in consonants:
        person_a_words.append(array)

We've just cut out an iteration over all_word. If all_word is large, that will be a significant saving.
Don't store the words in a list, just the count. All you care about is the relative number of words in each list; the words themselves don't matter. It's much easier to increment an integer than mutate a list, so consider the following:

person_a_words = 0
person_b_words = 0
for array in all_word:
    if array[0] in vowel:
        person_b_words += 1
    elif array[0] in consonants:
        person_a_words += 1

and then you can compare the two integers at the end. That's bound to be a performance saving.
Don't construct all_word as a list; use a generator. If you replace the square brackets with parens:

all_word = (letter_list[start:end+1] for start in xrange(l)
                                     for end in xrange(start, l))

then this becomes a generator comprehension instead of a list comprehension. This means it only creates the elements as they're needed by the for loop; it doesn't create them all in memory before continuing.

Using generators instead of lists is a really good way to reduce occupancy and speed up programs.
Do you even need to use all_word? For each value of start, the first letter of the resulting words will be the same, and this gives you (l - start) different words. You don't actually need to create the words; you just care about their initial letter, and how many distinct words they create.

You could just add the number of distinct words to each person's score directly:

person_a_words = 0
person_b_words = 0
for idx, letter in enumerate(letter_list):
    if letter in vowel:
        person_b_words += len(letter_list) - idx
    else:
        person_a_words += len(letter_list) - idx

That is substantially faster: I just ran this with a 1.5m character string, and it finished in ~1.5s.

Other non-performance related comments:

Don't use str as a variable name; overriding builtins is bad practice.
You've imported the string, sys and itertools modules, but you never use any of them. Why?
PEP 8 requires a space after commas in a list; you should add this in vowel and consonants.
You can get the individual letters of a string by calling list() on it. These calls are equivalent:

letter_list = [a for a in my_string]
letter_list = list(my_string)

although in this case, you don't need to coerce to a list first – you can iterate over the characters of a string directly.
There's no need to assign the length of letter_list to a variable, especially not one with as undescriptive a name as l. It just makes your code harder to read.
The name of your function isn't particularly helpful. Ideally it should give me some idea of what the function does. There should also be a docstring to explain the result.
I would rename the person_a* and person_b* variables to be consonant* and vowel*, respectively – that will make the code easier to read. A and B don't really mean anything (and as evidence, I got them the wrong way round when I first wrote that sentence).
Your function is doing some work (finding out whether there are more vowel sub-words or consonant subwords) and printing to screen (the result). It would be better to separate this into two functions: one that does the work, the other does the result.

That makes it easier to reuse the work of vowels vs. consonants.
To aid readability, I'd keep the same order of variables when you do the comparison at the end. i.e.

if vowel_count > consonant_count:
    print("Vowels victorious!")
elif vowel_count < consonant_count:
    print("Consonants champion!")
else:
    print("Draw!")

Using Python2 this worked.

def minion_game(s):
    Stuart, Kevin = 0,0
    length = len(s)
    for idx,sub in enumerate(s):
        if sub in 'AEIOU': Kevin += length - idx
        else: Stuart += length - idx
    print(['Draw','Kevin {}'.format(Kevin),'Stuart {}'.format(Stuart)][0 if Kevin == Stuart else 1 if Kevin>Stuart else 2])

if __name__ == '__main__':
    s = raw_input()
    minion_game(s)


PHP function to access a database and return json <?php

include_once('../dbInfo.php');

function getReport($user_table) {
    $tables = array(
        "day"        => "p_day",
        "month"      => "p_month"
        ... etc. .....
    );

    $table = $tables[$user_table];

    if(!$table) {
        die(json_encode(array("error" => "bad table name")));
    }

    $con = getConnection(); // getConnection is in '../dbInfo.php'

    $query = "select * from " . $table;
    $res = mysql_query($query, $con);

    if(!$res) {
        die(json_encode(array("error" => "no results from table")));
    }

    $fields_num = mysql_num_fields($res);
    $fields = array();
    for($i=0; $i < $fields_num; $i++) {
        $field = mysql_fetch_field($res);
        $fields[$i] = $field->name;
    }

    $i = 0;
    while($row = mysql_fetch_array($res)) {
        $rows[$i] = $row;
        $i++;
    }
    $json = array("rows" => $rows, "headers" => $fields);

    $jsontext = json_encode($json);
    return $jsontext;
}

?>

What this code is doing:

access the database, selecting rows from a table, and returning them as a serialized json object
a table name is looked up in $tables -- the keys are acceptable user input, the values are actual table/view names in the database
data is selected from the table
the data is put into a big hash
the hash is serialized as a json string and returned

Specific issues I'm concerned about:

security -- is my DB connection info safe?  This file is in the root directory of public content, so dbiInfo.php, with the database connection information, is not publicly accessible (I think)
security -- am I open to SQL injection attacks?  I build a SQL query with string concatenation
security -- $user_table is untrusted input; is it safe?  It's only used as a key to look up trusted input ...
error handling -- have I dealt with all error conditions
there are lots of versions of PHP functions -- am I using the right ones?

General issues:

following conventions
quality/readability/comments

Edit:  the data is publicly available -- I'm worried about somebody getting more than read access to one of the listed tables, or any access to any other table in the DB.

This:

$tables = array(
    "day"        => "p_day",
    "month"      => "p_month"
    ... etc. .....
);

$table = $tables[$user_table];

if(!$table) {
    die(json_encode(array("error" => "bad table name")));
}

will throw a notice if $user_table is not a valid array key, something you should have already tested. Rewrite as:

$tables = array(
    "day"        => "p_day",
    "month"      => "p_month"
    ... etc. .....
);

if(!array_key_exists($user_table, $tables)) {
    die(json_encode(array("error" => "bad table name")));
}

$table = $tables[$user_table];

I really hate it when functions die(), and in your case there's no point in that. You could simply do:

if(!$table) {
    return json_encode(array("error" => "bad table name"));
}

since the function is expected to return a json formatted string. If you really want to die() you should do that where you call the function and the returned string is an error. Or you could just return false when an error occurs and the raw array when everything works, and when calling the function do something like:

$result = json_encode(getReport("some_table"));

That way getReport() will be useful even when you don't need json encoded output. But that's up to you and how you actually use it.

As @LokiAstari mentions mysql_* functions are deprecated and should be avoided. I would skip mysqli_* functions too and use PDO which will give you the extra bonus of switching to another database engine if you ever need to and it has a nice OO interface.

For everything else, I'm with @LokiAstari.

<?php

include_once('../dbInfo.php');

function resolve_table($user_table) {
    $tables = array(
        "day"        => "p_day",
        "month"      => "p_month"
        ... etc. .....
    );

    // check table exists or return null
    return isset($tables[$user_table]) ? $tables[$user_table] : null;
}

function getReport($user_table) {

    $output = array();

    try {
        // move resolve table into separate function so can be reused
        $table = resolve_table($user_table);

        if(!$table) {
           // don't die here, throw and exception instead
           throw new Exception("bad table name");
        }

        $con = getConnection(); // getConnection is in '../dbInfo.php'

        // this is safe as $table is a trusted source,
        // have added backticks around table name incase it is a reserved word in mysql
        // $query = "select * from " . $table
        $query = "select * from `$table`";

        $res = mysql_query($query, $con);

        if(!$res) {
            // don't return error here, throw exception
            throw new Exception("no results from table");
        }

        // do you want to handle the case of no results?
        if (mysql_num_rows($res) == 0) {
            throw new Exception("no results from table");
        }

        // as others have said, mysqli_ or pdo not mysql_ functions
        // see nicer way of doing this below
//        $fields_num = mysql_num_fields($res);
//        $fields = array();
//        for($i=0; $i < $fields_num; $i++) {
//            $field = mysql_fetch_field($res);
//            $fields[$i] = $field->name;
//        }

        // declare the array before using
        $rows = array();

        // not needed
        // $i = 0;

        // use fetch assoc instead to get an associative array
        // while($row = mysql_fetch_array($res)) {
        while($row = mysql_fetch_assoc($res)) {
            // $rows[$i] = $row;
            // $i++;

            // [] automatically adds next element to array
            $rows[] = $row;
        }

        // assuming there is at least 1 row in result set (we have tested for 0 rows above)
        // we can just get the array_keys of the last $row
        $fields =  array_keys($row);

        // if exceptions have been thrown we will never reach this line
        $output = array("rows" => $rows, "headers" => $fields);

    } catch (Exception $ex) {
        $output['error'] = $ex->getMessage();
    }

    // not necessary
    // $jsontext = json_encode($output);

    return json_encode($output);
}

// remove closing php tag (unless something follows), otherwise you may have unwanted whitespace after it, which can cause header or cookie issues
// ?  >


Handling a response in a @Controller I have a simple spring controller which takes a @ModelAtrribute object and registers an employee. If it is a success, I forward it to a success, else an error page, and I am doing this via a boolean return value from @Service and Dao.

@Controller:

@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView registerEmployee(@ModelAttribute LoginModel loginModel){
    LOGGER.info(" REGISTER Controller [{}] ",loginModel.toString());
    ModelAndView model = new ModelAndView();
    if(!registerService.registerEmployeeByAdmin(loginModel)){
      model.setViewName("register");
      model.addObject("errorMessage", "Unable to register user, Please try again");
      return model;
    }
    model.addObject("employee", loginModel);
    return model;
}

@Service:

public boolean registerEmployeeByAdmin(LoginModel loginModel){
    LOGGER.info("Saving Employee login info ",loginModel.toString());
    boolean registered = registerDao.registerEmployeeByAdmin(loginModel);
    if(registered)
        registerDao.registerEmployeeInfo(loginModel);

    return registered;   //the value returned
}

Dao:

public boolean registerEmployeeByAdmin(LoginModel loginModel) {
    boolean registered = false;
    String addEmployeeQuery = "insert into employee_login (loginid,password_hash,user_created_date,"
            + "email) values (?,?,?,?);";
    try (Connection conn = Database.getConnection(env);
            PreparedStatement pstmt = conn.prepareStatement(addEmployeeQuery);) {

        if (conn != null) {
            pstmt.setInt(1, loginModel.getUserid());
            pstmt.setString(2, EmployeeHelper.getHashFromPassword(loginModel.getPassword_hash()));
            pstmt.setTimestamp(3, new java.sql.Timestamp(System.currentTimeMillis()));
            pstmt.setString(4, loginModel.getEmail());
            int rows = pstmt.executeUpdate();
            if (rows > 0)
                registered = true;
        }
    } catch (SQLException | NoSuchAlgorithmException e) {
        LOGGER.error("Error while adding user [{}] with error [{}]", loginModel.toString(), e);

    }
    return registered;
}

Is this the right way or can there be another way which is neat and clean?

There is another much simpler clean way.

Use ControllerAdvice and throw error from Service Layer itself. Build your common error response there. Yeah it is global exception handling.


A simple math torture game Introduction.

It is commonly known that the worst form of torture is performing monotonous tasks ad nauseam. So I constructed this simple game I can give to my students when they misbehave.

Task.

The goal was to make a problem that could take in two numbers, and construct n distinct multiplication problems where the user is asked to answer what x * y is.

Challenge.

Where I struggled was with the part in cursive. How do I write a clear and readable code that produces distinct multiplication problems? I tried to do it with creating a sample of distinct numbers X, and then choose y such that y ≤ x where x is a member of X. Unsure if this is the best idea.

The code and some comments

I choose to do import random instead of importing the modules as it is a bit clearer where the modules comes from
As above, choose to include a short ___docstring___ more out of habit than necessity I guess..
As mentioned above, do not really like my method for forcing the questions to be distinct.
Tried to comply with pep8 for the long strings, looks a bit strange.

Here is the code

import random

QUESTIONS = 5
MIN_VAL = 2
MAX_VAL = 12

def arithmetic_game(val_1=MIN_VAL,
                    val_2=MAX_VAL,
                    num_of_problem=QUESTIONS):
    """ Ask the user a series of arithmetic questions
    and returns the number of correct answers.

    Args: val_1 (int): Defines the range of multiplication
    Args: val_2 (int): Defines the range of multiplication
    Args: number_of_problems (int): Defines the number of questions

    Return: correct_answers (int): number of correct math questions answered"""

    correct_answers = 0

    num_lst = random.sample(
            range(min(val_1, val_2), max(val_2, val_2)+1),
            num_of_problem)

    for num_1 in num_lst:
        num_2 = random.randint(2, num_1)
        print('\nWhat is {:d} times {:d}?'
              ''.format(num_1, num_2))
        answer = num_1*num_2

        try:
            if int(input()) == answer:
                print('Yes, the answer is {:d}'
                      ''.format(answer))
                correct_answers += 1
            else:
                print('No, the correct answer was {:d}'
                      ''.format(answer))
        except NameError:
            raise ValueError('I am sorry, you have'
                             'to write in a valid integer')

    return correct_answers

if __name__ == "__main__":

    correct_answers = arithmetic_game()
    print('\nYou got {:d} out of {:d} answers correct'
          ''.format(correct_answers, QUESTIONS))

I think you meant to write max(val_1, val_2) instead of max(val_2, val_2).

Long Strings

I personally think the PEP8's 79 characters-per-line requirement is too strict and is not practically optimal. Increase it to, for instance, 100 for this code snippet and you'll get a more readable and concise code with all of the used strings fitting on a single line.

Other Improvements

I would apply an "Extract Variable" refactoring method and define a tuple of report template strings, which would allow to bring the nestedness 1 level down:

is_answer_correct = int(input()) == answer
print(ANSWER_TEMPLATES[is_answer_correct].format(answer))
correct_answers += is_answer_correct

where ANSWER_TEMPLATES is defined as:

ANSWER_TEMPLATES = (
    'No, the correct answer was {:d}',
    'Yes, the answer is {:d}'
)

As far as generating unique random pairs for the problem, there is also this approach involving keeping track of seen pairs and keeping generating a next pair until it has not been seen.

I think you need more functions. One to produce the random numbers, and one to get user input.
Personally I'd make your random number generator return all the numbers! This is as you can easily either slice the result, [:], or itertools.islice the result.
Follow PEP8 and don't be a hobgoblin. I'm always surprised when I remember that '{}' ''.format is allowed in Python, and format will act on the first string literal as well as the second.
I'd make a habit of keeping your try blocks as small as needed. This is so that you don't mask bugs. Whilst I don't think you'll be masking any here, it's a good habit to make. And so you could use else, or make only the small try except loop infinitely, so the user doesn't loose points for accidentally pressing a letter with a number.
I'm not sold by your need for the global constants. I'd make them 'magic literals'. However since they're mostly only used as default arguments, I personally wouldn't call them magic.
I'm not sold by val_1 and val_2, maybe minimum and maximum would be better? Python will also say they are the names when you go to use the function, and so will make more sense what is expected.

On the all, this is pretty small and I prefer your 'verbose' method of printing and more specifically adding to correct_answers than alecxe's. And so with the above minor changes I'd use something like:

import random
import itertools

QUESTIONS = 5
MIN_VAL = 2
MAX_VAL = 12

def generate_random_numbers(sample):
    sample = list(sample)
    for x in random.sample(sample, len(sample)):
        for y in random.sample(sample, len(sample)):
            yield (x, y)

def get_int_from_user():
    while True:
        try:
            return int(input())
        except NameError:
            raise ValueError('I am sorry, you have to write in a valid integer')

def arithmetic_game(val_1=MIN_VAL,
                    val_2=MAX_VAL,
                    num_of_problem=QUESTIONS):
    """
    Ask the user a series of arithmetic questions
    and returns the number of correct answers.

    Args: val_1 (int): Defines the range of multiplication
    Args: val_2 (int): Defines the range of multiplication
    Args: number_of_problems (int): Defines the number of questions

    Return: correct_answers (int): number of correct math questions answered
    """

    correct_answers = 0

    sample = range(min(val_1, val_2), max(val_1, val_2)+1)
    random_numbers = generate_random_numbers(sample, amount)
    random_numbers = itertools.islice(random_numbers, num_of_problem)

    for num_1, num_2 in num_lst:
        print('\nWhat is {:d} times {:d}?'.format(num_1, num_2))
        answer = num_1 * num_2
        if get_int_from_user() == answer:
            print('Yes, the answer is {:d}'.format(answer))
            correct_answers += 1
        else:
            print('No, the correct answer was {:d}'.format(answer))

    return correct_answers

if __name__ == "__main__":

    correct_answers = arithmetic_game()
    print('\nYou got {:d} out of {:d} answers correct'
          ''.format(correct_answers, QUESTIONS))


Find all combinations of a number sequence which is first increasing then decreasing Given an integer N(Natural Number), A program/Algorithm to find the
  remainder of arrangements that can be obtained by rearranging the
  numbers 1, 2, ...., N.

  Input Format: One line containing the integer N

  Output Format: An integer m, giving the remainder of the number of
  arrangements that could be obtained from 1, 2, ...., N is divide
  by Mod

  Constraints:
  Mod = 10^9+7
  N ≤ 10^9

  Example 1 Input
  3  Output
  2  Explanation: Consider the first three natural numbers 1, 2, 3. These can be arranged in the following ways: 2, 3, 1 and 1,
  3, 2. In both of these arrangements, the numbers increase to a certain
  point and then decrease. There are two such arrangements: 2, 3, 1 and
  1, 3, 2.

  Example 2

  Input
  4  Output
  6  Explanation: The six arrangements are (1, 2, 4, 3), (1,3,4,2), (1,4,3,2), (2,3,4,1), (2,4,3,1), (3,4,2,1).

#include<stdio.h>
#include<stdlib.h>
#define m 1000000007

unsigned long long int power(unsigned long long int x, unsigned long long int n){

    unsigned long long int res = 1;
    while(n > 0){
        if(n & 1){
            res = res * x;
            res = res%m;
        }
        x = x * x;
        x= x%m;
        n >>= 1;
    }
    return res;

}

int main(){

    unsigned long long int n,res=0,temp=1,i;
    scanf("%llu", &n);
    if(n==1 || n==0){
        printf("0\n");
        return 0;
    }
    temp = power(2, n-1);
    temp--;
    temp--;
    printf("%llu\n", temp);

    return 0;
}

Can Anyone Solve This with Better Time Complexity?

Bug

Input : 500000003
Output: 18446744073709551615

The problem is that the result of your power() call could be 0 or 1.  Then when you subtract 2, you get a negative number.  Given the input constaint of \$n ≤ 10^9\$, 500000003 is the only bad input, but in general this happens when n is any multiple of 500000003.  To correct this, you could change this:

temp--;
temp--;

to:

temp = (temp + m - 2) % m;

This ensures that temp will remain positive.  Time complexity wise, your program is great at \$O(\log n)\$.


Checking whether a string contains a substring only once I want to check if a string contains only a single occurrence of the given substring (so the result of containsOnce("foo-and-boo", "oo") should be false). In Java, a simple and straightforward implementation would be either

boolean containsOnce(final String s, final CharSequence substring) {
    final String substring0 = substring.toString();
    final int i = s.indexOf(substring0);
    return i != -1 && i == s.lastIndexOf(substring0);
}

or

boolean containsOnce(final String s, final CharSequence substring) {
        final String substring0 = substring.toString();
        final int i = s.indexOf(substring0);
        if (i == -1) {
            return false;
        }

        final int nextIndexOf = s.indexOf(substring0, i + 1);
        return nextIndexOf == 0 || nextIndexOf == -1; // nextIndexOf is 0 if both arguments are empty strings.
}

Can you suggest a simpler/more efficient implementation?

Perhaps using pattern matching. It looks more readable to me, but I have no idea about which is more efficient.

public static boolean containsOnce(final String s, final CharSequence substring) {
    Pattern pattern = Pattern.compile(substring.toString());
    Matcher matcher = pattern.matcher(s);
    if(matcher.find()){
        return !matcher.find();
    }
    return false;
}

public static void main(String[] args) throws Exception {
    System.out.println(containsOnce("aba","a"));    //false
    System.out.println(containsOnce("abab", "ab")); //false
    System.out.println(containsOnce("aba", "b"));   //true
    System.out.println(containsOnce("aaa", "aa"));  //true
    System.out.println(containsOnce("",""));        //true
    System.out.println(containsOnce("ab",""));      //false
}

Also note that containsOnce("aaa","aa") returns true. Not sure if you would count this as correct or not.

Note: you can also write it as

Pattern pattern = Pattern.compile(substring.toString());
Matcher matcher = pattern.matcher(s);
return matcher.find() && !matcher.find();

I don't know which of the two is more readable.

EDIT:

After looking up whichever is faster: indexof vs matcher
It seems to be the general consensus that indexof is a bit faster, but that we're talking about such low times that it really doesn't matter much.

Go for whichever solution you prefer I guess ...

In terms of efficiency, the substring.toString() is the showstopper as soon as substring is not a java.lang.String. The rest of the code looks fine.

The documentation of the method should include containsOnce("fooo", "oo") as an example for returning false, since that might be a non-obvious corner case.


Python program to take in two strings and print the larger string I have written a Python program to take in two strings and print the larger of the two strings.

Here is my code -

string1 = input("Enter first string: ")
string2 = input("Enter second string: ")
count1 = 0
count2 = 0
for i in string1:
      count1 = count1 + 1

for j in string2:
      count2 = count2 + 1

if (count1 < count2):
      print ("Larger string is:")
      print (string2)

elif (count1 == count2):
      print ("Both strings are equal.")
else:
      print ("Larger string is:")
      print (string1)

Here are some example outputs -

Enter first string: everything
Enter second string: nothing
Larger string is:
everything

Enter first string: cat
Enter second string: apple
Larger string is:
apple

I feel that my code is unnecessarily long. Therefore, I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.

Python strings supports Python built-in len function. You don't need to iterate through them manually, as for lists/dicts/sets etc (it is not Pythonic):

def compare_strings_len(s1, s2):
    if len(s1) > len(s2):
        print('String 1 is longer: ', s1)
    elif len(s1) < len(s2):
        print('String 2 is longer: ', s2)
    else:
        print('Strings length are equal!')

You can immediately assume that the first one is larger and then reassign it to the second one if that one is larger, like this:

larger = input("Enter first string: ")
string2 = input("Enter second string: ")
if (len(string2) > len(larger)):
    larger = string2
print(larger)


PHP/MySQL to delete data from 4 different tables at once I have four mysql tables setup like the following:

users (userid, firstname, lastname)  *one entry per user
schedules (userid, scheduleid, schedulename) *each user could have multiple schedules
classes (classid, scheduleid, classname) *each schedule is made up of multiple classes
schools (scheduleid, schoolid, schoolname) *one entry per user

I want the user to be able to delete their account, including ANY info from other tables tied to their account. So if they had 3 schedules with a bunch of classes in each and a school tied to each schedule, I'd want ALL of that data (including their user info) to be deleted in one fell swoop.

userid is all I need to delete from the users and schedules table easily.  But the classes and schools tables DON'T have a userid field, so I have to do some other way.

I wrote and tested the following code and it works fine...

//first get all schedules associated with this user account and put scheduleids into array
$sql = "SELECT scheduleid FROM schedules
        WHERE userid = '$userid'";
        $selectschedules = mysqli_query($connection, $sql);
        if (!$selectschedules) {
        die("Database query failed: " . mysqli_error());
        } else {
            while($data=mysqli_fetch_assoc($selectschedules)){
                 $schedules[] = $data;
            }
        }
//now loop through each schedule to delete all classes and any school associated with that particular schedule
foreach ($schedules as $item) {
    $sql = "DELETE FROM classes
            WHERE scheduleid = '".$item['scheduleid']."'";
            $deleteclasses = mysqli_query($connection, $sql);
            if (!$deleteclasses) {
            die("Database query failed: " . mysqli_error());
            } else {
            }
    $sql = "DELETE FROM schools
            WHERE scheduleid = '".$item['scheduleid']."'";
            $deleteschool = mysqli_query($connection, $sql);
            if (!$deleteschool) {
            die("Database query failed: " . mysqli_error());
            } else {
            }
}
//next delete all schedules associated with user account
$sql = "DELETE FROM schedules
        WHERE userid = '$userid'";
        $deleteschedules = mysqli_query($connection, $sql);
        if (!$deleteschedules) {
        die("Database query failed: " . mysqli_error());
        } else {
        }
//finally, delete the user's account
$sql = "DELETE FROM users
        WHERE userid = '$userid'
        LIMIT 1"; //should only be one, just being safe
        $deleteuser = mysqli_query($connection, $sql);
        if (!$deleteuser) {
        die("Database query failed: " . mysqli_error());
        } else {
        }

However, I believe the above code is inefficient (particularly looping through each schedule and doing delete queries on every loop). So I'm curious if there is a shorter/more efficient way to accomplish this same thing.  I am not good with JOINS and could be wrong, but would using JOINS potentially be the key to shortening this and NOT having to loop at all?

SIDE NOTE: Earlier I mentioned that classes and schools tables DON'T have a userid field.  If they did, it would be very easy to delete all of this stuff in one query. So it begs the question:  Should I add the userid field to the other tables?  I don't want to add it just to make deleting easier, but if you think it SHOULD have it regardless, then I would consider.

Any info/suggestions would be greatly appreciated.

Basically there are three vectors of improvement:

of course you can make your queries optimal, avoiding a loop
also, I would suggest to optimize the the process of executing the query, as it is evident that each query takes too much code to write
you should never put a single variable directly in the query, but always use a prepared statement instead.

To solve the first problem, you can always use a JOIN. Yes, DELETE queries support JOINs as well as SELECT ones. So it goes:

DELETE c.* FROM classes c, schedules s WHERE c.scheduleid=s.id AND s.userid = ?

To solve the second one would propose to use PDO (which can solve the third one as well) as it lets you to run a query in one line:

$pdo->prepare("DELETE FROM users WHERE userid = ?")->execute([$userid]);

So the overall code would be

$sql = "DELETE c.* FROM classes c, schedules s WHERE c.scheduleid=s.scheduleid AND s.userid = ?";
$pdo->prepare($sql)->execute([$userid]);

$sql = "DELETE c.* FROM schools sc, schedules s WHERE sc.scheduleid=s.scheduleid AND s.userid = ?";
$pdo->prepare($sql)->execute([$userid]);

$sql = "DELETE FROM schedules WHERE s.userid = ?";
$pdo->prepare($sql)->execute([$userid]);

$sql = "DELETE FROM users WHERE s.userid = ?";
$pdo->prepare($sql)->execute([$userid]);

As long as you are connecting to PDO properly, this code will report errors automatically, without a single extra line of code!

  Should I add the userid field to the other tables?

Quite contrary, you should NOT add such a field, keeping your database structure as normalized as possible

As we know if want to delete data from referenced table if we delete data from the parent table so for this we use the MySQL cascade feature.
We use MySQL ON DELETE cascade in this case. Just take an example if I have two tables.
1- Parent
2- Child
and I want to delete referenced data automatically from the child table if I delete data from the parent table. So for this, we use ON DELETE cascade on child table foreign key.
See a complete example using the below link
https://www.javadream.in/mysql-cascade-on-delete-and-on-update-cascade-example/


Counting pairs of relatively prime numbers Problem from Hacker Earth:

  Inverted GCD:

  Given an array a of \$N\$ numbers , you have to find the number of pair of indices \$i\$ and \$j\$ that satisfy the following relation:

  \$i < j\$
  \$a_i > a_j\$
  gcd\$(a_i , a_j) = 1\$

  Input:

  The first line of the input contains a single integer N - denoting the size of the array.
  The next line contains N space separated integers denoting the array a.

  Output:
  Output a single integer - the answer to the problem stated above.

  Constraints:
  \$1 \le N \le 10^5\$
  \$1 \le a_i \le 10^5\$

For this problem I've submitted the following solution in Python:

from fractions import gcd
n = int(input())
count = 0;
a = [int(x) for x in input().split()]
for i in range(n):
    for j in range(n):
        if(a[i]>a[j] and i<j and gcd(a[i] , a[j]) == 1):
            count +=1;
print(count)

I'm not sure what is the complexity of gcd() function in Python, but it clear due to two for loop that the time complexity is minimum \$O(n^2)\$.I can't understand how to reduce it. Because here we have to check these conditions between every pair of integers. I've seen such question here but there is no condition for gcd(), so can't relate these two questions. I'm newbie to Python.

tl;dr TLE beyond input size 40000 to 50000 (10 seconds for input size 100000)

Conditions (1) and (2) are transitive but independent and one-sided. This means they can only prune half of all candidates on average each, and so their combination only reduces the average candidate set to one fourth (i.e. half of a half). Such a small constant factor is not worth it to invest in (as in 'devising a special data structure'), unless overall performance is already close to a passing grade. Asymptotic performance doesn't change at all, of course. Hence it is best to take the doubling in performance that comes from index pruning (condition (2), which is essentially free) and test condition (1) as pairs are processed.

Condition (3) induces a squarish relation all on its own already, and it is not transitive. This means that there is no efficiency gain from precomputing this relation, and memoisation is likely to be completely ineffective in the face of random inputs.

The evaluation of the GCD for a pair of numbers takes time logarithmic in the smaller of the two inputs. This time can be cut by a considerable constant factor with a bit of precomputation, by computing integer-sized 'bit vectors' representing the presence of a handful of the smallest primes in the (radical) factorisation of a number.

This way a simple binary AND can prove the absence of shared small factors and thus avoid the computation of the actual GCD in about 89% of all cases (assuming factorisation by the first 32 primes, i.e. up to 131). In the remaining 11%, only the factorisation 'remainders' need to be GCDed, i.e. what remains after dividing out the small factors/radicals represented by the bit vectors. This saves some iterations of Euclid's algorithm.

This can give you an overall speed boost of an order of magnitude or more. On top of the factor 2 speed gain from index pruning mentioned by coderodde and some general efficiency tuning this might just be enough to beat the time limit...

Note: one might be tempted to extend the 'bit vectors' from 32 bits to 64 bits to utilise the bigger machine words on 64-bit machines, but this is not worth it. It doubles the up-front factorisation effort but it improves the rejection rate only from 88.7% to 90.3%, i.e. by a completely negligible 1.8%.

Here's a small table with the pass/reject rates for bit masks involving the given number of the first primes:

 8 primes: pass 17,102%, rej. 82,898%                 # up to 4 extra radicals
12 primes: pass 14,872%, rej. 85,128% // boost 2,690% # up to 3 extra radicals
16 primes: pass 13,609%, rej. 86,391% // boost 1.484%
32 primes: pass 11,300%, rej. 88,700% // boost 2,673%
64 primes: pass  9,683%, rej. 90,317% // boost 1,823% # up to 1 extra radical

The 'up to X extra radicals' bit says how many different prime factors can remain in the factorisations of numbers not exceeding 100,000 after the the given number of the first small primes has been factored out.

P.S.: the bounds on the number of numbers is the same as the bound on the size of the numbers, which means that the factorisations can be pre-computed wholesale without any divisions (by borrowing the logic behind the Sieve of Eratosthenes). The partial factoring for the bit vectors takes less than a millisecond, and factoring the input remainders takes less than 10 milliseconds for 100,000 inputs. Hence the stuff can always be computed wholesale and it isn't even worth it to have different code paths for small and big input batches.

--- UPDATE ---

For getting a better handle on the problem I needed a closer fix on some numbers, and so I coded things up in C++. It turned out that computing the gcd of the remainders (after factoring out the small primes used in the 'bit vectors') is orders of magnitude too slow, even though it occurs only for 0.35% of all candidates. This necessitated replacing the partial factorisation remainders with lists of the (up to two) remaining radicals.

'Radical' Optimisation

For numbers less than 107113 = 43 * 47 * 53, factoring out the 13 smallest primes leaves at most two distinct prime factors ('radicals'). Moreover, only factors up to half the limit need be considered since the only numbers with bigger prime factors are the primes, which are coprime to all numbers but themselves and self-pairings get excluded via criteria (1) and (2) both. This means that 2 x 16 bits = 32 bits are sufficient for storing the 'list' of remaining radicals for a number.

This size reduction is beneficial for L1 cache utilisation and it would allow to stuff both radicals into a single 32-bit integer; however, it collides with an important optimisation of the intersection operation. This optimisation is the reduction of branchings to the absolute minimum of two to three comparisons, by always treating the two-element lists as full and by replacing all but one of the remaining non-comparison branches with arithmetic (poor man's CMOV). This makes things easier for the CPU's branch prediction logic and reduces the amount of incurred branch mis-prediction penalties, but it requires the use of sentinel values for 'missing' radicals. With the only safe sentinel for a number a[i] being a[i] itself this means that the slots for the radicals must be able to hold full-sized numbers.

Elimination of one particularly nasty branch required adding a third radical slot (which always holds a sentinel value) but it resulted in a speedup of 10%. Without this explanation it might seem odd that the code uses three slots even though there can be at most two radicals. First, the data:

uint16_t sieve[1 + LIMIT];  // bit masks of partial factorisations of 1 .. LIMIT
uint16_t v[1 + LIMIT];      // v[i] = sieve[a[i]]
uint32_t f[1 + LIMIT][3];   // remaining factors (radicals) for each input (3rd is sentinel)
uint8_t skip[1 + LIMIT];    // for each a[j]: how many successors are not less

The code for generating these tables is elementary and of little interest here (especially as it takes less than 10 milliseconds even in C#). Hence I'm skipping it in the interest of brevity. Here is the meat of the code, the function that does the counting as specified by the task:

uint64_t count_matches (uint32_t const a[], uint32_t count)
{
    uint64_t result = 0;

    prepare_tables(a, count);

    for (uint32_t i = 0; i < count; ++i)
    {
        uint32_t a_i = a[i];
        unsigned v_i = v[i];

        for (uint32_t j = i + 1; j < count; ++j)
        {
            if ((v_i & v[j]) == 0)
            {
                if (a_i > a[j])
                {
                    if (uint32_t d = f[i][0] - f[j][0])
                    {
                        uint32_t di = (d >> 31) & 1;
                        uint32_t ci = di;
                        uint32_t cj = di ^ 1;

                        if ((d = f[i][ci] - f[j][cj]) != 0)
                        {
                            di = (d >> 31) & 1;
                            ci += di;
                            cj += di ^ 1;

                            if ((d = f[i][ci] - f[j][cj]) != 0)
                                ++result;
                        }
                    }
                }
                else j += skip[j];
            }
        }
    }

    return result;
}

On my laptop this clocks a bit less than 19 seconds for random inputs of size 100,000, compared to 22 seconds for a 'branchy' version of the intersection test (which has no use for the third slot):

                    int32_t d = int32_t(f[i][0] - f[j][0]);

                    if (d > 0)
                    {
                        d = int32_t(f[i][0] - f[j][1]);

                        result += d > 0 || d && f[i][1] != f[j][1];
                    }
                    else if (d != 0)
                    {
                        d = int32_t(f[i][1] - f[j][0]);

                        result += d < 0 || d && f[i][1] != f[j][1];
                    }

Of course, in Python the optimisation is bound to get killed by the interpreter overhead, because the code contains a lot of explicit little operations instead of pushing processing into the engine. But in any case it should be beneficial to utilise the fact the 'radical factor set intersection' involves only lists of at most two elements here instead of general sets.

Skip Counts

The skip count thing hasn't been mentioned yet - it's a small optimisation that costs virtually nothing and improves speed by about 10%. It utilises the fact that a[i] <= a[j] && a[j] <= a[j + k] implies a[i] <= a[j + k], and storing/precomputing this is cheap because it involves only a[j] and its context in the input sequence instead of depending on pairings of a[i] and a[j].

Half of all skip counts are 0, of course, and half of the rest is 1. The rest peters off quickly because the probability of a skip count having value k is 1 / ((k+1)*(k+2)), which means that skip counts of four bits or so already realise most of the performance gain that can be gotten this way.

Four bits would probably be optimum if one wanted to stuff several different values - like input number, small factor bit vector and skip count - into a single integer-sized variable, especially in languages where array indexings carry a heavy cost (Python, Java, C#). In my sample code I used a separate array for simplicity, and hence allocated one whole byte for each skip count.

Numbers and Summary

The reason I sat down and got coding was that I wanted to get a fix on some numbers, in order to get a better handle on the problem and a better feeling for the lay of the land. Here are those numbers.

For a random input vector of 100,000 numbers - the limit given in the task description - and enumerating only the 4,999,950,000 pairs of numbers with i < j, it took the following amounts of time to count the following things:

11.0 s for 2512386875 inversions
21.5 s for 3029211382 coprime pairs
17.3 s for 1527936260 candidates (a[i] > a[j] and no common factors among the first 16 primes)
15.7 s for 1527936260 candidates (dito, with byte-sized skip counts)
85.7 s for 1522549277 matches (with gcd applied to remainders)
18.6 s for 1522549277 matches (with list intersection for remainder radicals)

The most important message here is that the number of inversions (i.e. criterion (2) in the task description), the number of coprime pairs (criterion (3)) and the number of results to be counted are all the same order of magnitude as the number of pairs with i < j. The percentages are 50.2%, 60.6% and 30.5% respectively.

Also, just counting the number of inversions takes more than five times as long as the two seconds admissible as per the task description, even though my laptop is likely quite a bit faster than the hardware used by the robot judge.

Even if I found some fiendishly clever algorithm or data structure which can prune everything that doesn't fulfil the task conditions then the time would still be 30.5% * 19 s which is about 6 seconds. In other words, on a maximum input file the code would still take three times as long as the time limit.

For comparison, counting the matches for a vector of 1000 random inputs - as per coderodde's 'lightened' specification - takes less than 2 milliseconds with this code. I'd hate to think how long coderodde's solution would take on a maximum input file as per the actual task description; extrapolation from the given results puts it at more than half an hour.

In the first two paragraphs of this post I argumented why the intersection of the task criteria must leave a number of pairings that is still square in the number of inputs; now we know that the actual number is about 30% of 'j-pruned' pairs or 15% of all input pairs. Moreover, the C++ timings suggest that counting each result pair individually is simply not an option, since the optimisation potential that's still left is far less than an order of magnitude (which is why I didn't bother to create an optimised version).

Any admissible solution must count whole swathes of pairs in one go instead of processing each pair individually, but at the moment I cannot offer any specific advice as to how one might accomplish that. One seedling of an idea might lie in the fact that any prime must a priori be coprime to any input number other than itself, so that only criteria (1) and (2) need be applied for counting it. Similar considerations apply to sets of input numbers that have disjoint sets of prime factors.

I took a peek at the submission table at HackerEarth, and the only successful submissions I could see were in C++ with timings between 3.3 seconds and 12 seconds, with codes sizes ranging from 10KB to several hundred KB. This suggests that real solutions might be quite involved, compared to the simple code that has been discussed in this topic so far. I did not look at any of the code, however, because I intend to have a stab at the problem myself first...

UPDATE #2

250,000,000 factor set intersections per second

For an input vector of 10^5 values the current algorithm has to filter 0.5 * (10^5)^2 pairs of numbers - that's about 5 billion (American-style). Performance can be roughly doubled by looking only at inversions and by removing all branches but one from the set intersection code.

The standard algorithm for inversion counting by merge sorting divides the input into non-inverted and inverted runs and tallies the latter:

long count_inversions_m1 (List<int> values)
{
    long inversions = 0;
    int n = values.Count;
    var a = values.ToArray();
    var b = new int[n];

    for (int w = 1; w < n; w <<= 1)
    {
        for (int beg = 0; beg < n; beg += w + w)
        {
            int mid = Math.Min(beg + w, n);
            int end = Math.Min(mid + w, n);

            for (int i = beg, j = mid, k = beg; k < end; ++k)
            {
                if (i < mid && (j >= end || a[i] <= a[j]))
                {
                    b[k] = a[i++];
                }
                else // a[k] > a[j] for all k in [i .. mid - 1]
                {
                    inversions += mid - i;
                    b[k] = a[j++];
                }
            }
        }

        var t = a;
        a = b;
        b = t;
    }

    return inversions;
}

In the a[i] > a[j] branch, the run from a[i] to a[mid - 1] is inverted with respect to a[j]; all inversions in the input pass that branch eventually. Replacing the line

 inversions += mid - i;

with a small loop that performs factor set intersection on the values involved gives an algorithm that is a tad faster than the earlier one, because it never has to look at any non-inverted pairs. Simply dropping the intersection code from the earlier version in there would work, but it can be made faster by using branch-less comparison.

That is, instead of branching based on the result of comparing factors, a value is computed that is 0 if the two lists of non-bitmapped prime factors (at most two elements each) have some value in common, and 1 if they do not. I chose to abuse the fact that, given a pair of unequal values a and b, either a - b or b - a must be negative but no difference is negative if the values are equal. Hence the high bit of (a - b) | (b - a) is 1 if the values are different, and 0 if they are equal (as long as the difference does not exceed INT32_MAX).

A further speedup comes from ‘compressing’ factors down to 16 bits. This is possible because the factors are only ever compared for equality, and any unique mapping of values will do just as well for that. There are only 9592 primes up to 100000, and so there are many viable schemes for assigning each prime a unique 16-bit proxy value. I chose p < UINT_MAX ? p : (ushort)(p + 3) for simplicity. This ‘compression’ from 32 bits to 16 bits leads to better cache utilisation and reduces register pressure for 32-bit architectures (since a whole pair fits into a single machine word).

Here's the final set intersection code, ready for replacing the inversion branch in the above procedure (C++ version shown, but the C# is similar):

uint32_t a_j = b[k] = a[j++];                // x 815,024
unsigned f_j = factor_bits[a_j];
unsigned bj0 = big_factors[a_j][0];
unsigned bj1 = big_factors[a_j][1];

for (uint32_t l = i; l < mid; ++l)
{
    uint32_t a_i = a[l];                     // x 2,512,386,875

    if ((f_j & factor_bits[a_i]) == 0)
    {
        unsigned bi0 = big_factors[a_i][0];  // x 1,527,936,260
        unsigned di0 = ((bi0 - bj0) | (bj0 - bi0)) & ((bi0 - bj1) | (bj1 - bi0));
        unsigned bi1 = big_factors[a_i][1];
        unsigned di1 = ((bi1 - bj0) | (bj0 - bi1)) & ((bi1 - bj1) | (bj1 - bi1));

        result += (di0 & di1) >> 31;         // 1,522,549,277 x 1 vs 5,386,983 x 0
    }
}

The 16-bit factor bitmaps are kept in a separate array to improve cache efficiency, because the bitmap AND must occur for every inversion pair whereas comparison of the up to two extra factors occurs less often. I've annotated some code lines with execution counts for an input of 100,000 random values, to put things a bit into perspective.

The resulting code comes closer to the goal, but not close enough. The C++ version still needs 10 seconds for a maximum-size (non-degenerate) input, and for the C# edition it's 12.5 seconds. I submitted the C# but, as expected, it failed all (non-degenerate) test cases where the input size exceeded 40,000 significantly. The performance target seems almost within reach, but it seems hopeless to try squeezing another five-fold performance increase out of the current approach.

I've chosen to complete the write-up despite the failure because some of the techniques may be useful for other challenges. Thanks to Kaushal28 for bringing this neat problem to our attention - I had a lot of fun trying to solve it and I learnt a lot along the way.

i think the second for loop is unnecessary.

from fractions import gcd
n = int(input())
count = 0;
a = [int(x) for x in input().split()]
for i in range(n - 1 ):
    j = i + 1
    if(a[i]>a[j] and gcd(a[i] , a[j]) == 1):
            count +=1;
print(count)


Find a value between two of the same characters in a string using Python I am attempting to make a python script that imports a given file.

Then on the import of the file, I am pulling a value from in the filename to determine what function to run.

I will then eventually extend this to pull all files from a folder rather than explicitly pass it a specific file.

The format of the file names is always the following:

blah_Value_blah.extension

I am wondering if there is a better and more efficient way to pull Value from the above example than what I have given below?

Here is my code:

from os.path import splitext, basename

under = '_'

base = basename(splitext(filename_goes_here)[0])
value = base[base.find(under)+len(under):base.rfind(under)]

I am aware I can merge my two lines of code above into one line but it would be very unsightly.

Examples of the filenames are:

//path/to/file/GAME_team_2017.csv
//path/to/file/GAME_player_2017.csv
//path/to/file/GAME_rules_2017.csv

The sample output of the above files would be:

'team'
'player'
'rules'

Rather than using str.find, you could better describe yourself using regex. However it's not that much of an improvement.

For example using the regex _(.+)_ on the basename of the file is all you need. If you think a file extension is going to have an _ then you may need the splitext.

This can get:

from os.path import splitext, basename
from re import search

base = basename(splitext(filename_goes_here)[0])
value = search('_(.+)_', base)
if value is not None:
    value = value.group(1)

If you're using Python 3.6, as noted in the comments by 200_success, you could change the last line to:

value = value[0]

can adapt from here, just adjust your regex

import os
import re

def key(filename):
   # extract category from filename
    pattern = '(\s|\_)\d{4}.*'  # space/underscore & 4 digit date &  the rest
    return re.sub(pattern, '', os.path.basename(filename))


Calculating which direction my enemy should face when moving I have just implemented an algorithm which calculates the direction an enemy in my game should face when moving to a location.

This is a 2D game where characters can face in one of four directions: (Up, Down, Left, Right).

When navigating to a point, if the new point is further away on the X axis than the Y axis, the enemy should show it's left or right animation.  However, if the movement would take the enemy more along the Y axis than the X axis, the enemy should show it's up or down animations.

To put it visually, the center of the X in the following image illustrates the position of my enemy on an coordinate plane.  Depending on which quadrant his movement point is placed in, the respective animation for that quadrant should be shown.

Here is my implementation.  My questions are:

Does this algorithm accomplish what I am thinking it does? From watching it on my enemy, it looks good so far, however I could just be getting lucky!
Can this algorithm be improved in any way?

protected FacingDirections CalculateFacingDirection(Vector2 navPos)
{
    Vector2 curPos = transform.position;

    float xDiff = Mathf.Abs(navPos.x - curPos.x);
    float yDiff = Mathf.Abs(navPos.y - curPos.y);

    if(navPos.x > curPos.x) //we are moving left
    {
        if(navPos.y > curPos.y) //we are moving up
        {
            return xDiff > yDiff ? FacingDirections.Left : FacingDirections.Up; //are we moving more left or up?
        }

        return xDiff > yDiff ? FacingDirections.Left : FacingDirections.Down; //are we moving more left or down?
    }
    else //we are moving right
    {
        if (navPos.y > curPos.y) //we are moving up
        {
            return xDiff > yDiff ? FacingDirections.Right : FacingDirections.Up; //are we moving more left or up?
        }

        return xDiff > yDiff ? FacingDirections.Right : FacingDirections.Down; //are we moving more left or down?
    }
}

In my opinion you should first get the axis of the maximum direction via comparison of xDiff with yDiff:

protected FacingDirections CalculateFacingDirection(Vector2 navPos)
{
    Vector2 curPos = transform.position;

    float xDiff = Mathf.Abs(navPos.x - curPos.x);
    float yDiff = Mathf.Abs(navPos.y - curPos.y);

    if (xDiff > yDiff) // we are moving more along X axis
    {
        return navPos.x > curPos.x ? FacingDirections.Left : FacingDirections.Right;
    }
    // we are moving more along Y axis
    return navPos.y > curPos.y ? FacingDirections.Up : FacingDirections.Down;
}

Additional: remove comments and try to explain your code using variables or code logic:

float xDiff = Mathf.Abs(navPos.x - curPos.x);
float yDiff = Mathf.Abs(navPos.y - curPos.y);
bool movingRight = navPos.x > curPos.x;
bool movingUp = navPos.y > curPos.y;

if(xDiff>yDiff)
{
  return movingRight ? FacingDirections.Left :  FacingDirections.Right;
}
else
{
  return movingUp ? FacingDirections.Up :  FacingDirections.Down;
}


Convert seconds to hours/minutes/seconds and pretty print I'm self taught in python 3, and I frequently keep track of how long my scripts have been running using the time library.

import time
startTime = time.time()

#The main body of script...

print('The script finished in {0} seconds'.format(time.time() - startTime)

However this can be unhelpful if the script has been running for some time, an example output being:

'The script has been running for 4323.580279111862 seconds'

I wrote a function which takes a float variable and prints the time in a more readable way. I convert the seconds to integer to get rid of the 12 decimal places, and I can pass a boolean value which changes the wording of the print to indicate that the script is still running or has finished.

def printRuntime(seconds,finished=False):
    seconds = int(seconds)
    status = 'has been running for'
    if finished == True:
        status = 'finished in'

    if seconds < 60:
        print('The script {} {} seconds'.format(status,seconds))
        return
    elif seconds < 3600:
        minutes = seconds // 60
        seconds = seconds - 60*minutes
        print('The script {} {} minutes & {} seconds'.format(status,minutes,seconds))
        return
    else:
        hours = seconds // 3600
        minutes = (seconds - 3600*hours) // 60
        seconds = seconds - 3600*hours - 60*minutes
        print('The script {} {} hours, {} minutes & {} seconds'.format(status,hours,minutes,seconds))
        return

import time
startTime = time.time()

#The main body of script...

printRuntime(time.time() - startTime)

Since I'm self taught I have no real idea about best practice. I feel like there must be a more concise way of doing this, what mistakes am I making?

There is a built-in timeit module which is quite convenient for measuring execution times, but, if we were to improve this particular solution, I would switch to using divmod as suggested by Brandon here, utilize short if/else version for the status definition and join the time value parts with a comma filtering non-zero values only.

Something along these lines:

seconds = int(seconds)
status = 'has been running for' if not finished else 'finished in'

minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)

periods = [('hours', hours), ('minutes', minutes), ('seconds', seconds)]
time_string = ', '.join('{} {}'.format(value, name)
                        for name, value in periods
                        if value)

print('The script {} {}'.format(status, time_string))

I am also self-taught and do it much the same as you.

For a different reason (wanted to periodically run functions) I was looking for "time until execute" logging, anyway, I codged this together after reading several examples (including this page).

def secs_to_dhms(seconds):
    from datetime import datetime, timedelta
    d = datetime(1,1,1) + timedelta(seconds=int(seconds))
    output = "{:02}:{:02}:{:02}:{:02}" .format(d.day-1, d.hour, d.minute, d.second)
    return output

Not exactly what you wanted, but maybe of use to you, anyway.


Iterate an array of BlockingCollections I have an array of BlockingCollections that i have initiated like this:

BlockingCollection<FxDataMapper>[] _fxDataByPair ;
arrayOfBlockingCollection = new BlockingCollection<MyClassInstance>[4];
            for (int i = 0; i < 4; i++)
                _arrayOfBlockingCollection[i] = new BlockingCollection<MyClassInstance>();

Now it want to iterate the array and extract each of the array elements and consume the BlockingCollections elements My code is this and although it works i think its not the best one

private void testArrayConsuming()
{
    Task processor = Task.Factory.StartNew(() =>
    {
        foreach (var x in arrayOfBlockingCollection )
        {
            Task processor2 = Task.Factory.StartNew(() =>
            {
                foreach (var y in x.GetConsumingEnumerable())
                        Console.WriteLine(x.Element.Value.ToString());

            });
        }
    });
}

Your code has a couple of problems:

It is a void (synchronous) whose only task is to start a Task, lying to the caller since it's in fact an asynchronous Task.
You are using Task.Factory.StartNew instead of the preferred Task.Run

So, a better approach to this would be something like this:

private async Task testArrayConsuming()
{
    foreach (var x in arrayOfBlockingCollection)
    {
        await Task.Run(() =>
        {
            foreach (var y in x.GetConsumingEnumerable())
            {
                Console.WriteLine(x.Element.Value.ToString());
            }
        });
    }
}

This would block execution, consuming one x at a time. If you want this to be parallel, use this instead:

private async Task testArrayConsuming()
{
    var tasks = new List<Task>();
    foreach (var x in arrayOfBlockingCollection)
    {
        tasks.Add(Task.Run(() =>
        {
            foreach (var y in x.GetConsumingEnumerable())
            {
                Console.WriteLine(x.Element.Value.ToString());
            }
        }));
    }

    await Task.WhenAll(tasks); // wait for all of them
}

With the help of your knowledge i have tweaked the code and i come to this which seems to be the best in terms in CPU Usage

private async Task testArrayConsuming()
        {
            await Task.Run(() =>
            {
                foreach (var x in arrayOfBlockingCollection)
                {
                     Task.Run(() =>
                    {
                        foreach (var y in x.GetConsumingEnumerable())
                        {
                            Console.WriteLine(y.Element.Value.ToString());
                        }
                    });
                }
            });
        }

Hope you give me your opinion...


Printing a pattern through the use of a dictionary We had to port a c program to python.  The code works but uses a dictionary to solve the problem.  This doesn't feel like the right use of a dictionary.  Is there a better way?

#!/usr/bin/env python3

def main():
    while True:
        height = input("Height: ")
        try:
            height = int(height)
            if height >= 0:
                break
        except:
            pass

    mtn={}
    space_mtn(height,mtn)
    hashs_mtn(height,mtn)
    print_mtn(height,mtn)

def space_mtn(height,mtn):

    for i in range(height):
        for j in range(2*height+2):
            mtn[i,j]=" "
    return

def hashs_mtn(height,mtn):

    for i in range(height):
        for  j in range(height-1,height-i-2,-1):
            mtn[i,j] = '#'

    for i in range(height):
        for j in range(height+2,height+i+3):
            mtn[i,j] = '#'
    return

def print_mtn(height,mtn):

    for i in range(height):
        for j in range(height+3+i):
            print("{}".format(mtn[i,j]),end="")
        print("")
    return

if __name__ == "__main__":
    main()

For how you're using it, it seems like a list of lists would make more sense than a dict. This is somewhat like a 2-dimensional array in C.

Your mtn initialization becomes:

mtn = []

You'll need to do a little more work in space_mtn to generate the sublists:

def space_mtn(height,mtn):
    for i in range(height):
        mtn.append([])             # Append an empty sublist at each level
        for j in range(2*height+2):
            mtn[-1].append(" ")    # Append a space to the end of the currently-last list
    return

Now in hash_mtn and print_mtn, just change your mtn[i,j] calls to mtn[i][j].

Now, there are lots of ways to make this code less C-like and more "Pythonic". Such discussions are probably better for Code Review. I'll just say that it's possible (although not necessarily "best") to get equivalent functionality by replacing everything after your input while loop with one line:

print('\n'.join('{0:>{1}}  {0:{1}}'.format('#'*(i+1), height) for i in range(height)))

Dictionaries are great. As long as you don't care about a specific order (though there are ways of making them ordered and I believe they will be in a upcoming release of python).

In your case maybe the use of zip could be useful.


Given a pivot x, and a list lst, partition the list into three parts The task:

  Given a pivot x, and a list lst, partition the list into three parts.

  The first part contains all elements in lst that are less than x The
  second part contains all elements in lst that are equal to x The third
  part contains all elements in lst that are larger than x Ordering
  within a part can be arbitrary.

  For example, given x = 10 and lst = [9, 12, 3, 5, 14, 10, 10], one
  partition may be `[9, 3, 5, 10, 10, 12, 14].

My solution:

const createPartitionOf = (lst, pivot) => {
  const lessLst = lst.filter(x => x < pivot);
  const equalLst = lst.filter(x => x === pivot);
  const largerLst = lst.filter(x => x > pivot);
  return [...lessLst, ...equalLst, ...largerLst];
};

console.log(createPartitionOf([9, 12, 3, 5, 14, 10, 10], 10));

My solution2:

const createPartitionOf2 = (lst, pivot) => {
  const lessLst = [];
  const equalLst = [];
  const largerLst = [];
  for (let i = 0; i < lst.length; i++) {
    if (lst[i] < pivot) {
      lessLst.push(lst[i]);
    } else if (lst[i] > pivot) {
      largerLst.push(lst[i]);
    } else {
      equalLst.push(lst[i]);
    }
  }
  return [...lessLst, ...equalLst, ...largerLst];
};

console.log(createPartitionOf2([9, 12, 3, 5, 14, 10, 10], 10));

In your first solution you are traversing the list 3 times, whereas in the second solution only once. Given the functional-tag, I’d say you’re after the reduce function:

const flatten = (acc, x) => acc.concat(x)

const pivotPartition = (pivot, ary) => {
  const toOrdered = (triplet, n) => {
    let [less, equal, greater] = triplet

    switch(true) {
      case n < pivot: less.push(n); break
      case n > pivot: greater.push(n); break
      default: equal.push(n)
    }

    return triplet
  }

  return ary.reduce(toOrdered, [[], [], []]).reduce(flatten)
}

If you want to sort the subarrays as well, then the whole thing is just a ary.sort((a, b) => a - b), although as it is mutating the list, it isn’t a functional solution.

Consider 2 Pointers low and high are keep moving towards center direction ultimately x == value will be centered
        int x = 10;
        Integer[] intList = new Integer[] {9, 12, 3, 5, 14, 17, 10, 10};
        int pointlow=0, pointhigh = intList.length-1;
        Integer arr[] = new Integer[intList.length];

        for(int i=0; i<= intList.length-1; i++) {
            if(intList[i] < x) {
                arr[pointlow] = intList[i];
                pointlow++;
            }
            else {
                arr[pointhigh] = intList[i];
                pointhigh--;
            }
        }
        System.out.println(Arrays.asList(arr));


Displaying image for the selected year I have the following code and I'm trying to find a cleaner way to run the year functions. At the moment I have 5 years as divs with an onclick event to bring the appropriate year image into view. So if you click on 1950, the 1950 year image will appear. If you then click on 1960, the 1950 image will disappear and the 1960 image will appear and so on.

In order to make sure that only the year image I want to see appears I have coded each function to remove every other years' image but this is going to lead to massive bloat as I want to be able to increase my 5 years to 20 and up.

Is there a way such as using a loop to work something like:
"If I click on 1950 then hide anything other 1950 and just show 1950"
rather than what I have now which is
"If I click on 1950, then hide 1960 image, hide 1970 image, hide 1980 image... and show 1950 image"

<!doctype html>

<meta charset="utf-8">
<base href="http://dtwdev.co.uk/new/">
<title>Year test</title>

1950

1960

1970

1980

1990

Create a style for the classes hidden_year and visible_year. When you click a link use a selector that selects all with id containing "year_19" and set them all to hidden_year, then just set the link you clicked to visible_year.

You could use a loop to build up the id values 5-9 if you really wanted to. . . var curr_year = 'year_19' + i + '0' in a loop.

Here is an example:

<!doctype html>

<meta charset="utf-8">
<title>Year test</title>

1950

1960

1970

1980

1990

1950

1960

1970

1980

1990

    function slideInYear(el){
        var elem = document.getElementById(el);
        elem.style.transition = "left 0.5s linear 0s";
        elem.style.left = "50px";
        slideOutYear();
        elem.className = 'active';
    }

function slideOutYear(){
    var active = document.getElementsByClassName('active');
    if (active.length > 0) {
      var elem = active[0];
      elem.style.transition = "left 0.5s linear 0s";
      elem.style.left = "-500px";
      elem.className = '';
    }
}

change these things


Sort numbers in ascending order using Python This is Python code to sort the numbers in ascending order (It's my school task). How does it look?

It works, but I think that this can be improved.

# How many number we have to sort
num = int(input("How many figures : "))
storage = []
result = []

# Creating an array of users numbers
for i in range(1,num+1):
    a = int(input("Enter value" + str(i) + " : "))
    storage.append(a) # user enter

# Sorting the array
for m in range(len(storage)):
    b = min(storage)
    storage.remove(b)
    result.append(b) # user get
j = ' '.join(str(i) for i in result)
print(j)

You could combine your input to a single line to improve ease of use. For example,

storage = input("Enter values separated by spaces:")
storage = [int(x) for x in storage.split()]

This way you have the entire list of input and can avoid having to have the user enter the number of input, and avoid having to declare the num variable at all.

However, you probably also want to include some form of input validation or throw a meaningful error as right now if your user was to enter non-integers, your program would simply crash and output a vague error that the user would probably have a difficult time understanding.

try:
    storage = [int(x) for x in test.split()]
except ValueError:
    print("Non-integers in input!")

Alternatively, you could check if all the values are numeric and if not, have the user re-enter their input.

As for your sorting algorithm, if you don't want to use Python's implemented sort() or sorted(), you should research more efficient algorithm's such as quick sort or even implement the bubble sort that you learned.

Currently, your min_sort algorithm finds the minimum value in the list, which is O(n) then removes that element from the list (separately from the search) which is again O(n). This is extremely wasteful as you may end up searching through the entire list again and again (n times), so it would be better to use a more efficient sorting algorithm or at least recognize that we don't need to pass through the entire list twice on each iteration, just pass through the list once and keep track of the minimum value. You could do this by writing your own function like:

def find_remove_min(nums):
    """Returns the minimum number and the list without the min number"""
    if nums:
        min_index = 0
        for i in range(1, len(nums)):
            if nums[i] < nums[min_index]:
                min_index = i
        return nums[min_index], nums[:min_index] + nums[min_index+1:]

Then you could do something like,

while storage:
    min_num, storage = find_remove_min(storage)
    result.append(min_num)

which would be more readable and efficient imo.

alist= int (input (" enter the values of the list"))      #list  formed will have the keyboard values

n= len(alist)                                 # length of the list

for r in range( n-1):

  for c in range(0, n-r-1):

        if alist[c] > alist [ c+1]:

              alist [ c] , alist [ c+1] =alist [ c+1] , alist [c] #toswap

print( " sorted list", alist)

will give sorted list in ascending order


Counting the number of occurrences of chars in one string, in another string This program counts the total number of times any character from the source string can be found in the target string.

E.g Source String - "Hello World"
Target String - "llo"
Output = 5 (as there are 3 l's and 2 o's)

Source String - "Hello World"
Target String - "ooood"
Output = 3 (as there are 2 o's and 1 d)

Is there any better way of write the below program?

public class CountOccurence {
public static int countChars(String target, String source){
    char a[] = source.toCharArray();

    int loc = 0, count = 0;
    boolean charRepeat = false;

    for (loc = 0; loc < source.length(); loc++) {
        charRepeat = false;
        for (int z = 0; z < loc; z++) {
            if (a[loc] == a[z]) {
                charRepeat = true;
                break;
            }
        }

        if (charRepeat == false) {
            int i = 0;
            while ((i = target.indexOf(a[loc], i)) != -1) {
                count++;
                i++;
            }
        }
    }
    return count;
}

public static void main(String[] args) {
    String target = "Hello World";
    String source = "oood";

    int count = countChars(target, source);
    System.out.println(count);

    source = "lld";
    count = countChars(target, source);
    System.out.println(count);

}

}

Style

There are a few bad habits in here that should be resolved. Here's your core method:

public static int countChars(String target, String source){
    char a[] = source.toCharArray();

    int loc = 0, count = 0;
    boolean charRepeat = false;

    for (loc = 0; loc < source.length(); loc++) {
        charRepeat = false;
        for (int z = 0; z < loc; z++) {
            if (a[loc] == a[z]) {
                charRepeat = true;
                break;
            }
        }

        if (charRepeat == false) {
            int i = 0;
            while ((i = target.indexOf(a[loc], i)) != -1) {
                count++;
                i++;
            }
        }
    }
    return count;
}

let's go through some things that are style-based.

source comes before target. The natural thinking is that you go from the source to the target, your naming, and the order of the parameters, is awkward. I would call the source something like searchFor, and the target I would call searchIn. Note, you have confused these values so much that your description does not match your code. In your description you have:

E.g Source String - "Hello World"
Target String - "ooood"
Output = 3

but in your code you have:

String target = "Hello World";
String source = "oood";
int count = countChars(target, source);

Note how you have swapped the source/target between the example and the code.

source and target are basically bad names to have...
Your code uses a number of small variables that are unconventional. loc is not a terrible name, it is clearly short for location, but using the fill location would be better. I have a habit of using pos so I can't really complain. On the other hand, the variables a for the char array, and z for an index, are bad names. You already use charRepeat, so you know how to use meaningful names, use them. The z is interesting because it is common to use x, y, and z as names for coordinate space, so seeing z automatically implies there's an x and y too. You should rather just use the standard index variables i, j, and k (but don't use j unless you are already using i, and don't use k unless you are using j too).

Algorithm

Your algorithm is a bit messed up too. Basically, you scan the searchFor chars, and find the first occurrence of each char value. If it's the first one, you then use that to scan the searchIn value, and you count the 'hits' in there. There are two issues here. The first issue is the performance of the 'first check'. The performance is \$O(n^2)\$ where \$n\$ is the number of chars in the searchFor value.

Then, for each unique char, you then do a loop through all the searchIn chars. The loop through all those are disguised in two steps, first the while loop, and then inside that, the indexOf search.

The net result is that you have a performance of \$O(nm)\$ or \$O(n^2)\$ depending on whether there are more characters in the searchIn or searchFor strings.

There is a better solution for both the uniqueness testing, and for the searching. Consider sorting the chars in each string:

char[] lookFor = searchFor.toCharArray();
char[] lookIn = searchIn.toCharArray();

Arrays.sort(lookFor);
Arrays.sort(lookIn);

The two sorts are \$O(n \log n)\$ performance, so this is, so far, significantly less complicated... now, how do we compare? Well, with a 'simple' loop over all the lookIn characters:

int forpos = 0;
int count = 0;
for (char c : lookIn) {
    // advance the searchFor cursor to the next usable position
    while (forpos < lookFor.length && lookFor[forpos] < c) {
        forpos++;
    }
    if (forpos >= lookFor.length) {
        //nothing left to look for.
        break;
    }
    if (c == lookFor[forpos]) {
        count++;
    }
}
return count;

With the above code, you do two sorts, and 1 loop through each value. The net result is that your performance complexity is simply \$O(n \log n)\$ where \$n\$ is the longer of the searchIn or searchFor variables.

By sorting each side, you give yourself a significant algorithmic advantage.

If you like a compact solution using regular expressions try this:

public static void main(String[] args) {
    System.out.println(countChars("ooood", "Hello World"));
    System.out.println(countChars("llo", "Hello World"));
}
public static int countChars(String source, String target) {
    if (source.isEmpty()) return 0;
    String regex = "[" + source.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\]", "\\\\]") + "]";
    return target.length() - target.replaceAll(regex, "").length();
}

It creates a regular expression with a character class containing all characters from target. Then it replaces all those characters in source with nothing and returns how many characters have been removed.


Jquery code is sloppy my shoppingcart is working but i used to many var and functions and i think it looks sloppy. i dont know how to set it right.

here is the Jsfiddle link:

https://jsfiddle.net/z0c1ja37/

can someone help me to put things right in this code?

look at my jsfiddle link there is the full code

$('.productprijzen').hide();
var $select = $('<select>').addClass('keuzes');
$select.append('<option>Kies je optie</option>');
$select.append('<option value="volvo">Volvo</option>');
$select.append('<option value="saab">saab</option>');
$select.append('<option value="peugeot">peugeot</option>');
$select.append('<option value="mazda">mazda</option>');

$select.on('change', function () {
    $parent = $(this).closest(".row");
    $('.productprijzen', $parent).slideDown();

    // prijs en btw laten zien
    var merk = $(this).val();
    var productInfo = oProducten[merk];
    $parent.find('.prijs').html("€" + productInfo.prijs);
    $parent.find('.btw').html(productInfo.btw + "%");

    // berekening van aantal x prijs
    var $aantalKeuze = $parent.find('input.aantal');
    var $subtotaal = $parent.find('.sub');

    $aantalKeuze.bind('keyup mouseup', function () {
        var $subtotaalUiteindelijk = productInfo.prijs * $aantalKeuze.val();
        $subtotaal.html($subtotaalUiteindelijk);

        var totaalBtw6 = 0;
        var totaalBtw21 = 0;
        var $totaal = 0;
        var $subtotaalVeld = $(".sub");
        $subtotaalVeld.each(function () {
            if ($(this).text() !== "") {
                $totaal = $totaal + Number($(this).text());
            }
        });

Use named functions

It's very common to write event handlers inline as anonymous functions, but as code gets more complex, this leads to deeply nested code that can be hard to follow. The inner event in particular could be something like $aantalKeuze.bind('keyup mouseup', handleAantalKeuzeChange); (apologies for the mix of languages).

Register events only once

At the moment, you seem to be registering the keyup mouseup handler every time the user changes the parent select. If the HTML it's checking isn't being replaced, this is going to end up with duplicate handlers. If the HTML is dynamically created (which doesn't show in this code) you could use a .on() "delegated event" to bind it in advance.

Separate UI logic from calculations

Try to separate your workflow into:

Get data from HTML
Calculate values (totals etc)
Populate new HTML

This might mean more (named!) functions, or it might just mean moving lines around and more variables. The aim is that you should be able to examine and change the "business logic" in step 2 separately from the "display logic" in steps 1 and 3.

Be consistent

You mostly use the convention that variables prefixed with $ are jQuery DOM objects and others are values, but you have var $totaal = 0; instead of var totaal = 0;. This is closely related to the previous point - the business logic part of the code should have no $ variables in it.

You mostly scope your variables with var, but have it missing on $parent. Because of how JS "hoists" variables, it may be sensible to declare all your variables close to the top of the function as possible. Again, this may encourage you to split out some sections into their own function - if a set of variables is only used within a tight section of code, that code might be asking to become a separate function, with defined inputs and outputs.

You mostly use $parent.find(...), except in $('.productprijzen', $parent). Standardise on one or the other, unless I'm mistaken and there's a significant difference.

My (Disclaimer: opinion-based from a German point of view) main issue here, are the non-english identifier. Of course I can guess some, but a minimized version would be as readable and unsuitable for an detailed review as this code. Always code in english, you never know who will need to read your code.

In addition to that, it is actually up to you, if you prefer a clarifying variable, if it is only used once in the next line, or not. There is no global valid recommendation.


Inefficient DNA heterodimerization script I have stuck with this script it would be great if you could help me with your inputs. My problem is that I think the script is not that efficient - it takes a lot of time to end running.
I have a fasta file with around 9000 sequence lines (example below) and What my script does is:

reads the first line (ignores lines start with >) and makes 6mers (6 character blocks)
adds these 6mers to a list
makes reverse-complement of previous 6mers (list2)
saves the line if non of the reverse-complement 6mers are in the line.
Then goes to the next line in the file, and check if it contains any of the reverse-complement 6mers (in list2). If it does, it discards it. If it does not, it saves that line, and reads all reverse complement 6-mers of the new one into the list2 - in addition to the reverse-complement 6-mers that were already there.

my file:
>seq1
TCAGATGTGTATAAGAGACAGTTATTAGCCGGTTCCAGGTATGCAGTATGAGAA
>seq2
TCAGATGTGTATAAGAGACAGCGCCTTAATGTTGTCAGATGTCGAAGGTTAGAA
>seq3
TCAGATGTGTATAAGAGACAGTGTTACAGCGAGTGTTATTCCCAAGTTGAGGAA
>seq4
TCAGATGTGTATAAGAGACAGTTACCTGGCTGCAATATGGTTTTAGAGGACGAA

and this is my code:
import sys
from Bio import SeqIO
from Bio.Seq import Seq

def hetero_dimerization():
    script = sys.argv[0]
    file1 = sys.argv[1]
    list = []
    list2 = []
    with open(file1, 'r') as file:
        for record in SeqIO.parse(file, 'fasta'):
            for i in range(len(record.seq)):
                kmer = str(record.seq[i:i + 6])
                if len(kmer) == 6:
                    list.append(kmer)
            #print(record.seq)
            #print(list)

            for kmers in list:
                C_kmer = Seq(kmers).complement()
                list2.append(C_kmer[::-1])
            #print(list2)

            cnt=0
            if any(items in record.seq for items in list2):
                cnt +=1

            if cnt == 0:
                print('>'+record.id)
                print(record.seq)

if __name__ == '__main__':
    hetero_dimerization()

Here is your original code with comments on which lines should be revised for clarity
import sys
from Bio import SeqIO
from Bio.Seq import Seq

def hetero_dimerization():
    script = sys.argv[0]  # script is unused; the line should be removed
    file1 = sys.argv[1]
    list = []  # list is a python built-in python; overwrite it at your own peril. I'd suggest renaming this variable
    list2 = []
    with open(file1, 'r') as file:
        for record in SeqIO.parse(file, 'fasta'):
            for i in range(len(record.seq)):
                kmer = str(record.seq[i:i + 6])
                if len(kmer) == 6:  # this check is redundant. kmer is guaranteed to be of length 6
                    list.append(kmer)
            #print(record.seq)  # if you submit code for review, avoid commented out source code. it is confusing
            #print(list)  # same here, avoid commented out code

            # this is a bug. You add every kmer to the list even if you discard the sequence
            # you also add redundant ones, which causes considerable slowdown
            for kmers in list:
                C_kmer = Seq(kmers).complement()
                list2.append(C_kmer[::-1])
            #print(list2)  # avoid commented out code

            # adding a counter for a simple if is not very clean
            # instead consider `if not any(...):`
            cnt=0
            if any(items in record.seq for items in list2):
                cnt +=1

            if cnt == 0:
                print('>'+record.id)
                print(record.seq)

if __name__ == '__main__':
    hetero_dimerization()

Your code contains a bug (@danzel already pointed that out), as you append the list if inverse complements for every 6mer you encounter, irrespective of it being from a sequence you wish to discard and irrespective of it being already contained in the list. You've fixed the bug in your updated code and in the process also changed the algorithm to avoid a lot of unnecessary work.
You can slightly (~15%) improve this further by (a) switching the complement list to a set and searching the set for each 6mer in the sequence (instead of the other way around) and by stopping the search early (breaking) if you encounter a 6mer that is already in the list. I also took the liberty to python-ify your code a bit in the process.
def kmer_generator(record, k=6):
    sequence = record.seq
    for idx in range(len(sequence) - (k-1)):
        yield sequence[idx:(idx+6)]

def hetero_dimerization_optimized():
    taboo_list = set()
    resulting_sequences = list()
    with open("fasta-file", 'r') as file:
        for record in SeqIO.parse(file, 'fasta'):
            new_taboo_items = set()
            for kmer in kmer_generator(record):
                if str(kmer) in taboo_list:
                    break
                complement = str(kmer.reverse_complement())
                new_taboo_items.add(complement)
            else:
                # this is entered only if no break occurs
                # i.e. if no kmer was in the taboo_list :)
                taboo_list = taboo_list.union(new_taboo_items)
                resulting_sequences.append(record.seq)
    return resulting_sequences

From here, your most noticable speedups would come from (a) writing your own reverse_complement function that reduces constant overhead (~50% of the runtime is spend on this line), (b) switching to numpy and using chararray to get access to np.view and avoid further copies of your data; this is in addition to (a) and could save you an additional 20%+ runtime.
After this, you could look into multiprocessing to use additional cores to pre-filter sequences, but tbh. this will likely be over-engieered for a mere 9000 sequences.

I think this should work - this is my own answer, please give your inputs
I removed one list to avoid another layer of for loop in the code and performed the reverse-complement conversion in one compact loop. Also, I added the pass - else command to avoid writing 6mers of lines that do not meet the condition.
with open('file.fasta', 'r') as file:
    list = []
    for record in SeqIO.parse(file, 'fasta'):

        cnt = 0
        if any(items in record.seq for items in list):
            cnt += 1
            pass
        else:
            for i in range(len(record.seq)):
                kmer = str(record.seq[i:i + 6])
                if len(kmer) == 6:
                    C_kmer = Seq(kmer).complement()
                    list.append(C_kmer[::-1])

        if cnt == 0:
            print('>' + record.id)
            print(record.seq)


How to append values into existed Vec with iterator I have a Vec with value default [0], and then I want to append into the vec with an iterator which is read from stdin, now my code is not performant since I use an insert to shift all the values behind index 0, how to improve this code with rusty style?
#[allow(unused_imports)]
use std::cmp::{max, min};
use std::io::{stdin, stdout, BufWriter, Write};

#[derive(Default)]
struct Scanner {
    buffer: Vec<String>,
}
impl Scanner {
    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().expect("Failed parse");
            }
            let mut input = String::new();
            stdin().read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

fn main() {
    let mut scan = Scanner::default();

    let n: usize = scan.next();
    // How to improve these lines?
    let mut arr = (0..n).map(|i| scan.next()).collect();
    arr.insert(0, 0);
}

Playground link

I have got an answer with chain
fn main() {
    let mut scan = Scanner::default();
    let n: usize = scan.next();
    let mut arr = vec![0];
    let mut arr: Vec<i32> = arr.into_iter().chain((0..n).map(|i| scan.next())).collect();
    println!("{:?}", arr);
}


Print all permutations with repetition of characters Given a string of length n, print all permutation of the given string.
  Repetition of characters is allowed. Print these permutations in
  lexicographically sorted order

Examples:

Input: AB

Ouput: All permutations of AB with repetition are:

  AA
  AB
  BA
  BB

Input: ABC

Output: All permutations of ABC with repetition are:

   AAA
   AAB
   AAC
   ABA
   ...
   ...
   CCB
   CCC

The following is my code:

void permutate(const string& s, int* index, int depth, int len, int& count)
{
    if(depth == len)
    {
        ++count;
        for(int i = 0; i < len; ++i)
        {
            cout << s[index[i]];
        }
        cout << endl;
        return;
    }

    for(int i = 0; i < len; ++i)
    {
        index[depth] = i;
        permutate(s, index, depth+1, len, count);
    }
}

int main()
{
    string s("CBA");
    sort(s.begin(), s.end());
    cout << s << endl;
    cout << "**********" << endl;
    int len = s.size();
    int* index = new int[len];
    int count = 0;
    permutate(s, index, 0, len, count);
    cout << count << endl;

    system("pause");
    return 0;
}

In case you ever want to just display the string (if you have something like "AAA"):

// if a different character from the first is not found
// std::string::npos corresponds to "not found" (or -1)

if (s.find_first_not_of(s.front()) == std::string::npos)
{
    // inform user that only one permutation exists
}

This is a potential loss of data:

int len = s.size();

size() returns std::size_type, not int.  Do not use int for std::string or other STL container sizes.  They have their own size types that prevents this very issue.  This would be the proper initialization of len:

std::string::size_type len = s.size();

This is needless and potentially dangerous:

int* index = new int[len];

The "dangerous" part refers to the fact that delete is never used to free the allocated memory.  Always use delete with new where appropriate.

In order to free the memory properly, you would use delete in this way:

delete [] index;

But since you're utilizing the STL, instead consider an std::vector:

std::vector<int> index(s.size());

As the memory management is already properly done in std::vector's implementation, new/delete is not needed here at all.  Always try to avoid doing this manually in C++.
No need to pass the string's size; it's already part of the implementation.  Just use s.size().
With the utilization of the aforementioned std::vector and size(), you should now make depth and the loop counters of std::size_t.  This will avoid type-mismatch warnings from comparing size() with an int.  Make sure your compiler's warning flags are high.
Avoid using system("PAUSE") as it is platform-specific and can be imitated by better alternatives such as std::cin.get().  This will ask the user for a console input instead of a keystroke, but that difference shouldn't matter if it means maintaining portability.

Final code with applied changes (also tested on Ideone):

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <string>
#include <vector>

void permutate(const std::string& s, std::vector<int>& index, std::size_t depth, int& count)
{
    if (depth == s.size())
    {
        ++count;
        for (std::size_t i = 0; i < s.size(); ++i)
        {
            std::cout << s[index[i]];
        }
        std::cout << "\n";
        return;
    }

    for (std::size_t i = 0; i < s.size(); ++i)
    {
        index[depth] = i;
        permutate(s, index, depth+1, count);
    }
}

int main()
{
    std::string s("CBA");

    if (s.find_first_not_of(s.front()) == std::string::npos)
    {
        std::cout << "Only 1 permutation exists";
        return 0;
    }

    std::sort(s.begin(), s.end());

    std::cout << s << "\n**********\n";

    std::vector<int> index(s.size());
    int count = 0;

    permutate(s, index, 0, count);

    std::cout << "\nTotal permutations with repetitions: " << count;
}

I think it could be improved by not calling the task "permutations".
Permutations are rearrangements.  It seems you are mostly producing all combinations.

I refer you to these:

http://www.cplusplus.com/reference/algorithm/next_permutation/
http://en.wikipedia.org/wiki/Permutation