blob_id
stringlengths 40
40
| repo_name
stringlengths 5
119
| path
stringlengths 2
424
| length_bytes
int64 36
888k
| score
float64 3.5
5.22
| int_score
int64 4
5
| text
stringlengths 27
888k
|
---|---|---|---|---|---|---|
36ee5e017679d04766ec379ba1c7d345968d1d90 | Arushi-V/PythonWithCM | /2021.05.26/set_ex.py | 1,169 | 4.375 | 4 | # Set
# its a collection of unique items
# A set is a collection which is both unordered and unindexed.
jwellerySet = {"earings", "necklace", "ring"}
print(type(jwellerySet))
print(jwellerySet)
# duplicates are not allowed in sets
print(len(jwellerySet))
# A set can contain different data types:
wallet = {100, "cheques", "photos", "dl", "card"}
# Loop through the set, and print the values:
for item in jwellerySet:
print(item)
# add item in set
jwellerySet.add("bracelet")
print(jwellerySet)
# add sets
wallet.update(jwellerySet)
print(wallet)
# remove items
wallet.remove("cheques")
print(wallet)
# discard also remove items but don't raise error on item not found
wallet.discard("cheques")
print(wallet)
# union and update
# You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set1)
print(set3)
#intersection_update : prints the common value of two sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x) |
1f351a82046b76bc4b14897bc61f5eafde761bf3 | jacelecomte/Python | /first_occurrence.py | 1,027 | 3.671875 | 4 | # With runtime of O(log n) print array position of the first '1' found in the array
def location_of_first_one(array):
counter = 0
lowerbound = 0
upperbound = 0
length = len(array)
if length == 1:
return 0
while counter < length:
lowerbound = counter
counter *= 2
upperbound = counter
if upperbound > length:
upperbound = upperbound - 1
if array[lowerbound] == array[upperbound]:
counter = lowerbound + 1
elif array[lowerbound] != array[upperbound]:
if array[upperbound] == array[upperbound - 1]:
return upperbound-1
return upperbound
else:
print("error")
return 'error'
n = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]
m = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]
o = [1]
p = []
print(location_of_first_one(n))
print(location_of_first_one(m))
print(location_of_first_one(o))
print(location_of_first_one(p))
|
4d37e556f6f785cb9817e9a3068b2c9eea683e73 | karthikaManiJothi/PythonTraining | /Assignment/Day1Assignment/ReverseWordbyWord.py | 107 | 3.859375 | 4 | str =input("Enter string").split()
list1 =[]
for i in str:
list1.append(i[::-1])
print(" ".join(list1)) |
962c11de4dc82e0c0a722971dff82b517c9c149a | dedekinds/pyleetcode | /A_jzoffer/数组中只出现一次的数字.py | 1,283 | 3.703125 | 4 | 根据全部的^获得一个数,找到这个数的二进制数的右边第一个1的位置,根据这个1的位置可以将数组分类
成两组,这样就可以分别对每一组都来一波^即可
# -*- coding:utf-8 -*-
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def find_first_one(self,num):
if num == 0:return -1
cnt = 0
while num:
if num & 1:return cnt
else:
num = num >> 1
cnt += 1
def classifier(self,num,one_location):
if (num >> one_location)%2 :return 1
else:return 0
def FindNumsAppearOnce(self, array):
# write code here
temp = array[0]
for i in range(1,len(array)):
temp = temp ^ array[i]
one_location = self.find_first_one(temp)
num1 = []
num2 = []
for i in range(len(array)):
if (self.classifier(array[i],one_location))%2:num1.append(array[i])
else:num2.append(array[i])
a = num1[0]
b = num2[0]
for i in range(1,len(num1)):
a = a ^ num1[i]
for i in range(1,len(num2)):
b = b ^ num2[i]
return [a,b]
|
3f19379d6dff1963d40bf3cb302777041457e823 | EmineKala/Python-101 | /Python/Hafta2/alistirma6.py | 458 | 4 | 4 | #Bu egzersizde, size bir alışveriş listesi ve bir eşya verilecek.
#Eğer verilen eşya alışveriş listesinde ise True döndürün, alışveriş listesinde değilse False döndürün.
def shopping_list(list,item):
found = False
for i in list:
if i == item:
found = True
return found
list = ["süt","yumurta","ekmek","peynir", "zeytin"]
item = input ("Listede aranacak değeri yazınız:")
print(shopping_list(list,item))
|
a607db685fa19842c302dd8899eaf441768eb785 | wkwkgg/atcoder | /arc/017/a.py | 161 | 3.703125 | 4 | from math import sqrt
N = int(input().rstrip())
ans = "YES"
for i in range(2, int(sqrt(N))+1):
if N % i == 0:
ans = "NO"
break
print(ans)
|
f215511e2cbab26a91e6580c0fe0a96881f3d9a2 | MSoup/Interval-Merge | /main.py | 934 | 4.1875 | 4 | """
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
"""
def merge(lst):
newlst = []
for i in lst:
#Create list using first el; on future loops, check tail of el against head of next el. If Tail[before] < head[cur], no interval, append cur
if not newlst or newlst[-1][-1] < i[0]:
print("appending " + str(i))
newlst.append(i)
#Check tail of el against tail of cur;
elif newlst[-1][-1] < i[-1]:
print("Replacing " + str(newlst[-1][-1]) + " with " + str(i[-1]))
newlst[-1][-1] = i[-1]
return newlst
print(merge([[1, 3], [2, 6], [8, 10], [15, 18]]))
|
aa16c20cf456820bf4ab9ee8f122b73f5b5365d3 | jidhu/code | /DataStruct/strings/anagram.py | 400 | 3.859375 | 4 | s1 = 'asdfg'
s2 = 'gadsdfa'
s1 = [char for char in s1]
s2 = [char for char in s2]
def anagram(s1, s2):
if len(s1) != len(s2):
return False
count = [0]*256
for i in range(0,len(s1)):
count[i]=count[i]+1
for i in range(0,len(s2)):
count[i]-=1
for i in range(256):
if count[i] != 0:
return False
return True
print(anagram(s1,s2)) |
f7de84b4502f00f61a16d1835614c91ff52e01c2 | Beatriz021/Clases | /persona.py | 773 | 3.734375 | 4 | #crear una carpeta que se llame claases y dentro de los
#archivos dino.py persona.py
#crear una clases Persona() que tenga como atributos nombre, edad
#y profesión. Al instanciar la clases tiene que saludar igual que
#el dino diciendo sus atributos
class Persona:
def __init__(self, un_nombre="",una_edad=0,una_profesion=""):
self.nombre=un_nombre
self.edad=una_edad
self.profesion=una_profesion
print("Hola!. Mi nombre es ",self.nombre,"tengo",self.edad,"soy",self.profesion)
def cumpleaños(self):
self.edad=self.edad+1
print("Tendrás",self.edad)
objeto=Persona("Myrian",17,"Estudiante")
#Agregar un método a la clase persona que se llame Cumpleaños y que aumente la edad de la persona
#en un año
|
cbb9090a85a235ca747eb09e8300f060b74836f3 | charlie16-meet/MEET-YL1 | /oop/oop.py | 620 | 3.734375 | 4 | class Animal:
def __init__(self,name,color,age,size):
self.name=name
self.color=color
self.age=age
self.size=size
def print_all(self):
print(self.name)
print(self.color)
print(self.age)
print(self.size)
def sleep(self):
print(self.name,"is sleeping...zzzzz")
def eat(self,food):
print(self.name,"is eating",food,"yum yum")
dog = Animal(name="max",color="black",age=4,size="huge")
cat = Animal(name="min",color="white",age=2,size="tiny")
dog.print_all()
print("##################")
dog.sleep()
dog.eat("pizza")
cat.eat("fish")
cat.sleep()
print("#################")
cat.print_all()
|
68c925dd9cc70bb8f43854a410f10ac357d23eae | jonathanortizdam1993445/DI | /python/EJERCICIOS LISTAS/ejercicio1.py | 367 | 4.09375 | 4 | #!usr/bin/env python
print("Dime el número de palabras a introducir en la lista")
numero =int(input());
if int(numero)>0:
lista=[]
#VAMOS RELLENANDO LA LISTA TANTAS VECES COMO HEMOS INDICADO ARRIBA
for i in range(numero):
print ("Digame la palabra");
palabra=input();
lista+=[palabra]
print("La lista creada es: ",lista)
else:
print("Imposible")
|
ff23e4233995dee0237652908eb00b148afd25be | adamib4/learn_python | /digital_root.py | 590 | 4.15625 | 4 |
'''
In this kata, you must create a digital root function.A digital root is the recursive sum of all the digits in a
number.Given n, take the sum of the digits of n.If that value has more than one digit, continue reducing in this way
until a single-digit number is produced.This is only applicable to the natural numbers.
digital_root(16)
=> 1 + 6
=> 7
digital_root(942)
=> 9 + 4 + 2
=> 15 ...
=> 1 + 5
=> 6
'''
def digital_root(n):
n = list(map(int,str(n)))
result = sum(n)
while len(list(map(int,str(result)))) > 1:
result = digital_root(result)
return result
|
186992b34ee3b9316e17bc2d29153e15f67ae8f0 | shashank31mar/DSAlgo | /mergeKSorted.py | 932 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 8 22:42:24 2018
@author: shashankgupta
"""
from heap import Heap
import math
def mergeKSorted(arr,n,k):
temp = []
arr_index = []
next_arr_index = []
for i in range(k):
temp.append(arr[i][0])
arr_index.append(i)
next_arr_index.append(1)
mh = Heap(temp)
mh.convertToHeap()
output = []
for i in range(n*k):
root = mh.getMin()
output.append(root)
if next_arr_index[arr_index.index(root)] < n:
root = arr[arr_index.index(root)][next_arr_index[arr_index.index(root)]]
next_arr_index[arr_index.index(root)] += 1
else:
root = math.inf
mh.replaceMin(root)
def main():
arr = [[1,2,3,4],
[2,3,4,5],
[6,7,8,9]]
mergeKSorted(arr,3,3)
if __name__ == "__main__":
main() |
bce3d902b4336f47412ad3b2894db9b41dd991e5 | mansooni/algorithm | /codingame/TheRiver1.py | 242 | 3.5 | 4 | import sys
import math
r_1=int(input())
r_2=int(input())
while True:
r1 = list(str(r_1))
r2 = list(str(r_2))
if r_1<=r_2:
for i in r1:
r_1+=int(i)
elif r_1>r_2:
for j in r2:
r_2+=int(j)
if r_1==r_2 :
break
print(r_1)
|
daafa647ac4989a0e529a2da548f38e9079f4e62 | SESYNC-ci/online-data-with-R-lesson | /test_census_api_code.py | 649 | 3.59375 | 4 | from census import Census
# Not sure what this is doing
key = None
c = Census(key, year=2017)
c.acs5
# Define variables to extract (name and median household income) and get them for all counties and tracts in state 24
variables = ('NAME', 'B19013_001E')
response = c.acs5.state_county_tract(
variables,
state_fips='24',
county_fips=Census.ALL,
tract=Census.ALL,
)
response[0]
# Convert to dataframe while also subsetting by income greater than zero
df = (
pd
.DataFrame(response)
.query("B19013_001E >= 0")
)
# just make a boxplot by county
import seaborn as sns
sns.boxplot(
data = df,
x = 'county',
y = 'B19013_001E',
)
|
13f511e5d11ab75bc0fef923a8aae0a8e450dbb7 | terrancemount/terrance-python-training | /n-threading.py | 8,866 | 4.40625 | 4 | #!/usr/bin/env python3
'''
Topic Title: Threads
**John**
Concept: A thread, similar to Java, is a separate line of execution that runs
at the same time as the main thread and any other currently running threads.
In Python, threading is useful to run programs concurrently, especially when you need
to run IO tasks in parallel. Multithreading has the benefits of sharing the
same memory space and therefore can communicate and share info with each other
unlike processes. For the most part, threading in Python is similar to threading
in Java. A difference is Python will only use one core of a CPU, Java will use
multiple cores. This means Python will only run one one thread's code at a time
(Python is effectively single threaded). To get around this, you will want to
use fork(), which creates a new process instead of a new thread.
Notes (Some details)
****************************************************************************
**Terrance**
_thread Module
- Simplest way to start a thread is to use _thread module. This module is a
lightweight and fast way to start a thread with just a function definition.
You do not need a class to use _thread.
In a try / except block then call
_thread.start_new_thread( function, (args))
*function is the function you have and args is the args for that function.
Functionality of this is very limited compared to the threading module.
You can't control the thread once created. You can't stop the calling
thread and wait until called thread has finished i.e. join() funciton in
Threading module.
*****************************************************************************
**All**
- Threading Module Functions (modules are like libraries in java)
- active_count(): returns the number of threads currently alive
- current_thread(): returns the current Thread object
- get_ident(): return the 'thread identifier' of the current thread,
which is a non-zero integer
-"Its value has no direct meaning: it is intended as a magic
cookie to be used to index a dictionary
of thread-specific data" -Python documentation
- enumerate(): Return a list of all Thread objects currently alive
(like active_count(), but returns the actual objects)
- main_thread(): return the main Thread object
- settrace(function): set a trace function for all threads spawned from the threading module
- *A trace function is used for Logging*
- setprofile(): set a profile function for all threads spawned from the threading module
- Gives information about the thread (e.g. how long it has been running)
- stack_size([size]): set how much space the thread will take on the stack
- [size] is optional. If not included, defaults to 0.
If included, must be either 0, or >32,768
- size should be a multiple of the page size for the system (commonly 4KiB)
----------------------------------------------------------------------------------
**Terrance**
Synchronization functions
- threading.Lock() gets a reference to the locking primative. Call normally in global
scope and stored in a reference. The referecne is then used to aquire and
release functions listed below.
- aquire() aquires a lock on the code until it is ether released or until the
end of the function.
- release() release the aquire lock on the function.
**Avery**
- Thread Object
- start(): Same as Java's start(), splits execution and starts the thread
- run(): define what the thread is going to do once it's started
- join(): A thread calls another thread's join(), which stops the calling thread
until the called thread terminates. Once the called thread terminates,
the calling thread continues. Useful to stop the main thread from terminating
while other threads are still executing (call join on each thread in main)
- getName() and setName()
- Threads are not unique, initial name is set in the constructor
- is_alive(): return True if the thread is alive, False if it's not
- Mostly used from another thread, since a dead thread can't call is_alive()
- isDaemon() and setDaemon(): isDaemon() returns True if the thread is a daemon,
False if not setDaemon() sets whether a thread is a daemon or not
*** getters and setters for name and daemon are deprecated,
can just use name and daemon directly
============================================================================================
Use case (Why would you use it):
**Examples:
Client / Server tasks. Create a new thread for each client connected to the
server for proccessing.
IO tasks -
-make mulitple SQl requests and receive responses
-reads from the harddrive.
Theroetical example:
-> 10 second server request latency.(takes 10 seconds to get a response)
-> 1 second to process the response
-> 10 requests are made then how long, sequential vs paralell?
-> sequential (no threading)
-> 10 requests * 10 seconds latency + 10 seconds processing
= 110 seconds.
-> paralell (using threads, single core)
-> 10 second latency + 10 second proccessing
= 20 seconds.
-> Paralell has a massive decrease in time over sequential because the
process is not waiting for the response.
============================================================================================
Online Resources (URLs):
Offical thread documentation (difficult to start learning)
https://docs.python.org/3.6/library/threading.html
Tutorialspoint has good starting examples
https://www.tutorialspoint.com/python3/python_multithreading.htm
Authors:
- Avery Ehnis
- John Steele
- Terrance Mount
'''
import _thread
import threading
import time
import random
def main():
setup = None
#==================================================================================
print('Starting simple _thread example')
#Create a thread using _thread
try:
_thread.start_new_thread( print_simple_time, ("Simple-Thread-1", 2, ) )
_thread.start_new_thread( print_simple_time, ("Simple-Thread-2", 4, ) )
except:
print("Error: unable to start thread")
#=================================================================================
print('Start Thread module Async threads')
#Example of asynchronous threads (starts 10 threads that sleep for a
##random amount of time between 1-10 seconds)
threads = []
for x in range(5):
#Set the name for each thread to make it easier to distinguish
myThread = MyThread(name = 'Thread-{}'.format(x+1))
myThread.start()
threads.append(myThread)
time.sleep(.5)
#Joins the main thread with all of the asynchronous threads,
##pauses main until all threads are finished
for t in threads:
t.join()
print('All Async threads have ended')
#===============================================================================
print('Create sync threads')
#clears out all the previous threads
threads.clear()
index = 0
for x in range(5):
index += 1
myThread = SynchroThread(index, "Thread-" + str(index), 1)
myThread.start()
threads.append(myThread)
for t in threads:
t.join()
threadLock = threading.Lock()
#==============================================================================
#Class that extends the Thread class in the threading module
class MyThread(threading.Thread):
#When the thread starts, it runs automatically
#This run method overrides the run in Thread, threads just sleep
def run(self):
print('{} started'.format(self.getName()))
time.sleep(random.randint(1,11))
print('{} ended'.format(self.getName()))
#=============================================================================
#define a simple function to use with the _thread example
def print_simple_time( threadName, delay):
count = 0
while count < 3:
time.sleep(delay)
count += 1
print ("%s: %s" % ( threadName, time.ctime(time.time()) ))
#=============================================================================
class SynchroThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
# Get lock to synchronize threads
threadLock.acquire()
print_synchro_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
def print_synchro_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
#==================================================================================
if __name__ == '__main__':
main()
|
5d5ea3dd3464db1fa1348249ed120721140260d9 | NagiReddyPadala/python_programs | /Python_Scripting/Pycharm_projects/Practice/Generators.py | 182 | 3.796875 | 4 |
def topTen():
num = 1
while num <= 10:
yield num*num
num +=1
vals = topTen()
vals.__next__()
next(vals)
print(type(vals))
for val in vals:
print(val)
|
f5c4d2c171531cef22c98b019f010c61181cf8f5 | rsprenkels/kattis | /python/1_to_2/cups.py | 257 | 3.65625 | 4 | N = int(input())
cups = {}
for cup in range(N):
first, second = input().split()
if str.isdecimal(first):
cups[int(first) / 2] = second
else:
cups[int(second)] = first
for radius in sorted(cups.keys()):
print(cups[radius])
|
480cb828ea5fff46c8441a45871c567e0554b2cd | dmmfix/pyeuler | /p042.py | 377 | 3.734375 | 4 | #!/usr/bin/python
import euler
import math
def word_score(w):
return sum(map(ord, w.upper())) - (ord('A')-1)*len(w)
def is_trinum(n):
sn = int(math.floor(math.sqrt(n * 2)))
return n == (sn * (sn+1))//2
def is_triword(w):
return is_trinum(word_score(w))
triwords = filter(is_triword, euler.read_words('data/p042_words.txt'))
print(len(triwords))
|
bf040073f3b3eb4323f0622d72895bc25877e72d | bilaleluneis/LearningPython | /conditional_and_loops.py | 3,239 | 3.921875 | 4 |
__author__ = "Bilal El Uneis and Jieshu Wang"
__since__ = "July 2018"
__email__ = "bilaleluneis@gmail.com"
from numpy import random as random_generator
def if_example(name):
if name == "Jieshu":
for x in name:
if x == "s":
continue
print(x)
else:
print("Check failed!")
def loop_example(counter):
while counter > 0:
print(counter)
counter = counter + 1
if counter == 100:
break
def find_largest_number_example(end_num, num_size):
find_largest_number_list = random_generator.randint(end_num, size=num_size)
print('\nExample: Find the largest number in the list {}:'.format(find_largest_number_list))
largest_num_so_far = None
print('Initially, the largest number is {}'.format(largest_num_so_far))
for the_num in find_largest_number_list:
if largest_num_so_far is None or the_num > largest_num_so_far:
largest_num_so_far = the_num
print('{}, the largest number so far is {}'.format(the_num, largest_num_so_far))
print('Finally, the largest number is {}'.format(largest_num_so_far))
def sum_up_example(end_num, num_size):
sum_up_example_list = random_generator.randint(end_num, size=num_size)
print('\nExample: Sum up the number in the list of {}:'.format(sum_up_example_list))
sum_so_far = 0
print('Initially, the sum is {}'.format(sum_so_far))
for the_num in sum_up_example_list:
sum_so_far = sum_so_far + the_num
print('{}, The sum so far is {}'.format(the_num, sum_so_far))
print('The final sum is {}'.format(sum_so_far))
def average_example(end_num, num_size):
average_example_list = random_generator.randint(end_num, size=num_size)
print('\nExample: Calculate average of the number in the list of {}:'.format(average_example_list))
counter = 0
sum_so_far = 0
average_so_far = 0
for the_num in average_example_list:
counter = counter + 1
sum_so_far = sum_so_far + the_num
average_so_far = sum_so_far / counter
print('{}, the average so far is {}'.format(the_num, average_so_far))
print('the final average is {}, approximately {}'.format(average_so_far, int(average_so_far)))
def search_num_example(end_num, search_num):
print('\nSearch for the number of "{}" example:'.format(search_num))
found = False
for the_num in range(0, end_num):
if the_num == search_num:
found = True
print(the_num, found)
if found:
print('We found the number of {} here!'.format(search_num))
else:
print('The number of {} is not here.'.format(search_num))
def find_in_list(number_to_find):
number_found_in_list = None
for a_number in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
if a_number == number_to_find:
number_found_in_list = a_number
print("\nNumber found in list is: {}".format(number_found_in_list))
# start of running code
if __name__ == "__main__":
if_example("Bilal")
loop_example(20)
if_example("Jieshu")
find_largest_number_example(100, 8)
sum_up_example(50, 8)
average_example(80, 10)
search_num_example(15, 23)
search_num_example(15, 5)
find_in_list(10)
find_in_list(9)
|
ab9d4a089ce39fa5cb90fe80235c2cc41d43d4fc | neilharvey/AdventOfCode | /2020/Day23/day23.py | 3,103 | 4.28125 | 4 | import sys
def crab_cups(cups, start, total_moves):
move = 1
min_cup = min(cups)
max_cup = max(cups)
current = start
while move <= total_moves:
# The crab picks up the three cups that are immediately clockwise of the current cup.
x = cups[current - 1]
y = cups[x - 1]
z = cups[y - 1]
pick_up = [x, y, z]
# They are removed from the circle; cup spacing is adjusted as necessary to maintain the circle.
cups[current - 1] = cups[z - 1]
# The crab selects a destination cup: the cup with a label equal to the current cup's label minus one.
destination = current - 1 if current - 1 >= min_cup else max_cup
# If this would select one of the cups that was just picked up,
# the crab will keep subtracting one until it finds a cup that wasn't just picked up.
# If at any point in this process the value goes below the lowest value on any cup's label,
# it wraps around to the highest value on any cup's label instead.
while destination in pick_up:
destination = destination - 1 if destination - 1 >= min_cup else max_cup
# The crab places the cups it just picked up so that they are immediately clockwise of the destination cup.
# They keep the same order as when they were picked up.
tmp = cups[destination - 1]
cups[destination - 1] = x
cups[z - 1] = tmp
# The crab selects a new current cup: the cup which is immediately clockwise of the current cup.
current = cups[current - 1]
move += 1
return cups
def get_clockwise_from_one(cups):
current = cups[cups.index(1)]
result = []
for _ in range(0, len(cups) - 1):
result.append(cups[current - 1])
current = cups[current - 1]
return result
def get_cups(input):
# Since the cups are a fixed length we can represent the circular linked list of cups using an array,
# i.e. for a given cup n, a[n - 1] = m where m is the next cup clockwise.
# In retrospect this was a shit idea and I should have just used a linked list.
size = len(input)
cups = [0] * size
for (i, cup) in enumerate(input):
next = input[(i + 1) % size]
cups[cup - 1] = next
return cups
def main():
path = sys.argv[1] if len(sys.argv) > 1 else "example.txt"
with open(path) as f:
input = [int(x) for x in f.read()]
cups = get_cups(input)
start = input[0]
part_one_cups = crab_cups(cups[:], start, 100)
print(f"Part One: {''.join(map(str, get_clockwise_from_one(part_one_cups)))}")
extra_cups = range(1 + len(cups), 1 + 1000000)
input.extend(extra_cups)
cups = get_cups(input)
part_two_cups = crab_cups(cups, start, 10000000)
part_two_cups_clockwise_from_one = get_clockwise_from_one(part_two_cups)
print(f"Part Two: {part_two_cups_clockwise_from_one[0] * part_two_cups_clockwise_from_one[1]} ({part_two_cups_clockwise_from_one[0]} x {part_two_cups_clockwise_from_one[1]})")
if __name__ == "__main__":
main() |
de10be368792a24c4a7c5fcfcfee5a115543b196 | ilyas9797/university-stuff | /src/generators/mmlr.py | 6,413 | 3.71875 | 4 | """Реализация класса модифицированного многомерного линейного генератора и вспомогательных функций"""
import math
from typing import Callable, List
def bits_number(num):
"""Возвращает количество бит, необходимое для представления числа в двоичном виде"""
return math.floor(math.log2(num)) + 1
def nums_xor(nums: list):
"""xor массива чисел"""
ret = nums[0]
for n in nums[1:]:
ret ^= n
return ret
def form_nums_list(state: int, r: int, pickup_list: List[int]) -> List[int]:
"""Формирует список значений из ячеек state указанных в pickup_list"""
# возвращаемый список
ret = []
# маска для получения значения ячейки, состоит из r единиц. Для получения значения i-ой ячейки
# сдвигается на i*r влево. Далее производится операция AND со значением текущего состояния
# and_mask = int('1' * r, base=2)
and_mask = (1 << r) - 1
# для каждой точки съема
for point in pickup_list:
# опреление необходимого сдвига для маски
shift = r * point
# вычисление значения ячейки под номером point
point_val = ((and_mask << shift) & state) >> shift
# добавление в массив
ret.append(point_val)
return ret
class MMLR:
"""
Modified Multidimensional Linear Register
Класс для формирования модифицированного многомерного линейного генератора с одной обратной связью и имитации его
работы
Атрибуты экземпляров:
r: int
n: int
pp: List[int]
mf: function
state: int
"""
def __init__(
self,
r: int,
n: int,
pickup_points: List[int],
modifying_func: Callable,
init_state: int = 0):
"""
Конструктор модифицированного многомерного линейного генератора
Параметры:
r (int): размерность ячейки
n (int): количество ячеек
pickup_points (list): список номеров точек съема
modifying_func (function): модифицирующее преобразование
def modifying_func(x: int): int:
...
init_state (int): начальное заполнение регистра
"""
#
if r <= 0:
raise Exception
self.r = r
#
if n <= 0:
raise Exception
self.n = n
#
if len(pickup_points) <= 0 or len(pickup_points) > n:
raise Exception
if 0 not in pickup_points:
raise Exception
if set(pickup_points).difference(set(i for i in range(n))):
# содержит элементы не из промежутка [0,n-1]
raise Exception
self.pp = pickup_points
# добавить проверку аргументов функции
self.mf = modifying_func
#
if init_state < 0:
raise Exception
if init_state != 0 and bits_number(init_state) > n * r:
raise Exception
self.state = init_state
def form_pp_nums(self):
"""Формирует список чисел из ячеек, соответсвующих точкам съема"""
return form_nums_list(self.state, self.r, self.pp)
def do_shift(self, new_val: int):
"""Производит сдвиг регистра и записывает новое значение new_val в последнюю ячейку"""
# сдвиг в сторону младшей ячейки
self.state = self.state >> self.r
# запись нового значения в старшую ячейку
self.state = self.state | (new_val << (self.r * (self.n - 1)))
def do_cycle(self):
"""Произвести один цикл работы генератора"""
# формирование списка зачений из ячеек, соответсвующих точкам съема
pp_nums = self.form_pp_nums()
# xor значений точек съема
xored_nums = nums_xor(pp_nums)
# применение модифицирующего преобразования
modified_val = self.mf(xored_nums)
# сдвиг регистра и запись нового значения
self.do_shift(modified_val)
def get_current_state_val(self) -> int:
"""Возвращает значение, соответсвующее текущему состояния генератора"""
return self.state
def get_current_output_val(self) -> int:
"""Возвращает значение ячейки с наименьшим порядковым номером"""
return form_nums_list(self.state, self.r, [0])[0]
def get_current_state(self) -> List[int]:
"""Возвращает список значений ячеек, соответсвующий текущему состоянию генератора"""
return form_nums_list(self.state, self.r, [i for i in range(self.n)])
def __iter__(self):
return self
def __next__(self):
self.do_cycle()
return self.get_current_output_val(), self.get_current_state_val()
def do_idling(self, idling_rounds=0):
'''
Проделать idling_rounds холостых ходов генератора
'''
if idling_rounds < 0: raise Exception('Error: wrong idling_rounds value')
if idling_rounds == 0:
n = self.n
else:
n = idling_rounds
for _ in range(n):
next(self)
# pass
|
5b56868c3ef6062d012d17ba2674960cdd4a56cc | EveryDayIsAPractice/Leetcode-python3 | /242_Valid_Anagram-0.py | 859 | 3.53125 | 4 | class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if s is None:
if t is None:
return True
else:
return False
elif t is None:
return False
memory=dict()
memory2=dict()
for i in s:
if i in memory:
memory[i]+=1
else:
memory[i]=1
for i in t:
if i in memory2:
memory2[i]+=1
else:
memory2[i]=1
if len(memory)!=len(memory2):
return False
for i in memory:
if i in memory2:
if memory[i]!=memory2[i]:
return False
else:
return False
return True
|
e07cbd509cd36e1d263c5d289277388adb4c9128 | carlos-sales/exercicios-python | /ex098.py | 511 | 3.546875 | 4 | from time import sleep
def contador(ini, f, p):
aux = 1
if p == 0:
p = 1
if ini > f and p > 0:
p *= -1
if p < 0:
aux *= -1
print(f'Contagem de {ini} até {f} de {p} em {p}')
for i in range(ini, f+aux, p):
print(i, end=' ')
sleep(0.5)
print('FIM')
contador(1, 10, 1)
contador(10, 0, 2)
print('--- Personalize o contador ---')
inicio = int(input('Inicio: '))
fim = int(input('Fim: '))
pulo = int(input('Pulo: '))
contador(inicio, fim, pulo)
|
a63c4ac84215d38df5a5db91f42ffc264e3b6a38 | yugin96/cpy5python | /practical01/q7_generate_payroll.py | 1,197 | 4.21875 | 4 | #filename: q7_generate_payroll.py
#author: YuGin, 5C23
#created: 21/01/13
#modified: 22/01/13
#objective: Obtain a user's number of hours worked weekly, hourly pay, and CPF contribution, and hence calculate his net pay
#main
#prompt user input of name
name = input('Enter name: ')
#prompt user input of hours worked weekly
work_hours = int(input('Enter number of hours worked weekly: '))
#prompt user input of hourly pay
hourly_pay = float(input('Enter hourly pay in dollars: '))
#prompt user input of CPF contribution
CPF_rate = int(input('Enter CPF contribution rate (%): '))
#calculate gross and net weekly pay
gross_pay = hourly_pay * work_hours
net_pay = gross_pay * (1 - (CPF_rate / 100))
#calculate CPF contribution amount
CPF_amount = gross_pay * (CPF_rate / 100)
#output payroll statement
print('')
print('Payroll statement for ' + name)
print('Number of hours worked in week: ' + str(work_hours))
print('Hourly pay rate: $' + str('{0:.2f}'.format(hourly_pay)))
print('Gross pay = $' + '{0:.2f}'.format(gross_pay))
print('CPF contribution at ' + str(CPF_rate) + '% = $' + str('{0:.2f}'.format(CPF_amount)))
print('')
print('Net pay = $' + '{0:.2f}'.format(net_pay))
|
605d5956e4692c98543975a5168dcac57d235151 | jj1of62003/inital | /DandC.py | 656 | 3.609375 | 4 | #!/bin/python
class node:
def __init__(self):
self.right = None
self.left = None
def msort1(numList):
msort(numList, 0, len(numList) - 1)
def msort(numList, first, last):
"""This is the initiator for the Merg sort algorithm"""
listLen = len(numList)
if first < last:
middle = listLen // 2
msort(numList, first, middle)
msort(numList, middle + 1, last)
merg(numList, first, middle, last)
def merg(numList, first, middle, last):
L = numList[first:middle]
R = numList[middle:last + 1]
i, j = 0
for k in range(first, last + 1):
if L[i] < R[j]:
numList[k] = L[i]
i += 1
else:
numList[k] = R[j]
j += 1
return numList
|
c48b953f00f758701c26e38cbe8e251efa1b656b | Keshpatel/Python-Basics | /PythonBasicsExamples/PrintObjects.py | 544 | 4.09375 | 4 | # string representation of class object:
# Object printing concept:
class Test:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "x:%s y:%s" % (self.x, self.y)
def __str__(self):
return "value of a is %s and y is %s" %(self.x, self.y)
# Test Code:
# if there are both method then str will get consider .
# if there is no str method then it will call repr method
# if both str and repr both method is not available then it will give an error .
#
t= Test(10, 20)
print(t) |
7aa44710412f91a454617ede9a156b5a0962d177 | dcsm8/Udemy-Python-Course | /2. Functions and Loops in Python/class_25.py | 546 | 3.96875 | 4 |
cars = ['ok', 'ok', 'ok', 'ok', 'faulty', 'ok', 'ok']
for car_status in cars:
if car_status == 'faulty':
print('Stopping the production line!')
break
print(f'This car is {car_status}.')
for num in range(2, 10):
if num % 2 == 0:
print(f'Found an even number, {num}')
continue
print(f'Found a number, {num}')
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(f'{n} equals {x} * {n//x}')
break
else:
print(f'{n} is a prime number')
|
6b7751d8862cee4aa89812aefeb60b58b76bb5c9 | vadim900/cool | /Індивідуальний проект/data_service.py | 2,414 | 3.828125 | 4 |
def get_goods():
""" повертає вміст файла 'dovidnuk.txt` у вигляді списка
Returns:
'from_file' - список рядків файла
"""
with open('./data/dovidnuk.txt', encoding="utf8") as goods_file:
from_file = goods_file.readlines()
# накопичувач товару
goods_list =[]
for line in from_file:
line_list = line.split(';')
goods_list.append((line_list))
return goods_list
def get_prices():
with open('./data/runok.txt', encoding="utf8") as prices_file:
from_file = prices_file.readlines()
prices_list = []
for line in from_file:
line_list = line.split(';')
prices_list.append(line_list)
return prices_list
def show_goods(goods):
"""виводить список товарів
Args:
goods (list): список товару
"""
# задати інтервал виводу
goods_code_from = int(input("З якого кода товару? "))
goods_code_to = int(input("По який код товару? "))
# накопичує кількість виведених рядків
kol_lines = 0
for goods in goods:
if goods_code_from <= int(goods[0]) <= goods_code_to:
print("код: {:3} назва: {:16} кг: {:20}".format(goods[0], goods[1], goods[2]))
kol_lines += 1
# перевірити чи був вивід хоча б одного рядка
if kol_lines == 0:
print("По вашому запиту товарів не знайдено!")
def show_prices(prices):
prices_code_from = int(input("З якого коду? "))
prices_code_to = int(input("По який? "))
kol_lines = 0
for price in prices:
if prices_code_from <= int(price[0]) <= prices_code_to:
print("код: {:5} назва: {:5} кг на 2 число: {:5} на 10: {:5} на 14: {:5} на 24: {:5} місяць: {:5}".format(price[5], price[1],price[2],price[3],price[4],price[5],price[6]))
kol_lines += 1
if kol_lines == 0:
print("По вашому запиту не знайдено")
if __name__ == "__main__":
goods = get_goods()
show_goods(goods)
prices = get_prices()
show_prices(prices)
|
e583efce261779ccd5f68c25370f629ca5af22cc | sanjitroy1992/PythonCodingTraining | /Mains/decorator.py | 545 | 4.15625 | 4 | #1. How about you create a function using which you could call another function.
def f1(func):
def wrapper():
print("Before")
func()
print("ended")
return wrapper
#let's write a small function to print a value
@f1
def f():
print("Hi")
# f()
#2. let's write a function to add two numbers
def f2(func):
def wrapper(*args, **kwargs):
print("Before")
val = func(*args, **kwargs)
print("after")
return val
return wrapper
@f2
def add(x,y):
return x+y
print(add(2,3))
|
13263119c0b6283fe42fd719566701765ffb0af4 | anand14327sagar/Python_Learning | /IO.py | 115 | 3.84375 | 4 | # Python program showing simple I/O operation
name = raw_input("Enter your name : ")
print("Welcome "+name) |
219b3930cced2de9146cbd4c1d9c998beb672073 | purcellconsult/JNPR_Fundamentals | /day3-random.py | 1,052 | 3.96875 | 4 | from random import choice
import string
import random
first_name = ['Deen','John','Steve','Bruce','Sean']
last_name = ['Osaka','Marc','Mario','Dan','Anthony']
for x in range(2):
random_name = '{} {}'.format(choice(first_name),choice(last_name))
print(random_name)
## another way ....
email_service = ['gmail','hotmail','yahoo','outlook','aol']
rand_digit = random.randint(0,9)
rand_digit1 = random.randint(0,9)
rand_digit2 = random.randint(0,9)
for x in range(20):
first,last = choice(first_name), choice(last_name)
#random_name = f'{first} {last}'
#print(random_name)
random_mail_service = choice(email_service)
random_mail_per_user = '{}.{}@{}.com'.format(first,last,random_mail_service)
random_phone_number = '{}{}{}-{}{}{}-{}{}{}'.format(rand_digit,rand_digit1,rand_digit2,rand_digit,rand_digit1,rand_digit,rand_digit2,rand_digit,rand_digit)
random_phone_number = '{}-{}-{}'.format(random.randint(9),random.randint(9),random.randint(9))
print(random_mail_per_user," Phone number: ",random_phone_number)
|
6a77431ed971a411d27497e50730a50174576601 | ml-resources/neuralnetwork-programming | /ch01/linear-equation.py | 1,415 | 3.578125 | 4 | import tensorflow as tf
# linear equation is represented by
# ax + b = y
# y - ax = b
# y/b - a/b(x) = 1
# x, y is known and can be represented as X matrix, goal is to find a and b
# therefore we can represent the above goal as AX = B where X is the input matrix, A is the unknown(a,b) and B is all ones
# example
# 3x+2y = 15
# 4x−y = 10
# equation 1
x1 = tf.constant(3, dtype=tf.float32)
y1 = tf.constant(2, dtype=tf.float32)
point1 = tf.stack([x1, y1])
# equation 2
x2 = tf.constant(4, dtype=tf.float32)
y2 = tf.constant(-1, dtype=tf.float32)
point2 = tf.stack([x2, y2])
# solve for AX=C
X = tf.transpose(tf.stack([point1, point2]))
C = tf.ones((1,2), dtype=tf.float32)
A = tf.matmul(C, tf.matrix_inverse(X))
with tf.Session() as sess:
X = sess.run(X)
print(X)
A = sess.run(A)
print(A)
b = 1 / A[0][1]
a = -b * A[0][0]
print("Hence Linear Equation is: y = {a}x + {b}".format(a=a, b=b))
# canonical circle equation
# x2+y2+dx+ey+f = 0
# dx+ey+f=−(x2+y2) ==> AX = B
# we have to solve for d, e, f
points = tf.constant([[2,1], [0,5], [-1,2]], dtype=tf.float64)
X = tf.constant([[2,1,1], [0,5,1], [-1,2,1]], dtype=tf.float64)
B = -tf.constant([[5], [25], [5]], dtype=tf.float64)
A = tf.matrix_solve(X,B)
with tf.Session() as sess:
result = sess.run(A)
D, E, F = result.flatten()
print("Hence Circle Equation is: x**2 + y**2 + {D}x + {E}y + {F} = 0".format(**locals()))
|
93bb6728d812b31f74d8b5d959da845e58e64b40 | basoares/coursera-ml-py-exercises | /ex1/computeCost.py | 785 | 4.1875 | 4 | '''
Stanford Machine Learning (Coursera) - Python
ComputeCost example function
ComputeCost(X, y, theta) is a function that computes cost of using theta as
the parameter for linear regression to fit the data points in X and y
Released under the MIT License <http://opensource.org/licenses/mit-license.php>
'''
__version__ = '0.1'
__all__ = ['computeCost']
def computeCost(X, y, theta):
# Initialize some useful values
m = y.size
# You need to return the following variables correctly
J = 0;
# ====================== YOUR CODE HERE ======================
# Instructions: Compute the cost of a particular choice of theta
# You should set J to the cost.
# =========================================================================
return J
|
ebf96e7a2434f704fb37405c768a16f030a28a9e | ashrafulk/fire-detection | /mod1.py | 392 | 3.734375 | 4 | class cal:#modules
add =lambda a,b:a+b
def fact(n):
if n <=1:
return 1
else:
return n*cal.fact(n-1)
def prime(n):
for i in range(2,n):
if n%i==0:
print("its not prime")
break
else:
print("its prime number")
class cal1:
mul=lambda a,b:a*b
|
8b2171e10476822318987e7acf71b77fe848a894 | Seemant-tiger/housing-price-prediction | /src/ta_lib/_vendor/tigerml/core/utils/reports.py | 269 | 3.5625 | 4 | import os
def get_extension_of_path(path):
_, ext = os.path.splitext(os.path.basename(path))
return ext
def append_file_to_path(path, file_name):
if get_extension_of_path(path):
return path
else:
return os.path.join(path, file_name)
|
4fe6706fbcd2a80e6d02d87e08b092dedfab28d5 | Hasib104/Learning-Python | /Day004/1.Randomisation.py | 529 | 3.9375 | 4 | """#Importing Module"""
# import my_module
# print(my_module.pi)
import random
"""#Random Generator"""
# random_int = random.randint(1, 100)
# print(random_int)
"""#Manipulating result of random generator using seed"""
# random.seed(8)
# random_int = random.randint(1, 10)
# print(random_int)
"""#Heads or Tail"""
test_seed=int(input("Enter a seed number: "))
print(test_seed)
random.seed(test_seed)
flip= random.randint(0, 1)
print(flip)
if flip == 1:
print("Heads")
else:
print("Tail")
|
53461266ed2c6ebfa9e97d98ff8d491f0cec4364 | Ezi4Zy/leetcode | /24.两两交换链表中的节点.py | 818 | 3.640625 | 4 | #
# @lc app=leetcode.cn id=24 lang=python
#
# [24] 两两交换链表中的节点
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy_node = ListNode(0, head)
pre_node = dummy_node
while pre_node.next and pre_node.next.next:
next1_node = pre_node.next
next2_node = pre_node.next.next
next1_node.next = next2_node.next
pre_node.next = next2_node
next2_node.next = next1_node
pre_node = next1_node
return dummy_node.next
# @lc code=end
|
c39bca24adf4edcdb001bf7ed7e7cf0b051f5fec | krokhalev/GeekBrains | /Lesson1/Number1.py | 979 | 4.09375 | 4 |
variableOne = 1 # Создал первую переменную.
variableTwo = 2 # Создал вторую переменную.
print (variableOne, variableTwo) # Вывел на экран.
numberOne = input("Введи первое число.\n") # Запросил первое число, сохранил в переменную.
numberTwo = input("Введи второе число.\n") # Запросил второе число, сохранил в переменную.
textOne = input("Введи первый текст.\n") # Запросил первый текст, сохранил в переменную.
textTwo = input("Введи второй текст.\n") # Запросил второй текст, сохранил в переменную.
print("Первое число: " + numberOne, "\nВторое число: " + numberTwo, "\nПервый текст: " + textOne, "\nВторой текст: " + textTwo) # Вывел на экран. |
613f344965926d791953e9b9b212cdd7db6d797c | pengyang0106/python | /day24.py | 327 | 3.796875 | 4 | def calc_profit(n):
price = 24
cost = 8
profit = (price - cost) * n - 500
return profit
def calc_perf(profit):
if profit > 2000:
print('合格')
else:
print('不合格')
n = int(input('请输入今天咖啡店的销量'))
print(calc_profit(n))
profit = calc_profit(n)
calc_perf(profit) |
401f697ebeb6ee12edbbf226b9bbf89049b5733d | NutthanichN/grading-helper | /week_6/6210545530_lab6.py | 12,969 | 4.15625 | 4 |
# 1
def ll_sum(a, b, c):
"""Return sum of the all integers in the lists.
Args:
a (list): list one.
b (list): list two.
c (list): list three.
Returns:
int: the sum of all the number in the input lists.
Examples:
>>> ll_sum([1,2], [3], [4,5,6])
21
>>> ll_sum([2,0], [0], [0,1])
3
>>> ll_sum([2,0], [], [])
2
>>> ll_sum([2,0], ['a'], [9,8])
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> ll_sum([], [], [])
0
"""
list_too = []
for i in a:
list_too.append(i)
for j in b:
list_too.append(j)
for k in c:
list_too.append(k)
return sum(list_too)
# 2
def cumulative_sum(sth):
"""Return a list which contains the same integers but plus all the integers that come before it.
Args:
sth (list): an input list.
Returns:
list: a new list contains the same integers but plus all the integers that come before it.
Examples:
>>> cumulative_sum([1, 2, 3])
[1, 3, 6]
>>> cumulative_sum([3, 2, 1])
[3, 5, 6]
>>> cumulative_sum([8, 45, 700])
[8, 53, 753]
>>> cumulative_sum([-1, -3, -5])
[-1, -4, -9]
>>> cumulative_sum([8, 0, -10])
[8, 8, -2]
"""
new = []
count = 0
for num in sth:
count += num
new.append(count)
return new
# 3
def middle(list_a):
"""Return a new list that is the old list but excluded the first and
the last element of the old list.
Args:
list_a (list): an input list.
Returns:
list: a new list that excluded the first and the last element of the old list.
Examples:
>>> middle([1, 2, 3, 4])
[2, 3]
>>> middle([1, 3, 5, 7, 'e', 444, 5])
[3, 5, 7, 'e', 444]
>>> middle(['a','b','c','gg','k'])
['b', 'c', 'gg']
>>> middle(['a','b'])
[]
>>> middle(['a'])
[]
"""
new = []
for num in list_a[1:-1]:
new.append(num)
return new
# 4
def chop(t):
"""Return None
Args:
t (list): an input list.
Returns:
None
Examples:
>>> t = [1, 2, 3, 4]
>>> chop(t)
>>> t
[2, 3]
>>> w = ['a', 'b', 'c']
>>> chop(w)
>>> w
['b']
>>> b = ['a', 2, 'b', 3]
>>> chop(b)
>>> b
[2, 'b']
>>> chop('a')
Traceback (most recent call last):
...
AttributeError: 'str' object has no attribute 'pop'
>>> chop([2, 'e', 4])
"""
t.pop(0)
t.pop(-1)
return
# 5
def is_sorted(a_list):
"""Return True if the list is sorted, False if it's not.
Args:
a_list (list): an inout list.
Returns:
bool: True if the list is sorted, False if it's not.
Examples:
>>> is_sorted([1, 2, 2])
True
>>> is_sorted(['b', 'a'])
False
>>> is_sorted([0, 0, 0])
True
>>> is_sorted([-1, -2, 0, 1, 10])
False
>>> is_sorted([1, 2, 3, 'a', 'b', 'c'])
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
new = []
for element in a_list:
new.append(element)
a_list.sort()
return True if new == a_list else False
# 6
def front_x(a_list):
"""Return a list with the strings in sorted order, except group all the strings
that begin with 'x' first.
Args:
a_list (list): an input list.
Returns:
list: a new list which is a sorted list of the original list and
group all the strings that begin with 'x' first.
Examples:
>>> front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark'])
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
>>> front_x(['xerox', 'xa', 'cd', 'ab'])
['xa', 'xerox', 'ab', 'cd']
>>> front_x(['x456', 'x123', 'a01w', 'aw01'])
['x123', 'x456', 'a01w', 'aw01']
>>> front_x(['456', '123', 'a', '-2', 'x'])
['x', '-2', '123', '456', 'a']
>>> front_x(['x', 'xx', 'xy', 'xxxx'])
['x', 'xx', 'xxxx', 'xy']
"""
new_x = []
new_others = []
for sth in a_list:
if sth[0] == 'x':
new_x.append(sth)
else:
new_others.append(sth)
new_x.sort()
new_others.sort()
return new_x+new_others
# 7
def even_only(list_one):
"""Return a new list that contains only even numbers.
Args:
list_one (list): an input list.
Returns:
list: a new list that has only even number.
Examples:
>>> even_only([3, 1, 4, 1, 5, 9, 2, 6, 5])
[4, 2, 6]
>>> even_only([12, 3, 4, 5, 6, 7, 8, 9, 10])
[12, 4, 6, 8, 10]
>>> even_only(['a', 'b', 4, 5, 6])
Traceback (most recent call last):
...
TypeError: not all arguments converted during string formatting
>>> even_only([])
[]
>>> even_only([0])
[0]
"""
new = []
for num in list_one:
if num % 2 == 0:
new.append(num)
else:
pass
return new
# 8
def love(a_string):
"""Return a new string which is the same as the old string but the second last word
was changed to 'love'.
Args:
a_string (str): a string that needed the word change.
Returns:
str: a new string that the second last word was changed to 'love'.
Examples:
>>> love("I like Python")
'I love Python'
>>> love("I really like Python")
'I really love Python'
>>> love("IlikePython")
Traceback (most recent call last):
...
IndexError: list assignment index out of range
>>> love("like like, like like ,,")
'like like, like love ,,'
>>> love(1)
Traceback (most recent call last):
...
AttributeError: 'int' object has no attribute 'split'
"""
list_one = a_string.split()
list_one[-2] = 'love'
new = " ".join(list_one)
return new
# 9
def is_anagram(one, two):
"""Return True if the two input strings are anagrams.
Args:
one (str): string one.
two (str): string two.
Returns:
bool: True if the two input strings are anagrams.
Examples:
>>> is_anagram('arrange', 'Rear Nag')
True
>>> is_anagram('I m', 'im')
True
>>> is_anagram('234', '432')
True
>>> is_anagram('HIGH AND LOW', 'high and low')
True
>>> is_anagram('almost alike', 'almost alike.')
False
"""
one_use = one.lower()
two_use = two.lower()
list_one = []
list_two = []
for char in one_use:
list_one.append(char)
for ch in two_use:
list_two.append(ch)
if " " in list_one:
list_one.remove(" ")
if " " in list_two:
list_two.remove(" ")
list_one.sort()
list_two.sort()
return True if list_one == list_two else False
# 10
def has_duplicates(a_list):
"""Return True if there is any element that appears more than once.
Args:
a_list (list): an input list.
Returns:
bool: True if there is any element that appears more than once in the list.
Examples:
>>> has_duplicates([1, 2, 3, 4, 5])
False
>>> has_duplicates([1, 2, 3, 4, 5, 2])
True
>>> has_duplicates([0, 'a', 'b', 'a', 1])
True
>>> has_duplicates([])
False
>>> has_duplicates(['Hey', 'lets', 'try', 'Hey'])
True
"""
new = []
for num in a_list:
if num in new:
pass
else:
new.append(num)
return True if a_list != new else False
# 11
def average(nums):
"""Return the mean average of a list of numbers.
Args:
nums (list): an input list.
Returns:
float: average value of the numbers in the list.
Examples:
>>> average([1, 1, 5, 5, 10, 8, 7])
5.285714285714286
>>> average([0, 0, 1])
0.3333333333333333
>>> average([0])
0.0
>>> average([])
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
>>> average([-2, -1, 0, 5, 8])
2.0
"""
return sum(nums)/len(nums)
# 12
def centered_average(nums):
"""Return the mean average of the values that ignores the largest and
smallest values in the list.
Args:
nums (list): a list of numbers.
Returns:
float: average value of all the values in the list except the largest and smallest values.
Examples:
>>> centered_average([1,1,5,5,10,8,7])
5.2
>>> centered_average([10, 10, 3, 6, 7, -3])
6.5
>>> centered_average([0, 0, 0, 0])
0.0
>>> centered_average([1,2])
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
>>> centered_average([1,2,3])
2.0
"""
nums.sort()
nums.remove(nums[0])
nums.remove(nums[-1])
return sum(nums)/len(nums)
# 13
def reverse_pair(string_a):
"""Return the reverse pair of the input sentence.
Args:
string_a (str): an input string.
Returns:
str: a new string that is a reverse pair of the original string.
Examples:
>>> reverse_pair('May the fourth be with you')
'you with be fourth the May'
>>> reverse_pair('Hi this is a test')
'test a is this Hi'
>>> reverse_pair('a b c d e f g')
'g f e d c b a'
>>> reverse_pair('first last')
'last first'
>>> reverse_pair('one')
'one'
"""
list_a = string_a.split()
return " ".join(list_a[::-1])
# 14
def match_ends(a_list):
"""Return the number of strings which the string length is 2 or more and
the first and last character of the string are the same.
Args:
a_list (list): an input list.
Returns:
int: number of strings which the string length is 2 or more and the first and
last character of the string are the same.
Examples:
>>> match_ends(['Gingering', 'hello', 'wow'])
2
>>> match_ends(['i', 'l', 't'])
0
>>> match_ends(['0iii0', 'lll', 'ttt'])
3
>>> match_ends(['More', 'than', 'three', 'is', 'fine', 'too', '!!'])
1
>>> match_ends(['vvvvvvv', 'jjason'])
1
"""
count = 0
for sth in a_list:
if len(sth) >= 2:
if (a_list[a_list.index(sth)][0]).lower() == (a_list[a_list.index(sth)][-1]).lower():
count += 1
else:
pass
else:
pass
return count
# 15
def remove_adjacent(a_list):
"""Return a list where all adjacent elements have been reduced to a single element.
Args:
a_list (list): an input list.
Returns:
list: a new list that all adjacent elements have been reduced to a single element.
Examples:
>>> remove_adjacent([1, 2, 2, 3])
[1, 2, 3]
>>> remove_adjacent([1, 2, 3, 4, 5, 6, 8, 4, 4, 57 ,6 ,4 ,4 ,5])
[1, 2, 3, 4, 5, 6, 8, 4, 57, 6, 4, 5]
>>> remove_adjacent(['list', 'list', 'of', 'strings'])
['list', 'of', 'strings']
>>> remove_adjacent(['list', 'list', 0, 0, 1, 'mix'])
['list', 0, 1, 'mix']
>>> remove_adjacent([1, 1, 1, 1, 1, 1, 1])
[1]
"""
new = [a_list[0]]
for element in a_list:
if element == new[-1]:
pass
else:
new.append(element)
return new
# if __name__ == '__main__':
# import doctest
#
# doctest.testmod(verbose=True)
|
0413ee082f65e5ec041a182fd94d98903ab2e493 | LeonardoSaid/uri-py-solutions | /submissions/1051.py | 341 | 3.921875 | 4 | x = float(input(""))
if x <= 2000.0:
print("Isento")
elif x <= 3000.0:
salario = ( x - 2000.0 ) * 0.08
print("R$ %.2f" % salario)
elif x <= 4500:
salario = 0.08*1000 + ( x - 3000 ) * 0.18
print("R$ %.2f" % salario)
else:
salario = 0.08*1000 + 0.18*1500 + ( x - 4500 ) * 0.28
print("R$ %.2f" % salario) |
9daf9844007abb54e9b50610fdb8af500532087a | Rahul664/Pyhton_functional_code_snippets | /Python_Assignment_2/54.py | 472 | 3.625 | 4 | import time
try:
name = input("Enter your name:")
print("you entered: " + name)
except KeyboardInterrupt:
print( "Keyboard interrupt you hit ctrl-c")
i=1
try:
while(i<5):
time.sleep(1)
print (i)
i += 1
except KeyboardInterrupt:
print( "Keyboard interrupt")
try:
print ("Hi" +" "+ n)
except NameError:
print ("variable n is not defined or name error")
#arithmetic error
try:
a=89/0
except ArithmeticError:
print ("Division by zero error")
|
ff47b810fc153d3e49dbc62779b90fdfcf0d9dc0 | rjraiyani/Repository2 | /arrow.py | 80 | 3.671875 | 4 | N = int(input('Please enter your number ' ))
arrow = '-' * N + '>'
print(arrow)
|
f70553987465b9d012012209a1c11e65030c3477 | haell/AulasPythonGbara | /mundo_TRES/ex099.py | 1,047 | 3.8125 | 4 | # Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros.
# Seu programa tem que analisar todos os valores e dizer qual deles é o maior.
from time import sleep
from ex098 import linha
def gera_param(qtd_digitos):
from random import randint
numeros = list()
for i in range(int(qtd_digitos)):
n = randint(0, 100)
numeros.append(n)
return numeros
def maior(*param):
print(f"Analisando os valores passados...")
if not param or not param[0]:
sem_valor = 'Foi informado 0 ou nenhum valor.'
print(sem_valor)
else:
for i in param[0]:
print(f"{i}", end=' ')
sleep(0.5)
maior_valor = max(param[0])
print(f"Foram informados {len(param[0])} valores ao todo.")
print(f"O maior valor informado foi {maior_valor}")
linha()
maior(gera_param(6))
sleep(0.5)
maior(gera_param(3))
sleep(0.5)
maior(gera_param(2))
sleep(0.5)
maior(gera_param(1))
sleep(0.5)
maior()
|
421f472b5e756607786c7e8cd7d871c9b0cf9ab9 | leor/python-algo | /Lesson1/Task8/code.py | 539 | 3.8125 | 4 | year = int(input("Введите год (например 1970): "))
# вариант 1
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Год високосный")
else:
print("Год не високосный")
else:
print("Год високосный")
else:
print("Год не високосный")
# вариант 2
import calendar
if calendar.isleap(year):
print("Год високосный")
else:
print("Год не високосный")
|
9d0fe12e7136033934de45a10bc2b2ee53fcb1d2 | leofdss/busca-em-largura | /arvore.py | 771 | 3.78125 | 4 | class Node(object):
def __init__(self, key):
self.key = key
self.children = None
self.dad = ''
def BFS(self, key):
print('\n-----------Busca-----------')
return _BFS([self], key)
def _BFS(nodes, key):
filhos = []
if nodes:
for item in nodes:
print(item.key)
if item.key == key:
print('-----------Fim da Busca-----------')
return item
elif item.children:
i = 0
while i < len(item.children):
item.children[i].dad = item.key
i += 1
filhos += item.children
print('Proxima camada')
return _BFS(filhos, key)
else:
return None
|
323a13f44e40e887ace111dc5a42ec5d17576cc6 | genuinenameerror/algorithm-week2 | /nonsequential.py | 322 | 3.953125 | 4 | finding_target = 9
finding_numbers = [0, 3, 5, 6, 1, 2, 4]
def is_exist_target_number_binary(target, numbers):
# 이 부분을 채워보세요!
for i in numbers:
if i==target:
return True
return False
result = is_exist_target_number_binary(finding_target, finding_numbers)
print(result)
|
5cd23f58faeab5288c8c97bef9721f7bc0349b0e | imvivek71/LearningPython | /Examples/PrintingIdentityMatrix.py | 171 | 3.796875 | 4 | n=input("Enter the size of matrix")
for i in range(0,n):
for j in range(0, n):
if i==j:
print "1 ",
else:
print "0 ",
print |
e4fc1728dfcc2f166d3eb3696d2f1fccaaf7469e | hi2gage/csci127 | /Programs/program6/test2.py | 415 | 3.59375 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
csv_data = pd.read_csv("airlines.csv")
data_frame_line = pd.DataFrame(data = csv_data, columns=['Diverted', 'Cancelled','Delayed', 'Year'])
df = data_frame_line.groupby('Year')['Delayed','Cancelled'].sum()
ax = df.plot(secondary_y='Delayed')
ax.set_ylabel('# of Cancelled Flights')
ax.right_ax.set_ylabel('# of Delayed Flights')
plt.show()
|
82b674c58a027347ea3a53c66ea475cf55afe3c2 | alvinkgao/leetcode_solutions | /Python3/101.Symmetric_Tree.py | 1,279 | 3.9375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
return self.isSymmetricHelper(root, root)
def isSymmetricHelper(self, left: TreeNode, right: TreeNode) -> bool:
if left == None and right == None:
return True
if left == None or right == None:
return False
return left.val == right.val and self.isSymmetricHelper(left.left, right.right) and self.isSymmetricHelper(left.right, right.left)
def isSymmetricIter(self, root: TreeNode) -> bool:
queue = deque()
queue.append(root)
queue.append(root)
while(queue):
right = queue.popleft()
left = queue.popleft()
if left == None and right == None:
continue
if left == None or right == None:
return False
if left.val != right.val:
return False
queue.append(left.left)
queue.append(right.right)
queue.append(left.right)
queue.append(right.left)
return True |
3dbe47c222f4cdad2bdf9ef0e822ae3015b37df2 | Aditya7256/Demo | /Recursion in Python.py | 245 | 4.0625 | 4 | # Recursion in python:
def my_function(k):
if k > 0:
result = k + my_function(k - 1)
print(result)
else:
result = 0
return result
print("\n\nrecursion Example Results")
my_function(10)
|
b6e2f222d980336a625af2b818094cf0b12294aa | gupta93/TemplatesForAlgorithm | /0-1knapsack.py | 808 | 3.65625 | 4 | def knapsack(weights,values,maximum_weight):
heightOfTable = len(values)
weightTable = [[0 for x in xrange(maximum_weight+1)] for y in xrange(heightOfTable)]
for column in xrange(weights[0],maximum_weight+1):
weightTable[0][column]=values[0]
for row in xrange(1,heightOfTable):
for column in xrange(maximum_weight+1):
if column>=weights[row]:
weightTable[row][column]=max(values[row]+weightTable[row-1][column-weights[row]],weightTable[row-1][column])
else:
weightTable[row][column]=weightTable[row-1][column]
return weightTable
def traceElementsOfWeights(weights,weightTable,maximum_weight):
heightOfTable = len(weights)
for row in xrange(heightOfTable,0,-1):
if
knapsack([1,3,4,5],[1,4,5,7],7) |
57c39bbfa3088293863f3f8f27128a899d3ac24e | AhhhHmmm/MITx-6.00.1x | /Week 2/palinRecur.py | 342 | 3.921875 | 4 | word = 'oHahO'
def processWord(word):
tempWord = ''
for letter in word:
if letter.isalpha():
tempWord += letter
tempWord = tempWord.lower()
return tempWord
def palinRecur(word):
if len(word) == 0 or len(word) == 1:
return True
else:
return word[0] == word[-1] and palinRecur(word[1:-1])
print(palinRecur(processWord('ohO'))) |
56a1424436b02be4bb109f2a137438469c4d0963 | dooma/backtrack | /lib/backtrack.py | 5,423 | 4.03125 | 4 | __author__ = 'Călin Sălăgean'
class Backtrack():
'''
Class provides permutations of any list with a specified rule. Every rule should be implemented
Candidate list is a list with unique elements
'''
def __init__(self, array):
'''
Class constructor
:param array: The list that should be reordered
:return:
'''
self.validate(array)
self.__array = array
self.__result = []
self.__permutation = []
@staticmethod
def validate(array):
'''
Validation method
:param array:
:return:
:raise AttributeError: If array is not a list
:raise ValueError: If elements from array are not integers or floats
'''
if type(array) is not list or not len(array):
raise AttributeError("'input' attribute should be a list")
for elem in array:
try:
int(elem)
float(elem)
except ValueError:
error_message = "The element on position {} should be integer or float number".format(array.index(elem))
raise ValueError(error_message)
@property
def array(self):
'''
:return: List provided at constructor
'''
return self.__array
@property
def result(self):
'''
:return: List with results
'''
return self.__result
def reset_result(self):
'''
Initialize result with empty list. Needed if don't want to append to already generated solutions
:return: None
'''
self.__result = []
@property
def minimum_value(self):
'''
:return: Minimum value from array
'''
return min(self.__array)
def determine(self, index = 0, method = 'valley'):
'''
Generates all solutions for given method.
Implements backtracking algorithm using recursive call.
:param index: Position in array
:param method: Given algorithm that a candidate list should match to be a solution
:return: None
'''
if index == len(self.array):
if getattr(self, method)():
self.__result.append(self.construct_permutation())
else:
for elem in range(len(self.array)):
if not elem in self.__permutation:
self.__permutation.append(elem)
self.determine(index + 1)
self.__permutation.pop()
def determine_inline(self, method = 'valley'):
'''
Generates all solutions for given method.
Implements backtracking algorithm using recursive call.
:param method: Given algorithm that a candidate list should match to be a solution
:return: None
'''
self.__permutation = [-1]
while len(self.__permutation):
choosed = False
elem = self.__permutation[-1]
while not choosed and elem < len(self.__array) - 1:
elem += 1
choosed = elem not in self.__permutation
if choosed:
self.__permutation.pop()
self.__permutation.append(elem)
if len(self.__permutation) == len(self.__array) and getattr(self, method)():
self.__result.append(self.construct_permutation())
self.__permutation.append(-1)
else:
self.__permutation.pop()
def valley(self):
'''
Algorithm to match the candidate list in valley order.
It should be in descending order and ascending order, no other posibilities allowed.
:return: Bool
'''
array = self.construct_permutation()
start = array.index(self.minimum_value)
array.reverse()
end = len(array) - array.index(self.minimum_value)
array.reverse()
descend = array[ : start]
constant = array[start : end]
ascend = array[end : ]
condition = self.issorted(descend, reverse=True) \
and self.issorted(ascend) \
and constant == self.minimum_array(end - start) \
and len(descend) \
and len(ascend)
return condition
def construct_permutation(self):
'''
Creates a solution list using generated positions and values provided in constructor
:return: List
'''
permutation = []
for elem in self.__permutation:
permutation.append(self.__array[elem])
return permutation
@staticmethod
def issorted(array, reverse=False):
'''
Checks if porivided list is sorted.
Faster than sorted(list) == list
:param array: List that should be checked
:param reverse: Parameter for direction
:return:
'''
for index in range(1, len(array)):
if reverse and array[index - 1] < array[index]:
return False
elif not reverse and array[index - 1] > array[index]:
return False
return True
def minimum_array(self, count):
'''
Generates an array with middle element in the lowest position of valley
:param count: Number of minimum elements included
:return:
'''
return [self.minimum_value] * count |
c96f980d7d731f319947d295738fb787f8584428 | tskaro/unihero | /populate.py | 834 | 3.578125 | 4 | import sqlite3
items = [
{"id": 1, "name": "Jedi Starfighter", "speed": 1, "arm": 1, "capacity": 15, "quantity": 11},
{"id": 2, "name": "Starship Enterprise", "speed": 15, "arm": 9, "capacity": 3000, "quantity": 6},
{"id": 3, "name": "Millennium Falcon", "speed": 18, "arm": 10, "capacity": 10, "quantity": 8},
{"id": 4, "name": "super galaxy gurren lagann", "speed": 30, "arm": 10, "capacity": 10000, "quantity": 1}
]
list = []
for item in items:
(*values,) = item.values()
list.append((*values,))
connection = sqlite3.connect("data.db")
cursor = connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS ships (id INTEGER PRIMARY KEY, name text, speed integer, arm integer, capacity integer, quantity integer)')
query_string = "INSERT INTO ships VALUES(?, ?, ?, ?, ?, ?)"
cursor.executemany(query_string, list)
connection.commit()
connection.close()
|
3d1a07c60461370a22729b4e6b0d0e9f4557c0d0 | nikileeyx/objectOrientedProgramming | /7002_theCar.py | 428 | 3.546875 | 4 | class Car:
def __init__(self, brand, colour, speed):
self.brand = brand
self.colour = colour
self.speed = speed
def whoAmI(self):
print("Hi I am a " + self.colour + " car")
def upgrade(self, speed):
speed += 10
print("Your speed has increased by " + str(self.speed))
return speed
'''
Pass in to Python Shell these commands
car = Car("hello", "yellow", "10")
car.whoAmI()
'''
|
da935e4b4081b151278414c7a574c9fba4343147 | yawzyag/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 133 | 3.828125 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
st = set(my_list)
num = 0
for i in st:
num = num + i
return num
|
5284a6a31f1ed1f74418c3817173533c91d42893 | s2motion/python-cookbook | /src/2/matching_and_searching_for_text_patterns_using_regular_expressions/example_practice.py | 905 | 4.53125 | 5 | # example.py
#
# Examples of simple regular expression matching
# Exact Match & Match at start or end & Search for the location of the first occurence
text = 'yeah, but no, but yeah, but no, but yeah'
# Exact Match
print(text == 'yeah')
# >>>False
# Match at start or end
print(text.startswith('yeah'))
# >>>True
print(text.endswith('no'))
# >>>False
#Search for the location of the first occurences
print(text.find('no'))
# >>>10
import re
# Some sample text
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
# # (a) Find all matching dates
datepat = re.compile(r'\d+/\d+/\d+')
print(datepat.findall(text))
# # (b) Find all matching dates with capture groups. convert 2012-11-27
datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
for month, day, year in datepat.findall(text):
print('{}-{}-{}'.format(year, month, day))
# # (c) Iterative search
for m in datepat.finditer(text):
print(m.groups())
|
d70372aa6b6f9fa5470caac68c83ac13fcc5716f | yetanotherbot/leetcode | /13. Roman to Integer/solution.py | 724 | 3.5625 | 4 | class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
romanceDict = {"M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100,
"XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5,
"IV": 4, "I": 1}
result = 0
i = 0
while i < len(s):
if i < len(s) - 1 and s[i] + s[i + 1] in romanceDict:
result += romanceDict[s[i] + s[i + 1]]
i += 2
else:
result += romanceDict[s[i]]
i += 1
return result
if __name__ == '__main__':
so = Solution()
tests = 'MCMXCVI'
print so.romanToInt(tests)
|
2376141f6d5d132d938068860ceda18e75d67f5a | Aman08-forsk/FSDP_2019 | /Day05/regex1.py | 233 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 7 10:44:09 2019
@author: Hp
"""
import re
n=int(input("Enter the numbers:"))
for i in range(n):
s=input("Enter the input:")
print(bool(re.search(r'^[-+.]?[0-9]*\.[0-9]+$',s))) |
12a7909e1aa0dd5f0522c911e65ddbd3da74b8d5 | scaniasvolvos/python-basics | /3d-to-2d.py | 523 | 4.34375 | 4 |
Input = [[[3], [4]], [[5], [6]], [[7], [8]]]
result = []
for i in Input:
for j in i:
result.append(j)
print (result)
'''
# Python code to convert a 3D list into a 2D list
# Input list initialization
Input = [[[3], [4]], [[5], [6]], [[7], [8]]]
# Output list initialization
Output = []
# Using iteration
for temp in Input:
for elem in temp:
Output.append(elem)
# printing output
print("Initial 3d list is")
print(Input)
print("Converted 2d list is")
print(Output)
''' |
57bb81044cbd0e910552d249b3f6dfdf36efd043 | EricAlanPearson/python-challenge | /PyBank/main.py | 2,027 | 3.59375 | 4 | #PyBank
import os
import sys
import csv
#open file and write to file
budget_data = os.path.join(".", "budget_data.csv")
financial_analysis = os.path.join(".", "financial_analysis.txt")
with open (budget_data, "r", newline="") as filehandle:
next(filehandle)
csvreader = csv.reader(filehandle)
# loop
total_months = 0
total_net_amount = 0
monthly_changes = 0
prev_month_amount = 0
current_month_amount = 0
diff_current_prev = 0
greatest_increase = 0
greatest_decrease = 0
current_month = ""
greatest_increase_month = ""
greatest_decrease_month = ""
for row in csvreader:
total_months += 1
current_month = row[0]
current_month_amount = float(row[1])
total_net_amount += current_month_amount
diff_current_prev = current_month_amount - prev_month_amount
if (csvreader.line_num != 1):
monthly_changes += diff_current_prev
if (diff_current_prev > greatest_increase):
greatest_increase = diff_current_prev
greatest_increase_month = current_month
if (diff_current_prev < greatest_decrease):
greatest_decrease = diff_current_prev
greatest_decrease_month = current_month
prev_month_amount = current_month_amount
#calculate average change
average_change = monthly_changes/(total_months-1)
#print file
with open(financial_analysis, "w+") as filehandle:
filehandle.write("Financial Analysis\n")
filehandle.write("-" *32 + "\n")
filehandle.write(f"Total Months: {total_months: .0f}\n")
filehandle.write(f"Total: ${total_net_amount: .0f}\n")
filehandle.write(f"Average Change: ${average_change: .2f}\n")
filehandle.write(f"Greatest Increase in Profits: {greatest_increase_month} (${greatest_increase: .0f})\n")
filehandle.write(f"Greatest Decrease in Profits: {greatest_decrease_month} (${greatest_decrease: .0f})\n")
# print screen
with open(financial_analysis, "r") as filehandle:
print(filehandle.read())
|
0fa89cfbe93a7d26750f7d99371bf14bd4974dc0 | asparagus/chess | /client/fen.py | 3,440 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf8 -*-
"""This module contains functionality for the Forsyth-Edwards Notation."""
import re
class Fen:
"""Static class for dealing with the notation."""
# Initial state in Forsyth-Edwards Notation (FEN)
INITIAL_STATE = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
# Empty square notation for decompressed representation
EMPTY_SQUARE = '-'
def __init__(self, fen=None):
if not fen:
fen = Fen.INITIAL_STATE
data = fen.split(" ")
self.pieces = data[0]
self.active = data[1]
self.castling = data[2]
self.en_passant = data[3]
self.halfmove_clock = int(data[4])
self.fullmove_number = int(data[5])
def get_piece(self, col, row):
"""
Get the piece at the given row and column.
>>> f = Fen()
>>> f.get_piece(0, 0)
'R'
>>> f.get_piece(0, 1)
'P'
>>> f.get_piece(4, 7)
'k'
>>> f.get_piece(4, 4)
"""
rows = self.pieces.split('/')
rows.reverse()
row_pieces = Fen.decompress(rows[row])
piece = row_pieces[col]
return piece if piece != Fen.EMPTY_SQUARE else None
def set_piece(self, col, row, piece):
"""
Set a piece in a given row and column.
>>> f = Fen()
>>> f.set_piece(2, 3, 'B')
>>> f.get_piece(2, 3)
'B'
>>> f.set_piece(0, 0, None)
>>> f.get_piece(0, 0)
"""
if piece is None:
piece = Fen.EMPTY_SQUARE
rows = self.pieces.split('/')
rows.reverse()
row_pieces = Fen.decompress(rows[row])
row_pieces = row_pieces[:col] + piece + row_pieces[col + 1:]
rows[row] = Fen.compress(row_pieces)
rows.reverse()
self.pieces = '/'.join(rows)
@classmethod
def compress(cls, piece_row):
"""
Use numbers to compress the notation for pieces.
>>> Fen.compress("--------")
'8'
>>> Fen.compress("p-P--Bq")
'p1P2Bq'
"""
pattern = '(%s+)' % Fen.EMPTY_SQUARE
while True:
match = re.search(pattern, piece_row)
if match is None:
break
blanks = match.group(0)
piece_row = piece_row.replace(blanks, str(len(blanks)), 1)
return piece_row
@classmethod
def decompress(cls, piece_row):
"""
Transform numbers to - in order to manipulate board pieces easily.
>>> Fen.decompress('8')
'--------'
>>> Fen.decompress('p1P2Bq')
'p-P--Bq'
"""
pattern = r'([0-9])'
while True:
match = re.search(pattern, piece_row)
if match is None:
break
num = match.group(0)
piece_row = piece_row.replace(num, cls.EMPTY_SQUARE * int(num), 1)
return piece_row
def __str__(self):
"""
Return the string representation of this FEN.
>>> f = Fen()
>>> str(f) == Fen.INITIAL_STATE
True
"""
fen = " ".join([
self.pieces,
self.active,
self.castling,
self.en_passant,
str(self.halfmove_clock),
str(self.fullmove_number)
])
return fen
if __name__ == '__main__':
import doctest
doctest.testmod()
|
89b2535e32f30a1e27b4870138b97f72e367bf9a | zzag/codesamples | /elliptic_curve.py | 2,272 | 3.65625 | 4 | def extended_euclidean(a, b):
r_prev, r = a, b
s_prev, s = 1, 0
t_prev, t = 0, 1
while r:
q = r_prev // r
r_prev, r = r, r_prev - q*r
s_prev, s = s, s_prev - q*s
t_prev, t = t, t_prev - q*t
return s_prev, t_prev
def find_inverse(x, p):
inv, _ = extended_euclidean(x, p)
return inv
class EllipticCurve:
"""Elliptic curve modulo p.
y^2 = x^3 + ax + b (mod p)
Elliptic curve is singular if its discriminant -16*(4a^3 + 27b^2)
is zero modulo p. If discriminant is zero polynomial has repeated
roots, cusps, etc.
"""
POINT_AT_INFINITY = (float('inf'), float('inf'))
def __init__(self, a, b, p):
discriminant = 16 * (4 * a**3 + 27 * b**2)
if discriminant % p == 0:
raise ValueError('singular elliptic curve')
self.a = a
self.b = b
self.p = p
def add(self, p1, p2):
"""Add two points p1 and p2."""
x1, y1 = p1
x2, y2 = p2
a, p = self.a, self.p
if p1 == self.POINT_AT_INFINITY:
return p2
elif p2 == self.POINT_AT_INFINITY:
return p1
elif x1 == x2 and y1 != y2:
# We can rewrite this condition as
# x1 == x2 and find_inverse(-y1, p) == y2
# but, y1 != y2 is more efficient.
# This is correct because vertical line intersects
# the elliptic curve in one or two points.
return self.POINT_AT_INFINITY
if p1 == p2:
m = (3 * x1**2 + a) * find_inverse(2 * y1, p) % p
else:
m = (y2 - y1) * find_inverse(x2 - x1, p) % p
x3 = (m**2 - x1 - x2) % p
y3 = (m * (x1 - x3) - y1) % p
result = (x3, y3)
return result
def pow(self, n, b):
"""Raise n to the power of b.
Note:
With "+" group operation this is the same as
"add point 'n' b times".
"""
num_bits = b.bit_length()
res = self.POINT_AT_INFINITY
for i in range(num_bits, -1, -1):
res = self.add(res, res)
if b & (1 << i):
res = self.add(res, n)
return res
curve = EllipticCurve(a=2, b=2, p=17)
a = (5, 1)
print(curve.pow(a, 2))
|
e042690a66da0f9dd13774cd79b9e9b844ebeb81 | xiang12835/python-learning | /leetcode/linked_list/24. Swap Nodes in Pairs.py | 2,077 | 4.0625 | 4 | # coding=utf-8
"""
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
递归
"""
if not head or not head.next:
return head
tmp = head.next
head.next = self.swapPairs(head.next.next)
tmp.next = head
return tmp
class Solution1:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
循环;哨兵
1->2->3->4
-1->2->1->4->3->null
"""
if not head or not head.next:
return head
cur = dummy = ListNode(-1)
dummy.next = head
while cur.next and cur.next.next:
next_one, next_two, next_three = cur.next, cur.next.next, cur.next.next.next
cur.next = next_two
next_two.next = next_one
next_one.next = next_three
cur = next_one
return dummy.next
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution2:
def swapPairs(self, head: ListNode) -> ListNode:
"""
迭代法
T: O(N)
S: O(1)
"""
if not head or not head.next:
return head # 易错
dummy = cur = ListNode(-1)
dummy.next = head # 易错,需要连接起来
while cur.next and cur.next.next:
one = cur.next
two = cur.next.next
tree = cur.next.next.next
cur.next = two
two.next = one
one.next = tree
cur = one
return dummy.next |
e4314e2952cbb1330f12ff89f8502ac9cf15b894 | VenetianDevil/Universality | /Python_Infosys/1/solution.py | 1,077 | 4.25 | 4 | #!/usr/bin/python
# -*- coding: iso-8859-2 -*-
##########################################
# Write a program that reads one line from the the standard input which contains two integers and a symbol of the operation. Depending on the symbol, the program should print the correct value of the operation. If the user gave the wrong symbol, it should print text "Error".
# Input
# Space separated integers X and Y (-1000 ≤ X ≤ 1000, -1000 ≤ Y ≤ 1000) and a symbol of the operation S (+, -, *, %)
# Output
# Result of the operation X S Y
# Example
# Input:
# 4 3 +
# Output:
# 7
############################################
x, y, operand = input().split()
try:
x = int(x)
except ValueError:
print ('x nie liczba')
try:
y = int(y)
except ValueError:
print ('y nie integer')
if x >= -1000 and x <= 100 and y>=-1000 and y<=1000:
if operand == '+':
print(x + y)
elif operand == '-':
print(x - y)
elif operand == '*':
print(x * y)
elif operand == '%':
print(x % y)
else:
print('Error') |
1faeaa13d3e991583613f24be7ecfc2a3f5b6211 | sadiquemohd/data_analytics | /python_math /hw5/task1.py | 273 | 3.671875 | 4 | import numpy as np
"""
Задание 1
Создайте numpy array с элементами от числа N до 0 (например, для N = 10 это будет array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])).
"""
def createNpArray(n):
return np.arange(0, n)[::-1]
|
4c4341f5395e02e99740a752093dbb848136ce8c | cathalgarvey/mdr | /mdr/utils.py | 1,687 | 3.6875 | 4 | # -*- coding: utf-8 -*-
import re
import itertools
def find_continous_subsequence(iterable, predicate):
"""
find the continuous subsequence with predicate function return true
>>> find_continous_subsequence([2, 1, 2, 4], lambda x: x % 2 == 0)
[[2], [2, 4]]
>>> find_continous_subsequence([2, 1, 2, 4], lambda x: x % 2 != 0)
[[1]]
"""
seqs = []
for key, values in itertools.groupby(iterable, key=predicate):
if key == True:
seqs.append(list(values))
return seqs
def split_sequence(seq, predicate):
"""
split the sequence at the position when predicate return true
>>> list(split_sequence([0, 1, 2, 1, 2], lambda x: x == 1))
[[0], [1, 2], [1, 2]]
>>> list(split_sequence([0, 1, 2, 1, 2, 1], lambda x: x == 2))
[[0, 1], [2, 1], [2, 1]]
>>> list(split_sequence([('a', 1), ('b', 2), ('c', 1)], lambda x: x[1] == 1))
[[('a', 1), ('b', 2)], [('c', 1)]]
"""
seqs = []
for s in seq:
if predicate(s):
if seqs:
yield seqs
seqs = [s]
else:
seqs.append(s)
if seqs:
yield seqs
def reverse_dict(d):
return dict(reversed(item) for item in d.items())
def common_prefix(*sequences):
"""determine the common prefix of all sequences passed
For example:
>>> common_prefix('abcdef', 'abc', 'abac')
['a', 'b']
"""
prefix = []
for sample in zip(*sequences):
first = sample[0]
if all([x == first for x in sample[1:]]):
prefix.append(first)
else:
break
return prefix
def simplify_xpath(xpath):
return re.sub('\[\d+\]', '', xpath)
|
0482736893323b828ebd7b938808294a6165b2db | WinrichSy/Codewars_Solutions | /Python/7kyu/ReturnTheFirstMmultiplesOfN.py | 194 | 3.546875 | 4 | #Return the first M multiples of N
#https://www.codewars.com/kata/593c9175933500f33400003e
def multiples(m, n):
ans = []
for i in range(1, m+1):
ans.append(i*n)
return ans
|
ff09747fb8734328b4badb9f40a52aee36b706bd | sharmarishabh54/hospital | /update appointments.py | 4,911 | 3.578125 | 4 | from tkinter import *
import tkinter.messagebox
import sqlite3
conn = sqlite3.connect('database1.db')
c = conn.cursor()
class application:
def __init__(self,master):
self.master = master
# heading label
self.heading = Label(master, text="Update Appointments",fg='darkslategray',font='times 40',bg='darkseagreen')
self.heading.place(x=350,y=30)
# search criteria
self.name=Label(master,text=" ENTER PATIENT'S NAME",font='times 18',bg='darkseagreen')
self.name.place(x=10,y=150)
#entry for name
self.name_ent = Entry(master,width=50)
self.name_ent.place(x=340,y=155)
# search button
self.search = Button(master,text="Search",font='times 13',width=12,height=1,bg='lightblue',command=self.search_db)
self.search.place(x=340,y=200)
def search_db(self):
self.input = self.name_ent.get()
# execute sql
sql = "SELECT * FROM appointments WHERE name LIKE ?"
self.res=c.execute(sql,(self.input,))
for self.row in self.res:
self.name1 = self.row[1]
self.age=self.row[2]
self.gender = self.row[3]
self.location = self.row[4]
self.phone = self.row[5]
self.time = self.row[6]
# update form
self.uname = Label(self.master,text="Patient's Name",font='times 18',bg='darkseagreen')
self.uname.place(x=10,y=250)
self.uage = Label(self.master,text="Age",font='times 18',bg='darkseagreen')
self.uage.place(x=10,y=300)
self.ugender = Label(self.master,text="Gender",font='times 18',bg='darkseagreen')
self.ugender.place(x=10,y=350)
self.ulocation = Label(self.master,text="Location",font='times 18',bg='darkseagreen')
self.ulocation.place(x=10,y=400)
self.uphone = Label(self.master,text="Phone no.",font='times 18',bg='darkseagreen')
self.uphone.place(x=10,y=450)
self.utime = Label(self.master,text="Appointment Time",font='times 18',bg='darkseagreen')
self.utime.place(x=10,y=500)
# ENTRIES FOR EACH LABEL
self.ent1 = Entry(self.master,width=30)
self.ent1.place(x=220,y=255)
self.ent1.insert(END,str(self.name1))
self.ent2 = Entry(self.master,width=30)
self.ent2.place(x=220,y=305)
self.ent2.insert(END,str(self.age))
self.ent3 = Entry(self.master,width=30)
self.ent3.place(x=220,y=355)
self.ent3.insert(END,str(self.gender))
self.ent4 = Entry(self.master,width=30)
self.ent4.place(x=220,y=405)
self.ent4.insert(END,str(self.location))
self.ent5 = Entry(self.master,width=30)
self.ent5.place(x=220,y=455)
self.ent5.insert(END,str(self.phone))
self.ent6 = Entry(self.master,width=30)
self.ent6.place(x=220,y=505)
self.ent6.insert(END,str(self.time))
#button to execute update
self.update = Button(self.master,text="Update",width=20,height=2,bg='springgreen',command=self.update_db)
self.update.place(x=220,y=555)
#button to delete
self.delete = Button(self.master,text="Delete",width=20,height=2,bg='red',command=self.delete_db)
self.delete.place(x=400,y=555)
def update_db(self):
#declaring the varialbe to updtae
self.v1= self.ent1.get()
self.v2= self.ent2.get()
self.v3= self.ent3.get()
self.v4= self.ent4.get()
self.v5= self.ent5.get()
self.v6= self.ent6.get()
query = "UPDATE appointments SET NAME=?, AGE=?, GENDER=?, LOCATION=?, PHONE=?, SCHEDULED_TIME=? WHERE NAME LIKE ?"
c.execute(query,(self.v1,self.v2,self.v3,self.v4,self.v5,self.v6,self.name_ent.get(),))
conn.commit()
tkinter.messagebox.showinfo("UPDATED","Successfully Updated")
def delete_db(self):
sql2="DELETE FROM appointments WHERE name LIKE ?"
c.execute(sql2,(self.name_ent.get(),))
conn.commit()
tkinter.messagebox.showinfo("DELETED","Successfully Deleted")
self.ent1.destroy()
self.ent2.destroy()
self.ent3.destroy()
self.ent4.destroy()
self.ent5.destroy()
self.ent6.destroy()
# creating the object
root= Tk()
b= application(root)
# icon
icon = PhotoImage(file='sharda.png')
root.tk.call('wm', 'iconphoto', root._w, icon)
#photo
photo = PhotoImage(file="Campus4.png")
pic = Label(root,image=photo)
pic.place(x=300,y=600)
root.geometry("1200x720+0+0")
root.resizable(False,False)
root.title('Sharda Hospital Management')
root.configure(bg='darkseagreen')
root.mainloop()
|
a5788b401b11810f033f8937e2f4d01791539e97 | simonfong6/ECE-143-Team-6 | /data_analysis/plotting.py | 6,412 | 3.796875 | 4 | #!/usr/bin/env python3
"""
Plotting functions
"""
import matplotlib.pyplot as plt
from math import pi # For radar graph.
def histogram(df, column_name, title, xlabel, ylabel, bins=10):
"""
Makes a histogram of the data.
Args:
df (pandas.DataFrame): All of the data.
column_name (str): The specific data to use for the plot.
title (str): The title of the plot.
xlabel (str): The xlabel of the plot.
ylabel (str): The ylabel of the plot.
"""
# Get the data.
column = df[column_name]
ax = plt.gca()
column.hist(ax=ax, alpha=0.9, color='blue', bins=bins)
# Handle title and labels.
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
def histograms(column_name, original, filtered, title, xlabel, ylabel):
"""
Plots two histograms side by side.
Args:
column_name (str): The specific data to use for the plot.
original (pandas.DataFrame): All of the data including outliers.
filtered (pandas.DataFrame): All of the data without outliers.
title (str): The title of the plot.
xlabel (str): The xlabel of the plot.
ylabel (str): The ylabel of the plot.
"""
# Get the data.
orig_column = original[column_name]
filt_column = filtered[column_name]
# Start a subplot.
_, (ax1, ax2) = plt.subplots(1, 2)
# Plot the data with outliers.
orig_column.hist(ax=ax1, alpha=0.9, color='blue')
ax1.set_title('Original {title} Histogram'.format(title=title))
ax1.set(xlabel=xlabel, ylabel=ylabel)
# Plot the data without outliers.
filt_column.hist(ax=ax2, alpha=0.9, color='blue')
ax2.set_title('Filtered {title} Histogram'.format(title=title))
ax2.set(xlabel=xlabel, ylabel=ylabel)
def graph_labels(title, xlabel=None, ylabel=None):
"""
Helps write title and axis labels.
Args:
title (str): The title of the plot.
xlabel (str): The xlabel of the plot.
ylabel (str): The ylabel of the plot.
"""
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
def pie_chart(percentages, column_name, yes_label, no_label, title):
"""
Helps plot a pie chart for yes or no data.
Args:
percentages (pandas.DataFrame): All of the data averaged.
column_name (str): The specific data to use for the plot.
yes_label (str): The label for the yes portion of the chart.
no_label (str): The label for the no portion of the chart.
title (str): The title of the plot.
"""
yes_percentage = percentages[column_name]
no_percentage = 1 - yes_percentage
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = yes_label, no_label
sizes = [yes_percentage, no_percentage]
# Explode the Yes.
explode = (0.1, 0)
ax = plt.gca()
ax.pie(
sizes,
explode=explode,
labels=labels,
autopct='%1.1f%%',
shadow=True,
startangle=90)
# Equal aspect ratio ensures that pie is drawn as a circle.
ax.axis('equal')
plt.title(title)
def radar(angles, categories, values, ylim, yticks, fill_color='b'):
"""
Helps plot a radar graph.
Args:
angles (list): Angles to plot spines of radar graph. Should be in
radians. Spans from [0, 2*pi].
categories (list): Categories to write on each spine.
values (list): Values to plot for each spine.
ylim (int): How big to make the circle.
yticks (list(int)): The labels mark on each spine.
"""
# Initialise the spider plot
ax = plt.subplot(111, polar=True)
# Draw one axe per variable + add labels labels yet
plt.xticks(angles, categories, color='black', size=10)
# Make sure the xtick labels don't overlap the graph.
for label,rot in zip(ax.get_xticklabels(),angles):
# All labels on left side are right aligned.
# All labels on right side are left aligned.
if rot <= pi / 2 or rot >= 3 * pi / 2:
label.set_horizontalalignment("left")
else:
label.set_horizontalalignment("right")
# Draw ylabels
yticks_labels = [str(tick) for tick in yticks]
ax.set_rlabel_position(0)
plt.yticks(yticks, yticks_labels, color="black", size=7)
plt.ylim(0, ylim)
# Angles/Values double first.
angles_first_doubled = angles + angles[:1]
values_first_doubled = values + values[:1]
# Plot data
ax.plot(angles_first_doubled, values_first_doubled, linewidth=1, linestyle='solid')
# Fill area
ax.fill(angles_first_doubled, values_first_doubled, fill_color, alpha=0.1)
def plot_radar(categories, values, num_yticks=5, fill_color='b'):
"""
Helps plot a radar graph.
Args:
categories (list): Categories to write on each spine.
values (list): Values to plot for each spine.
num_yticks (int): Optional. Defaults to 5. The number of ticks to show
on each spine.
"""
N = len(categories)
max_value = int(max(values))
step_size = int(max_value / num_yticks)
yticks = list(range(step_size, max_value , step_size))
# What will be the angle of each axis in the plot? (we divide the plot / number of variable)
angles = [n / float(N) * 2 * pi for n in range(N)]
radar(angles, categories, values, max_value + step_size, yticks, fill_color)
def plot_radar_df(df, column_names, xlabels=None, fill_color='b'):
"""
Helps plot a radar graph.
Args:
df (pandas.DataFrame): The data to be accessed to be plotted.
column_names (list(str)): The names of the columns to be plotted on the
graph.
xlabels (dict(str->str)): Maps each column name to human readable label.
Optional. When not specified, the column names are used as the
labels.
"""
# Get sums.
sums = df.sum()
# Grab only the qualities we want.
sums = sums[column_names]
# Convert it to a dict.
sums = sums.to_dict()
# Pull column names and values.
if xlabels is not None:
names = list(sums.keys())
categories = [xlabels[name] for name in names]
else:
categories = list(sums.keys())
values = list(sums.values())
# Plot it.
plot_radar(categories, values, fill_color=fill_color)
|
bb89d07d4de447e8e3d0670f6723471151afc10d | imckl/leetcode | /medium/79-word-search.py | 2,994 | 3.84375 | 4 | # Given a 2D board and a word, find if the word exists in the grid.
#
# The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells
# are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
#
# https://leetcode.com/problems/word-search/
from typing import List
class Solution:
def __init__(self):
self._directions = [
{'row': 0, 'col': -1},
{'row': 0, 'col': 1},
{'row': 1, 'col': 0},
{'row': -1, 'col': 0},
]
def exist(self, board: List[List[str]], word: str) -> bool:
rows, cols = len(board), len(board[0])
if rows == 0 or cols == 0:
return False
if not word:
return False
# if rows * cols < len(word):
# return False
used: List[List[int]] = [[-1 for _ in range(cols)] for _ in range(rows)]
for row in range(rows):
for col in range(cols):
if board[row][col] == word[0]:
used[row][col] = 0
if self._search_letter(board, rows, cols, row, col, word, 1, used):
return True
used[row][col] = -1
return False
# return self._search(board, R, C, )
def _search_letter(self, board: List[List[str]], rows: int, cols: int,
start_row: int, start_col: int, word: str, word_idx: int,
used: List[List[int]]):
# 递归终止的条件
if word_idx == len(word):
return board[start_row][start_col] == word[word_idx - 1]
# 按顺时针从上方开始搜索字符
for dir in self._directions:
tmp_row, tmp_col = start_row + dir['row'], start_col + dir['col']
# 超出索引边界
if not (0 <= tmp_row <= rows - 1 and 0 <= tmp_col <= cols - 1):
continue
# 节点已经使用
if used[tmp_row][tmp_col] != -1:
continue
# 不为对应字符
if board[tmp_row][tmp_col] != word[word_idx]:
continue
used[tmp_row][tmp_col] = word_idx
if self._search_letter(board, rows, cols, tmp_row, tmp_col, word, word_idx + 1, used):
return True
used[start_row][start_col] = -1
return False
def main():
board = [
['A', 'B', 'C', 'E'],
['S', 'F', 'C', 'S'],
['A', 'D', 'E', 'E']
]
word = 'ABCB'
# board = [
# ['Z', 'K', 'Z', 'Z'],
# ['A', 'C', 'C', 'E'],
# ['K', 'C', 'C', 'Z']
# ]
# word = 'ACCCCK'
board = [
["A", "B", "C", "E"],
["S", "F", "C", "S"],
["A", "D", "E", "E"]
]
word = "SEE"
board = [["a", "a"]]
word = "aaa"
solution = Solution()
result = solution.exist(board, word)
print(result)
if __name__ == '__main__':
main()
|
6fb560d71277e8cba3bbf1ef4d4e1226198c30fb | DeepakKumar-Mahadevan/repo01 | /Programs-01/dict-02.py | 232 | 3.796875 | 4 | num = {1:'A',2:'B',3:'C'}
print (num.items())
num[4] = 'D'
num[5] = 'E'
print (num.items())
num[6] = 'F'
num[7] = 'G'
num[8] = 'H'
num[9] = 'I'
num[10] = 'J'
print (num.items())
del num[6]
del num[8]
print (num.items()) |
4cada6c959eee83ade46002ca973890b89e2c226 | Jhancykrishna/luminarpythonprograms | /functions/even.py | 228 | 4.03125 | 4 | def even():
num=int(input('enter a number'))
if(num%2==0):
print('even number')
even()
print('**************')
def even(num):
if (num % 2 == 0):
print('even number')
even(4)
print('**************')
|
a13b42b6daf5f92a30bf2dfc1750653729046429 | VVSKushwanthReddy/100_days_of_DSA | /Data Structure with Python/List/Insert and Serach.py | 125 | 3.515625 | 4 | l = [10, 20, 30, 40, 50]
l.append(30)
print(l)
l.insert(1, 15)
print(l)
print(15 in l)
print(l.count(30))
print(l.index(30))
|
426a03f49e6099725e36d8ffd14c2f8caecad9b7 | jbremer/triegen | /triegen.py | 3,505 | 3.609375 | 4 | #!/usr/bin/env python
"""Triegen (C) Jurriaan Bremer 2013
Utility to generate a Trie from a set of strings.
"""
import RBTree
import sys
class Node:
"""Represents a single, light-weight, node of a tree."""
def __init__(self, left, value, right):
self.left = left
self.value = value
self.right = right
self.parent = None
def count(self):
"""Returns the count of values, including its own."""
ret = 1
if self.left:
ret += self.left.count()
if self.right:
ret += self.right.count()
return ret
def is_left(self):
return self.parent.left == self if self.parent else None
def trie(l):
"""Function which translates a list into a balanced trie."""
def node(n):
if not n:
return None
ret = Node(node(n.left), n.value, node(n.right))
if ret.left:
ret.left.parent = ret
if ret.right:
ret.right.parent = ret
return ret
# there's some serious stuff going on in the Garbage Collector,
# effectively unlinking the _entire_ tree when omitting a temporary
# storage of the tree object (due to an aggressive __del__ in RBTree)
tree = RBTree.RBList(l)
return node(tree.root)
def calcdiff(n):
"""Calculates the difference between a Nodes value, left, and right.
This function has no return value, it only adds some fields to the Nodes.
"""
def triegen_C_int(n, fmt):
"""Trie Generator for C.
Returns a list of C code, which represent the generated Trie.
"""
lines = []
if n.left:
if n.left.count() == 1:
lines += triegen_C_int(n.left, fmt)
left = n.left.value
else:
lines += ['if(x < %s) {' % n.value]
lines += [' ' + x for x in triegen_C_int(n.left, fmt)]
lines += ['}']
left = n.value
if n.right:
if n.right.count() == 1:
lines += triegen_C_int(n.right, fmt)
right = n.right.value
else:
lines += ['%sif(x > %s) {' % ('else ' if n.left else '', n.value)]
lines += [' ' + x for x in triegen_C_int(n.right, fmt)]
lines += ['}']
right = n.value
if n.left and n.right and left == right:
lines += ['else {']
elif n.left and n.right and n.parent and n.parent.parent and \
abs(n.parent.value - n.parent.parent.value) == 4 and \
n.is_left() != n.parent.is_left():
lines += ['else {']
elif n.left and n.right and n.parent and n.parent.parent and \
n.parent.parent.parent and \
n.is_left() != n.parent.parent.is_left() and \
abs(n.parent.value - n.parent.parent.parent.value) == 4:
lines += ['else {']
elif n.left or n.right:
lines += ['else if(x == %s) {' % n.value]
else:
lines += ['if(x == %s) {' % n.value]
lines += [' return ' + fmt.format(n.value) + ';', '}']
return lines
def triegen_C(n, fn, fmt):
lines = ['#include <stdio.h>', 'const char *%s(int x)' % fn, '{']
lines += [' ' + x for x in triegen_C_int(n, fmt)]
return lines + [' return NULL;', '}']
if __name__ == '__main__':
if len(sys.argv) < 4:
print 'Usage: %s <infile> <funcname> <fmt>' % sys.argv[0]
exit(0)
root = trie(int(x.strip()) for x in open(sys.argv[1]))
calcdiff(root)
print '\n'.join(triegen_C(root, sys.argv[2], sys.argv[3]))
|
0b36837149426177911c262a03dcb153f6b33716 | Jerry9757/pytw_a01 | /ex1_tk.py | 408 | 3.625 | 4 | # github Pytw_T01, Git 練習
from tkinter import *
from tkinter import ttk
my_window =Tk()
my_window.geometry("400x450") # window size
my_window.title("Hello tkinter") # window size
label_one= Label(my_window, text='Message ')
label_one.grid(row=0, column=0)
text_msg=Text(my_window,height=1, width=20)
text_msg.grid(row=0, column=1)
text_msg.insert(END, "Hello world! ")
my_window.mainloop()
|
322812b0925f094500374daeab3c4a4ef69fcdb8 | gmt710/leetcode_python | /primary/4_levelOrder.py | 1,400 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
# if root is None:return []
# stack = [root]
# yy=[]
# #none就出
# while stack:
# y=[]
# #出栈
# #每一层
# print(len(stack))
# for i in range(len(stack)):
# current = stack.pop(0)
# y.append(current.val)
# if current.left:
# #入栈
# stack.append(current.left)
# if current.right:
# stack.append(current.right)
# yy.append(y)
# return yy
import Queue
res = []
q = Queue.Queue()
if root:
q.put(root)
while not q.empty():
level = []
length = q.qsize()
for i in range(length):
node = q.get()
level.append(node.val)
if node.left:
q.put(node.left)
if node.right:
q.put(node.right)
res.append(level)
return res
|
f07453deb6191dea09f0971ef446ffd8da4e0c4d | Muhammadabubakar503/LearnOOPFall2020 | /lecture/lec_3_condition.py | 548 | 3.953125 | 4 | #if condition
a=4000
if a>3000:
print("a is greater")
print("________________________________________________________________")
#if else condition
a=10
b=20
if a>b:
print("a is greater")
else:
print("b is greater")
print("________________________________________________________________")
# if elif condition
mobile_prize= 28000
if mobile_prize<20000:
print("the range of the price is normal")
elif mobile_prize<30000:
print("the range of the price is good")
else:
print("the range of the price is high") |
ef936f4821123c71a0975c5bc822123b526624da | vinoth-rz/xrange | /xrange.py | 5,220 | 3.828125 | 4 | from math import ceil
from collections import Sequence, Iterator
class xrange(Sequence):
"""Pure-Python implementation of an ``xrange`` (aka ``range``
in Python 3) object. See `the CPython documentation
<http://docs.python.org/py3k/library/functions.html#range>`_
for details.
"""
def __init__(self, *args):
if len(args) == 1:
start, stop, step = 0, args[0], 1
elif len(args) == 2:
start, stop, step = args[0], args[1], 1
elif len(args) == 3:
start, stop, step = args
else:
raise TypeError('xrange() requires 1-3 int arguments')
try:
start, stop, step = int(start), int(stop), int(step)
except ValueError:
raise TypeError('an integer is required')
if step == 0:
raise ValueError('xrange() arg 3 must not be zero')
elif step < 0:
stop = min(stop, start)
else:
stop = max(stop, start)
self._start = start
self._stop = stop
self._step = step
self._len = (stop - start) // step + bool((stop - start) % step)
def __repr__(self):
if self._start == 0 and self._step == 1:
return 'xrange(%d)' % self._stop
elif self._step == 1:
return 'xrange(%d, %d)' % (self._start, self._stop)
return 'xrange(%d, %d, %d)' % (self._start, self._stop, self._step)
def __eq__(self, other):
return isinstance(other, xrange) and \
self._start == other._start and \
self._stop == other._stop and \
self._step == other._step
def __len__(self):
return self._len
def index(self, value):
"""Return the 0-based position of integer `value` in
the sequence this xrange represents."""
diff = value - self._start
quotient, remainder = divmod(diff, self._step)
if remainder == 0 and 0 <= quotient < self._len:
return abs(quotient)
raise ValueError('%r is not in range' % value)
def count(self, value):
"""Return the number of ocurrences of integer `value`
in the sequence this xrange represents."""
# a value can occur exactly zero or one times
return int(value in self)
def __contains__(self, value):
"""Return ``True`` if the integer `value` occurs in
the sequence this xrange represents."""
try:
self.index(value)
return True
except ValueError:
return False
def __reversed__(self):
"""Return an xrange which represents a sequence whose
contents are the same as the sequence this xrange
represents, but in the opposite order."""
sign = self._step / abs(self._step)
last = self._start + ((self._len - 1) * self._step)
return xrange(last, self._start - sign, -1 * self._step)
def __getitem__(self, index):
"""Return the element at position ``index`` in the sequence
this xrange represents, or raise :class:`IndexError` if the
position is out of range."""
if isinstance(index, slice):
return self.__getitem_slice(index)
if index < 0:
# negative indexes access from the end
index = self._len + index
if index < 0 or index >= self._len:
raise IndexError('xrange object index out of range')
return self._start + index * self._step
def __getitem_slice(self, slce):
"""Return an xrange which represents the requested slce
of the sequence represented by this xrange.
"""
start, stop, step = slce.start, slce.stop, slce.step
if step == 0:
raise ValueError('slice step cannot be 0')
start = start or self._start
stop = stop or self._stop
if start < 0:
start = max(0, start + self._len)
if stop < 0:
stop = max(start, stop + self._len)
if step is None or step > 0:
return xrange(start, stop, step or 1)
else:
rv = reversed(self)
rv._step = step
return rv
def __iter__(self):
"""Return an iterator which enumerates the elements of the
sequence this xrange represents."""
return xrangeiterator(self)
class xrangeiterator(Iterator):
"""An iterator for an :class:`xrange`.
"""
def __init__(self, xrangeobj):
self._xrange = xrangeobj
# Initialize the "last outputted value" to the value
# just before the first value; this simplifies next()
self._last = self._xrange._start - self._xrange._step
self._count = 0
def __iter__(self):
"""An iterator is already an iterator, so return ``self``.
"""
return self
def next(self):
"""Return the next element in the sequence represented
by the xrange we are iterating, or raise StopIteration
if we have passed the end of the sequence."""
self._last += self._xrange._step
self._count += 1
if self._count > self._xrange._len:
raise StopIteration()
return self._last
|
957ab29289184d27b72433111fde4d79893d98a2 | OliEyEy/Git_FOR | /FOR/Áfangi 1/Æfingarverkefni/09_AEfingarverkefni/Æfingarverkefni 9.py | 1,545 | 3.59375 | 4 | #Æfingarverkfefni 9 - Ólafur Eysteinn - 8. Nóvember 2016
on="on"
while on=="on":
print("1. Lengsta orðið - 2. Random tölur - 3. Að telja orð - 4. Afturábak - 5. Hætta")
valmynd=int(input("Veldu lið. 1, 2, 3, 4 eða 5. "))
if valmynd==1:
#Liður 1
print("Liður 1")
ordalisti=[]
print("Sláðu 5 orð inn í lista.")
for x in range(5):
nafn=input("Slá inn orð hér. ")
ordalisti.append(nafn)
print(ordalisti)
radad=sorted(ordalisti, key=len)
print("Lengsta orðið er",min(radad))
print("Það er",len(min(radad)),"stafir.")
if valmynd==2:
#Liður 2
print("Liður 2")
nafn=input("Sláðu inn nafn þitt. ")
print("Nafnið þitt í stórum stöfum er",nafn.upper())
print("Nafnið þitt í litlum stöfum er", nafn.lower())
stafur=input("Sláðu inn einhvern staf og forritð skiptir honum út fyrir @ ")
for staf in nafn:
nafn=nafn.replace(stafur, "@")
print(nafn)
if valmynd==3:
#Liður 3
print("Liður 3")
hveMorgOrd=1
strengur=input("Sláðu inn setningu. ")
for staf in strengur:
if staf==" ":
hveMorgOrd=hveMorgOrd+1
print("Þú skrifaðir",hveMorgOrd,"orð.")
if valmynd==4:
#Liður 4
print("Liður 4")
setning=input("Sláðu inn setningu. ")
print(setning[::-1])
if valmynd==5:
print("Takk fyrir mig.")
on="off" |
08db14431f04a39050c2fbf74745b016c7064b35 | Pennylele/Algorithms-fun-daily | /150.py | 726 | 3.671875 | 4 | class Solution:
def evalRPN(self, tokens):
stack = []
def math(num1, num2, operator):
if operator == "+":
return int(num1) + int(num2)
if operator == "-":
return int(num2) - int(num1)
if operator == "*":
return int(num1) * int(num2)
if operator == "/":
return int(int(num2)/int(num1))
for i in tokens:
if i in "+-*/":
num1 = stack.pop()
num2 = stack.pop()
stack.append(math(num1, num2, i))
else:
stack.append(i)
return stack[0]
obj = Solution()
print(obj.evalRPN(["4","13","5","/","+"])) |
411fb38ec9c257cfadf9598c92d5f0b336b0a3df | perglervitek/Python-B6B36ZAL | /08/otazky.py | 343 | 3.6875 | 4 | # lst = [10,20,30,40,50,60,70]
# for v in lst:
# print(v)
# print("---------------")
# for v in lst:
# print(v, lst.pop(0))
lst1 = [
{'name': 'Josef Novák', 'age': 27},
{'name': 'Jan Srp', 'age': 80}
]
# create a copy of lst1
lst2 = []
for v in lst1:
lst2.append(v)
lst2.pop()
lst2[0]['age'] = 15
print(lst1)
print(lst2)
print(lst1) |
32b368b818680d617098076c60d5e8b16c3b699e | Raj1v/machine_learning_final_project | /mean_recommendations.py | 1,180 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 19 13:19:46 2019
@author: Rajiv
"""
import numpy as np
class RecommendMean(object):
def __init__(self):
return
def get_ratings(self, targetid, targetmovies):
"""Returns mean ratings for each target movie"""
predictions = []
for movie in targetmovies:
prediction = self.mean_of_movies[movie - 1]
predictions.append(prediction)
return np.array([targetmovies, predictions]).T
def init_data(self, data):
#Take the input data matrix and add two new columns at the start, the first with the user id, the second with
#this user's mean. Also if we want all our data to be normalized and mean=True, we do that here as well
new_data = data.copy()
transp_data = new_data.T
mean_of_movies = []
#calculate the mean of all_movies
for i in range(len(transp_data)):
movie_mean = new_data[i][new_data[i] != 0].mean()
mean_of_movies.append(movie_mean)
self.mean_of_movies = np.array(mean_of_movies)
|
132552e3768837e33e6c7e7f31bf31bbbaa74759 | irfankhan309/DS-AL | /Py_Codes/my_practice/python_series/MRO.py | 1,019 | 3.984375 | 4 | #THIS IS METHOD RESOLUTION ORDER (MRO),using C3 algorithm , (Linearization)
#1.magine you were implementing a programming language that featured inheritance.
#2.When you first approach this topic you decide:
#a child class will have all of the functions and attributes that it’s parent classes should have!
#Now this may work for the vast majority of scenarios but what would happen if two parent classes both implemented,
# the same function or attribute? How do you decide what function or attribute takes precedence?
class A:
def m1(self):
print('this is A class')
class B:
def m1(self):
print('this is class B')
class C:
def m1(self):
print('this is C class')
class Z:
def m1(self):
print('this is D class')
class X(A,B):
def m1(self):
print('this is X class')
class Y(B,C):
def m1(self):
print('this is Y class')
class P(X,Y,C,Z):#PXAYBCZO
pass
#def m1(self):
# print('this is P class')
p=P()
p.m1()
|
f2ca20e9c4d281194986d064c9b98e62e17fbaeb | alex2018hillel/Hillel2020Python | /Lesson_5/Task_3.py | 225 | 3.75 | 4 | text = "Help ELephant learn LOops. While's and fOrs. RLD!"
symbol = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
word_list = []
for l in list(text):
if l in list(symbol):
word_list.append(l)
word = ''.join(word_list)
print(word) |
5b89071c42810564c4556fa9030dbdff39e070f4 | rafaelperazzo/programacao-web | /moodledata/vpl_data/396/usersdata/302/81017/submittedfiles/av1_programa2.py | 689 | 3.8125 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
n = int(input('Primeira aposta: '))
a = int(input('segunda aposta: '))
b = int(input('Terceira aposta: '))
c = int(input('Quarta aposta: '))
d = int(input('Quinta aposta: '))
e = int(input('Sexta aposta: '))
f = int(input('Primeiro sorteado: '))
g = int(input('segundo sorteado: '))
h = int(input('Terceiro sorteado: '))
i = int(input('Quarto sorteado: '))
j = int(input('Quinto sorteado: '))
k = int(input('Sexto sorteado: '))
if (n and a and b and c and d and e) == (f or g or h or i or j or k):
print('Sena')
if (n and a and b and c and d or e) == (f and g and h and i and j and k):
print('Quina')
|
4884ec9675f3094eacfb1bd904b40554f79d233f | MaartensInformatica/Afvink-4 | /bug collegcot.py | 389 | 3.71875 | 4 | #geef de variabele bugs een waarde om ermee te kunnen werken
bugs = 0
for dag in range(1,6):
bugs += int(input('Dag '+str(dag )+' aantal bugs: '))
print('totaal: ',bugs)
#Er zijn 5 dagen, dus een reeks van 1 tot 6 (1 t/m 5)
#In de reeks wordt voor elke dag de input gevraagd onder de naam bugs
#print het totaal. Aan het einde van de loop is bugs het aantal bugs van 5 dagen
|
4156e51b2936e465a631fdbf12d113e7046db2ec | sunxianpeng123/python_common | /common_used_package/json_pickle_test.py | 1,522 | 3.546875 | 4 | # encoding: utf-8
"""
@author: sunxianpeng
@file: json_pickle_test.py
@time: 2019/12/1 20:04
"""
import json
def dumps():
# dumps可以格式化所有的基本数据类型为字符串
list_json = json.dumps([])
# 数字
num_json = json.dumps(1)
# 字符串
str_json = json.dumps('abc')
dict = {"name": "Tom", "age": 23}
dict_json = json.dumps(dict) # 字典
print('list json = {}'.format(list_json))
print('num json = {}'.format(num_json))
print('str json = {}'.format(str_json))
print('dict json = {}'.format(dict_json))
print(type(dict_json))
with open('test.json','w',encoding='utf-8') as f:
# indent 超级好用,格式化保存字典,默认为None,小于0为零个空格,美化json格式
f.write(json.dumps(dict, indent=4))
def dump():
dict = {"name": "Tom", "age": 24}
json.dump(dict,open('test.json','w',encoding='utf-8'))
def loads():
dict_1 = {"name": "Tom", "age": 23}
dict_json = json.dumps(dict_1) # 字典
dict_2 = json.loads(dict_json)
print('dict_1 = {}'.format(dict_1))
print('dict_2 = {}'.format(dict_2))
num_json_1 = json.dumps(1)
num_json_2 = json.loads(num_json_1)
print(num_json_2)#1
print(type(num_json_2))#<class 'int'>
def load():
dict_json = json.load(open('test.json','r',encoding='utf-8'))
print(type(dict_json))#<class 'dict'>
print(dict_json)#{'name': 'Tom', 'age': 24}
if __name__ == '__main__':
# dumps()
# dump()
# loads()
load() |
a7f0e0e07c270272362513180235e560526bc790 | ishaansaxena/ProjectEuler | /100-199/108.py | 351 | 3.546875 | 4 | #!/usr/bin/python
from time import *
from math import *
start = time()
def numOfFactors(x):
factors = 1
for i in range(2, int(sqrt(x))+1):
if x%i == 0:
factors += 1
if x % sqrt(x) == 0:
factors = 2*factors - 1
else:
factors = 2*factors
return factors
for x in range(1,100000):
print x, numOfFactors(x)
print time() - start, "seconds" |
612f8f95614e0047c339e942e4bcdfe515c76601 | Alcheemiist/42-AI-Bootcamp-python | /M00/ex01/exec.py | 159 | 3.578125 | 4 | def step_back(x):
return x[::-1]
import sys
sent_str = ""
for i in sys.argv[1:]:
sent_str += str(i).swapcase() + " "
print(step_back(sent_str.strip())) |
5e25539bf587bf615e6ebb4abb10c445c1977e3f | bonicim/technical_interviews_exposed | /tst/fifty_common_interview_questions_leetcode_book/test_implement_strStr.py | 1,582 | 3.65625 | 4 | import pytest
from src.algorithms.fifty_common_interview_questions_leetcode_book.str_str import (
str_str,
)
def test_should_return_2():
haystack = "hello"
needle = "ll"
assert str_str(haystack, needle) == 2
def test_should_return_negative_1():
haystack = "aaaaaaaaaaaaaa"
needle = "bba"
assert str_str(haystack, needle) == -1
def test_matching_string_at_end_should_return_3():
haystack = "helllo"
needle = "llo"
assert str_str(haystack, needle) == 3
def test_needle_at_end_of_haystack_return_4():
haystack = "hello"
needle = "o"
assert str_str(haystack, needle) == 4
def test_empty_needle_should_return_0():
assert str_str("fghgffdsgfsdgdf", "") == 0
def test_empty_haystack_should_return_negative_1():
assert str_str("", "fdafdsfasdf") == -1
def test_empty_needle_empty_haystack_should_return_0():
assert str_str("", "") == 0
def test_needle_greater_than_haystack_should_return_negative_1():
assert str_str("dfddf", "fdsafadsfasdfadsfadsf") == -1
def test_multiple_needles_in_haystack():
haystack = "mississippi"
needle = "issi"
assert str_str(haystack, needle) == 1
def test_long_strings_should_return_negative_1():
haystack = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
needle = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaX"
assert str_str(haystack, needle) == -1
|
44ba6645417c5a8c7ad509dd7f4cf4292a0be822 | krysnuvadga/learning_portfolio | /preps/listAverage.py | 116 | 3.78125 | 4 | def average(arr):
n = len(arr)
s = sum(arr)
a = s/n
return a
list1 = [1,2,3]
print(average(list1))
|
1330586aa13df5de529dc2ffa61924508fe84fc9 | mthezeng/euler-solutions | /p013.py | 1,916 | 4.4375 | 4 | def addition_algorithm(numb3rs):
"""the elementary school addition algorithm
numb3rs is a file object
returns a list of digits corresponding to the sum of all numbers in numb3rs
the list is in reverse order: the last digit appears first in the list
Indeed, since python no longer has a maximum integer size, this can be brute-forced
more straight-forwardly by adding the numbers directly. This solution is
purely for the experience of coding the addition algorithm, and it can probably
be flexibly translated into other programming languages that do have a
maxmimum integer size."""
sum_digits = []
column_pos, row_pos = 1, 1
carryover = 0
current_column = []
for c in range(50):
for r in range(100):
numb3rs.seek((51 * r) + (50 - (c + 1)))
current_column.append(int(numb3rs.read(1)))
current_sum = int(sum(current_column))
if current_sum > 10:
carryover = int((current_sum - (current_sum % 10)) / 10)
if c < 49:
current_sum = current_sum % 10
sum_digits.append(current_sum)
current_column = [carryover]
return sum_digits
def first_ten_digits(sum_list):
first_ten = ''
i = -1
stop = -11
while i > stop:
if sum_list[i] < 10:
first_ten = first_ten + str(sum_list[i])
i -= 1
else:
a_string = str(sum_list[i])
digits = 0
if sum_list[i] >= 100:
digits = 3
stop += 2
i -= 1
else:
digits = 2
stop += 1
i -= 1
for x in range(digits):
first_ten = first_ten + a_string[x]
return first_ten
fifty_digit_nums = open('50_digit_numbers.txt')
digit_list = addition_algorithm(fifty_digit_nums)
print(first_ten_digits(digit_list))
|
bbbcccee1d34b533f48cb710c13ccda52b998d5c | ishaankulshrestha/pythonBaseProjects | /com/ishaan/python/Refresher/A_refresher.py | 3,284 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 5 14:55:24 2018
@author: ishaan
"""
a, b, c, d, e = 1, 2, 3, 4, "ishaan"
print(a, b, c, d, e)
list1 = [1, 2, 3, 4, 'a', 'b', 'c', 'd']
print(list1)
print(list1[0:5])
tuple1 = (1, 2, 3, 4)
print(tuple1)
print(tuple1[2:4])
dictn = {"name": "ishaan", "company": "snapdeal", "desg": "ds"}
print(dictn.get("name"))
print(a + b)
print(b % c)
print(b ** c)
if (a < b and b < c):
print("yes")
else:
print("no")
if (not a > b and b < c):
print("yes")
else:
print("no")
if (3 in list1):
print("it is there")
else:
print("it is not there")
a = 1
while (a < 10):
a = a + 1
if (a == 3):
continue
print(a)
if (a > 4):
break
for i in range(20):
print(i)
for i in list1:
print(i)
for i in range(5):
for j in range(5):
print(i * j)
it = iter(list1)
nx = next(it)
print(nx)
## GENERATOR FUNCTION
def add1(n): # generator function
sum = 0
for i in range(n):
sum = sum + i
yield sum
f = add1(20) # f is iterator object
for i in range(10):
print(next(f))
import math
print(math.pi)
print(math.e)
var1 = 'Hello World!'
var2 = "Python Programming"
print("var1[0]: ", var1[0])
print("var2[1:5]: ", var2[1:5])
var1 = 'Hello World!'
print("Updated String :- ", var1[:6] + 'Python')
print('a' * 10)
print("let us see %s how this format %10d and %20d" % ("ishaan", 7, 6))
## use """ for multiline operations
#### Lists
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7]
print("list1[0]: ", list1[0])
print("list2[1:5]: ", list2[1:5])
list1[3] = 2001
del list1[2]
print(list1)
## Tuples
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7)
print("tup1[0]: ", tup1[0])
print("tup2[1:5]: ", tup2[1:5])
### Tuple and List Operattion
## cmp, len , max, min, tuple
di = {"key1": 10, "key2": 20, "key3": 30}
print(di["key1"], "Hi", di.get("key2"))
print(di)
for i in di.keys():
print(di.get(i))
keys = iter(di)
for i in keys:
print(i)
def addme(a, b=2):
return a + b * 2
print(addme(8))
### All parameters (arguments) in the Python language are passed by reference.
# Variable Function definition is here
def printinfo(arg1, *vartuple):
"This prints a variable passed arguments"
print("Output is: ")
print(arg1)
for var in vartuple:
print(var)
return
# Now you can call printinfo function
printinfo(10)
printinfo(70, 60, 50)
### Scope Global and local both
# When you import a module, the Python interpreter searches for the module in the following sequences −
#
# The current directory.
#
# If the module is not found, Python then searches each directory in the shell variable PYTHONPATH.
#
# If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python3/.
# Open a file
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)
print("Closed or not : ", fo.closed)
print("Opening mode : ", fo.mode)
fo.close()
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print("Read String is : ", str)
# Close opened file
fo.close()
# import os
# os.rename(f1,f2)
# os.remove("hi.txt")
os.mkdir("test")
os.chdir("newdir")
os.getcwd()
|
5334395e7d49ca38d4d6a4f87ed68b8f7f800936 | ronin2448/kaggle | /Titantic/src/tutorial/tutorialAnalysis.py | 4,315 | 3.609375 | 4 | '''
Created on Jun 22, 2014
@author: Domingo
'''
import csv as csv
import numpy as np
if __name__ == '__main__':
csv_file_object = csv.reader( open('../data/train.csv', 'rb') )
print("File read")
header = csv_file_object.next() #next() skips the first line which is the header
data = [] # create a list object called data
for row in csv_file_object:
data.append(row)
data = np.array(data) # convert from a list to an array. Be aware each item is currently a string in this format
print("Converted data into a Numpy array")
print(data)
#The size () function counts how many elements are in the array
# and sum() sums them
number_passengers = np.size( data[0::, 1].astype(np.float) )
number_survived = np.sum( data[0::,1].astype(np.float) )
proportion_survivors = number_survived / number_passengers
print(number_passengers)
print(number_survived)
print(proportion_survivors)
women_only_stats = data[0::,4] == "female" # This finds where all the elements in the gender column that equals female
men_only_stats = data[0::,4] != "female" # This finds where all the elements do not equal female (i.e. male)
#using the index from above we select the females and males seperately
women_onboard = data[women_only_stats,1].astype(np.float)
men_onboard = data[men_only_stats,1].astype(np.float)
# Then we find the proportions of them that survived
proportion_women_survived = np.sum(women_onboard) / np.size(women_onboard)
proportion_men_survived = np.sum(men_onboard) / np.size(men_onboard)
#print results!
print 'Proportion of women who survived is %s' % proportion_women_survived
print 'Proportion of men who survived is %s' % proportion_men_survived
# do analysis by binning class and ages...
fare_ceiling = 40
#the modify the data in the Fare column to = 39, if greater or equal to ceiliing
data[ data[0::,9].astype(np.float) >= fare_ceiling, 9 ] = fare_ceiling - 1.0
fare_bracket_size = 10
number_of_price_brackets = fare_ceiling / fare_bracket_size
#I know there were at least 3 classes on board
number_of_classes = 3
#But it is better practice to calculate from data
# Take the length of an array of unique values in column index 2
number_of_classes = len(np.unique(data[0::,2]))
# Initialize the survival table with all zeros
survival_table = np.zeros((2, number_of_classes, number_of_price_brackets))
for i in xrange(number_of_classes): #foreach class
for j in xrange(number_of_price_brackets): # freach price bin
women_only_stats = data[
( data[0::,4] == "female") # is a female
& (data[0::,2].astype(np.float) == i+1) # was in the ith class
& (data[0:,9].astype(np.float) >= j*fare_bracket_size) # was greater than this bin
& (data[0:,9].astype(np.float) < (j+1)*fare_bracket_size) # was less than the next bin in the 2nd col
, 1]
men_only_stats = data[
( data[0::,4] != "female") # is a male
& (data[0::,2].astype(np.float) == i+1) # was in the ith class
& (data[0:,9].astype(np.float) >= j*fare_bracket_size) # was greater than this bin
& (data[0:,9].astype(np.float) < (j+1)*fare_bracket_size) # was less than the next bin in the 2nd col
, 1]
survival_table[0,i,j] = np.mean(women_only_stats.astype(np.float))
survival_table[1,i,j] = np.mean(men_only_stats.astype(np.float))
survival_table[ survival_table != survival_table] = 0
print(survival_table)
survival_table[ survival_table < 0.5 ] = 0
survival_table[ survival_table >= 0.5] = 1
print(survival_table)
pass |
aa7f61472af49b92e5bf973f74ea017802b7a6d4 | Linus-MK/AtCoder | /AtCoder_unofficial/chokudai_speedrun_002_f_2.py | 510 | 3.640625 | 4 | # setに入れてしまってその長さとかで解けないかな?
# setやlistはsetに入れられない。
# 1つの数に置き換えれば良い 大*10**10 + 小 なら
# Python (3.8.2)で462ms
n = int(input())
ans = set()
for _ in range(n):
a, b = list(map(int, input().split()))
if a < b:
a, b = b, a
# どちらを使ってもほぼ同じ速度だった。ビットシフトのほうが速そうだけど。
ans.add(a*10**10 + b)
# ans.add((a<<30) + b)
print(len(ans))
|
d438aa349aa2976a8da5f83574a4473cca6b20a8 | vgsprasad/Python_codes | /prime1s.py | 336 | 3.734375 | 4 | def numones(num):
count = 0
while(num & (num-1)):
count = count +1
num = num & (num-1)
return count
def countPrimeSetBits(self, L, R):
count = 0
primelist = [2,3,5,7,11,13,17,19]
for X in range(L,R):
if numones(X) in primelist:
count = count+1
return count
|
7716238a1a85eea8588ad5bb95cd755742e5f0cd | AaronLack/C200 | /Assignment5/magic.py | 224 | 3.828125 | 4 | def magic(x):
x= (((15+x)*3)-(9))/(3)-12
return x
if __name__=="__main__":
x = input("Pick any positive whole number: ")
x = int(x)
print("Your number was", magic(x))
if __name__=="main":
pass |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 290