blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1456a4b16db3807dadac19921db94482535ec00e | JaeGyu/PythonEx_1 | /ModifyTest.py | 417 | 3.640625 | 4 | class Mody:
def __init__(self, name = "test"):
self.__name = name
self.age = 23
self._addr = "suwon"
self.__phone = "010"
def get_name(self):
return self.__name
def get_phone(self):
return self.__phone
def mody_main(self):
mo = Mody("ali... |
8a12202e8b7f9e7cb877534cac81b9b0bb9c829d | JaeGyu/PythonEx_1 | /ex15.py | 449 | 3.5 | 4 | #_*_ coding: utf-8 _*_
import sys
args = sys.argv
if len(args) < 2:
sys.exit("ϰ ϸ ũƮ ڿ μ Է ϼ.")
filename = args[1]
txt = open(filename,"r")
print " %r :" % filename
print txt.read()
txt.close()
print " ̸ ٽ Է ּ"
file_again = raw_input("> ")
txt_again = open(file_again,"r")
print txt_again.read()
txt_again... |
0ca452691ccbc94a8b7a8df8a48735d7094f3237 | JaeGyu/PythonEx_1 | /20160104_1.py | 790 | 3.765625 | 4 | #_*_ coding: utf-8 _*_
print True * 2
print False * 30
print bool(0)
print bool(1)
print bool(-1)
print bool(0.0)
print bool(0.1)
if 0 == False:
print '참'
else:
print '거짓'
print bool('')
print bool(' ')
print bool(None)
print bool({})
print bool([])
if 0 == True:
print "참"
else:
print "거짓"
print [] or () # ... |
db00d8d227217a282f02635af2c258e0a9ed3be9 | JaeGyu/PythonEx_1 | /StackTest.py | 635 | 3.84375 | 4 | class Stack:
store = []
def push(self, data):
self.store.append(data)
def isEmpty(self):
return len(self.store) == 0
def pop(self):
return self.store.pop()
def top(self):
return self.store[len(self.store) - 1]
def size(self):
return len(self.... |
9b0cd969911cce8d7cefcb3b34541eb291244679 | JaeGyu/PythonEx_1 | /20160124_2.py | 1,072 | 3.859375 | 4 | #_*_ coding: utf-8 _*_
a = set([1,2,3])
print type(a)
print a
a = set((1,2,2,2,2,2,1))
print a
c = set({'a':1,'b':2})
print c
c = set({'a':1,'b':2}.values())
print c
B = set([4,5,6,10,20,30])
C = set([10,20,30])
print C.issubset(B)
print C <= B
print B.issuperset(C)
print B >= C
print
A = set([1,2,3,4,5,6,7,... |
6f1cea6d55a685f16ef3791eafc31b5e465e32cb | JaeGyu/PythonEx_1 | /House2.py | 791 | 3.96875 | 4 | class House2(object):
company = "Python Factory"
def __init__(self, year, acreages, address, price):
self.year = year
self.acreages = acreages
self.address = address
self.price = price
def show_company(self):
print(House2.company)
def change_price(self,... |
a9dece4a4d2acdee564eda57d3b3f4db52adfc69 | JaeGyu/PythonEx_1 | /20170104_1.py | 476 | 3.578125 | 4 |
outter = 77
def func():
global outter
outter += 23
print(outter)
func()
outData = [77]
def func2(param):
param[0] += 23
print(param)
func2(outData)
class A(object):
def whoami(self):
return self.__class__.__name__
a = A()
print(a.whoami())
class Abcdefg(A):
pass
abc = A... |
4f21366c6bbcbb605c0b0de3e06195b504646c91 | jorie1703/workshops | /Prac02/ASCII_Table.py | 180 | 3.65625 | 4 | __author__ = 'jc226070'
lower = 33
upper = 100
print("ASCII Code CHAR")
print("---------- ----")
for i in range(lower, upper):
print("{:>6} {:>8}".format(i, chr(i)))
|
07e9c0bc2d278391ec0cc3be016a330554dbb171 | joao-afonso-pereira/Battleship_AI | /battleship.py | 9,466 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 20 20:44:40 2020
@author: João Afonso
"""
import numpy as np
import random
import scipy.ndimage as ndimage
import matplotlib.pyplot as plt
import sys
import matplotlib
matplotlib.use("Agg")
# method used with the ndimage function that checks the neighbors of a boat cel... |
dfd894e6b95ebf85d1095b0d7a10009985438f13 | meganc0530/36-650 | /Homework_5/q9/q9.py | 263 | 4.0625 | 4 | def check_palindrome(string):
if len(string) < 1:
print(True)
else:
if string[0] == string[-1]:
return(check_palindrome(string[1:-1]))
else:
print(False)
check_palindrome("kayak")
check_palindrome("hello") |
bbbfdb25b79291e2c1dea012d83928f3e6e1af45 | meganc0530/36-650 | /Homework 6/q6/q6.py | 2,498 | 4.4375 | 4 | class Node(object):
def __init__(self, data):
self.data = data
self.previous = None
# Class to create a Reverse Linked List
class ReverseLinkedList(object):
def __init__(self, tail=None):
self.tail = tail
# Print the reverse linked list
def print_list(self):
if self.ta... |
8c2ebde11321eab6d57a148e3338837719845b46 | mtkwT/Numerical-Caluculation | /algorithm/gauss.py | 1,634 | 3.796875 | 4 | from my_library import *
# 部分ピボット選択付きの前進消去をする関数
def forward_elimination_pivoting(A, b, N):
for piv in range(N):
# 各列で値が最大となる行を見つける
max_val_row = piv
max_val = 0.0
for row in range(piv, N, 1):
if (abs(A[row][piv]) > max_val):
# 値が最大の行
max_v... |
44e3b8961412a20ca0d66de46913233fb62dd404 | linshiu/python | /think_python/10_02_capitalize_nested.py | 327 | 3.609375 | 4 | def capitalize_all(t):
res =[]
for s in t:
res.append(s.capitalize())
return res
def capitalize_nested(nested_list):
new = []
for t in nested_list:
new.extend(capitalize_all(t))
return new
test = [['hi','ook'],['bye']]
x= capitalize_nested(... |
fb7cfee52daef7bfb5e9a2214e0e7723e38ea529 | linshiu/python | /Leetcode/leetcode344_reverseString.py | 336 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode 344 - Reverse String
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
"""
def reverseString(s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
#%% Test
test = "hello"
rev... |
4d5c849984dfea171a5ab1b58ef3939f1b6d28a9 | linshiu/python | /Leetcode/leetcode104_maxDepth.py | 1,893 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode 104. Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest
path from the root node down to the farthest leaf node.
"""
#%% Solution 1
# Definition for a binary tree node.
class TreeNode(object):
... |
bd1ee5f00c3c9600576def0d562859e9f3e20c61 | linshiu/python | /Leetcode/leetcode20_isValidParenthesis.py | 1,238 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode - 20 - Valid Parenthesis
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all
valid but "(]" and "([)]" are not.
"""
#%% Function
def isVal... |
85eaf3aa7e1e40f6a28ddff49d0f4d9b6683b146 | linshiu/python | /Leetcode/leetcode070_climbStairs.py | 1,680 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode 70. - Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps.
In how many distinct ways can you climb to the top?
Solution:
Think like a decision treen starting at n, next level can take 1 step (n-1) or... |
1d6951c621ac22dee9dc9b8a38f1b8c3e096bbeb | linshiu/python | /Leetcode/leetcode_198_house_robber.py | 1,808 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode - 198 - House Robber
You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed, the only constraint
stopping you from robbing each of them is that adjacent houses have security
system connected and it will automatically... |
7097a378658ac9745e281e5eab37f1ec06a9a848 | linshiu/python | /data_structures_algorithms/problem_solving_data_structures_algorithms/chap04_recursion/isPalindrome.py | 1,529 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Problem Solving with Algorithms and Data Structures, Brad Miller
Chapter 4: Recursion
Palindrome
IDE: Spyder, Python 3
Check if word is a palindrome using recursion.
A string is a palindrome if it is spelled the same both forward
and backward. for example: radar is a palindrome. for bonu... |
ad968fffa3591cc4fa988ec63f6c7a7d82aeedbb | linshiu/python | /think_python/10_13_interlock.py | 1,662 | 4.5 | 4 | # -*- coding: cp1252 -*-
'''
Two words 'interlock' if taking alternating letters from each forms a new
word. For example, 'shoe' and 'cold' interlock to form schooled.'''
'''
Write a program that finds all pairs of words that interlock'''
from bisect import bisect_left
def make_word_list():
"""Reads... |
b2604bc36cb0169b8e40cbc4386f7c54b7a6379a | linshiu/python | /data_structures_algorithms/problem_solving_data_structures_algorithms/chap05_searching_sorting/quickSort.py | 3,907 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Problem Solving with Algorithms and Data Structures, Brad Miller
Chapter 5: Searching and Sorting
IDE: Spyder, Python 3
Quick Sort
"""
import timeit
import matplotlib.pyplot as plt
import numpy.random as nprnd
import numpy as np
import random
#%% Function ####################################... |
9a9e4f1b4cfe26bb87a22fdb9237f27970bac857 | linshiu/python | /misc/findTop.py | 1,688 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Find the top K in a list of tuples
"""
#%% function
def getFrequency(list_tuples, pos):
"""Gets the frequency of each value of a certain index position in tuple
Args:
list_tuples (list): list of tuples
pos (int): index position of items to find frequency
... |
7389267b5249cc6303ed915fb456e5db443f8ab0 | linshiu/python | /data_structures_algorithms/problem_solving_data_structures_algorithms/chap05_searching_sorting/insertionSort.py | 2,512 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Problem Solving with Algorithms and Data Structures, Brad Miller
Chapter 5: Searching and Sorting
IDE: Spyder, Python 3
Selection Sort
"""
import timeit
import matplotlib.pyplot as plt
import numpy.random as nprnd
import numpy as np
#%% Function #############################################... |
7546879d2d47a435e6eb65706e87e035447aef92 | gFilleti/Google-IT-Automation | /interect_os/4st_week/commannd_line.py | 1,903 | 4.65625 | 5 | #!/usr/bin/env python3.8
import sys
import os
#Command_line arguments are parameters that are passed to a program when it's started
print(sys.argv) # this will print the command-line arguments that are passed with the program.
#if we call ./command_line.py it will print the list of commands passed, i... |
efffa34cf3d39654e3bcc17fb79011c23b808c75 | gFilleti/Google-IT-Automation | /interect_os/2st_week/files/opening_file.py | 2,954 | 3.921875 | 4 | #!/usr/bin/env python3.8
import os
os.chdir("base_files")#with this the scrip can work in any OS
path = os.path.abspath("long_text.txt")# abspath function will return the absolute path of the filename
# in this case i could use path = "long_text.txt" becouse already
file = open(path... |
ec4019b7e098e7a5598dbd550ae2bf580709c004 | khgupta/DFS-1 | /Problem1.py | 1,643 | 3.734375 | 4 |
import collections
#Time complexity: O(m*n)
#Space complexity: O(m*n)
#Works on leetcode: yes
#Approach: We use a queue to perform BFS and start from the source cell. While queue is not empty, we pop from it and see
#if the neighbouring cells are within bound and of original color, we add those cells to the queue.
c... |
b34c0bed2da1010ac95123fece372043abdc47a8 | dawahent/gradeSche | /sampleInputOutput/sampleIO.py | 892 | 3.5625 | 4 | ##Taken Semesters
##working hours: a collection mapping course to hours of each semester
sem0_hr = {'cs101':15, 'cs125':20, 'cs173':15}
sem1_hr = {'cs225':22, 'cs223':17, 'cs374':35}
##semesterDict: a collection storing info of a semester
sem0 = {'workload':6, 'hours':sem0_hr}
sem1 = {'workload':9, 'hours':sem1_hr}
##s... |
ea2a2b182b63a3d39944be1ad094b65102b4da2f | k-lowen/5001-Final-Project-Sample | /WOODS Quad.py | 7,602 | 3.90625 | 4 | #HOUSE MAZE KEY
# Woods D1 -- Down
# Woods D2 --Up (or portal)
# Woods D3 -- Down
# Woods D4 -- up (or portal)
# Woods D5 -- down (up --> surprise portal to water D2)
# Woods D6 -- up
#CHANGE MENUS TO THEME
def simple_menu():
print("1. Upstairs -- enter -- up")
print("2. Downstairs -- enter -- down")
def st... |
40d77885ad353fc3e3ea75809fe8414c1de76528 | sasidhar-programmer/python | /python/linked_list/LinkedList.py | 3,092 | 3.859375 | 4 |
class Node :
def __init__(self, val) :
self.val = val
self.next = None
class LinkedList :
def __init__(self) :
self.head = self.tail = None
def is_head_none(self) :
if self.head is None :
return True
def append(self, val) :
if... |
3a558f8ccc1ed823d548ce6c4bf513b7bfbe176f | nguaki/python | /environment/pandas/8_concat/concat.py | 1,318 | 3.578125 | 4 | import pandas as pd
india_weather = pd.DataFrame({
"city": ["mumbai","delhi","banglore"],
"temperature": [32,45,30],
"humidity": [80, 60, 78]
})
print (india_weather)
us_weather = pd.DataFrame({
"city": ["new york","chicago","orlando"],
"temperature": [21,14,35],
"humidity": [68, 65, 75]
})
p... |
bf96890cb51f02b129f6639241dce779d66878ce | nguaki/python | /environment/pandas/list2df.py | 389 | 3.859375 | 4 | import pandas as pd
l1 = []
l2 = []
l3 = []
for i in range(0,9):
l1.append(i)
l2.append(i+1)
l3.append(i+2)
df1 = pd.DataFrame()
df1['col1'] = l1
df1['col2'] = l2
df1['col3'] = l3
print(df1)
df2 = pd.DataFrame( { 'colA': l1, 'colB': l2, 'colC': l3})
print(df2)
import numpy as np
df3 = pd.DataFram... |
ca535443d132051c72e9db05f5eca389be8308ae | nguaki/python | /workspace/pandas/4_read_write_to_excel/4_read_writeto_excel.py | 1,927 | 3.65625 | 4 | import pandas as pd
df = pd.read_csv("stock_data.csv")
print(df)
#Removes header
print("====")
df = pd.read_csv("stock_data.csv", skiprows=1)
print(df)
#Removes header
print("XXXX")
df = pd.read_csv("stock_data.csv", header=1)
print(df)
#New column headers and also removes index
df = pd.read_csv("stock_data.csv", h... |
5bf7deebd66e8178018035151f24f7833bf7f2e8 | nguaki/python | /environment/deck_card1.py | 2,553 | 3.859375 | 4 | import random
class Card(object):
def __init__(self, suite, rank):
self.suite = suite
self.rank = rank
def show(self):
print( "{} of {}".format(self.suite, self.rank) )
class Deck(object):
def __init__(self):
self.cards = []
self.build()
def ... |
329cbadc867b96ae1b25403f993ad6b33c79909b | javierkos/Taskrabbit-analysis | /discarded_code/store_postcodes.py | 291 | 3.625 | 4 | import sqlite3
conn = sqlite3.connect('databases/taskrabbit_ny.db')
c = conn.cursor()
with open("ny_n.txt") as f:
content = f.readlines()
for line in content:
postcode = line
c.execute("INSERT INTO locations(name,city_id) VALUES('" + postcode + "',1)")
conn.commit()
c.close() |
47963eaf81b88f5fcd73a31eb9194f9b8564d837 | TheVioletBaron/voting-map | /region.py | 3,354 | 3.796875 | 4 | """
Casey Edmonds-Estes
Project 4
11/13/18
"""
class Region:
"""
A region (represented by a list of long/lat coordinates) along with
republican, democrat, and other vote counts.
"""
def __init__(self, coords, r_votes, d_votes, o_votes):
self.coords = coords
self.republican_votes = ... |
979b9efab40df77b37d3aed9a5546b3c09448a05 | Seariell/basics-of-python | /hw5/task_7.py | 2,362 | 3.5625 | 4 | # homework lesson: 5, task: 7
"""
Создать вручную и заполнить несколькими строками текстовый файл, в котором каждая строка должна содержать
данные о фирме: название, форма собственности, выручка, издержки.
Пример строки файла: firm_1 ООО 10000 5000.
Необходимо построчно прочитать файл, вычислить прибыль каждой компании... |
c42b1020a823d7d5133848e28f61828c9457575f | Seariell/basics-of-python | /hw7/task_2.py | 2,499 | 3.625 | 4 | # homework lesson: 7, task: 2
"""
2. Реализовать проект расчета суммарного расхода ткани на производство одежды.
Основная сущность (класс) этого проекта — одежда, которая может иметь определенное название.
К типам одежды в этом проекте относятся пальто и костюм. У этих типов одежды существуют параметры:
размер (для пал... |
c7a57382792775f13019b2f828511db676506b10 | Seariell/basics-of-python | /hw6/task_1.py | 2,606 | 3.796875 | 4 | # homework lesson: 6, task: 1
"""
Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) и метод running (запуск).
Атрибут реализовать как приватный. В рамках метода реализовать переключение светофора в режимы:
красный, желтый, зеленый. Продолжительность первого состояния (красный) составля... |
c7b70abd45789ff29866de3855274a59735d1ba8 | Seariell/basics-of-python | /hw5/task_2.py | 710 | 4.21875 | 4 | # homework lesson: 5, task: 2
"""
Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк,
количества слов в каждой строке.
"""
with open('task_2.txt') as my_file:
lines = my_file.readlines()
num_lines = len(lines)
words = []
for ind, line in enumerat... |
eef4c5b10cab0caf9c048f27299a03ccbcdb95d0 | shibaeff/Console-Game-TPP | /src/abstract_classes/abstract_class_test.py | 535 | 3.5 | 4 | import unittest as ut
from src.abstract_classes import abstract_classes as ac
class TestAbstract(ut.TestCase):
def test_creation(self):
abs_char = ac.AbsCharacter("Jim", 2, 2, list())
self.assertEquals(type(abs_char), ac.AbsCharacter)
abs_manager = ac.AbsManager("Jim", 2, 2, 2, 2, list(... |
2eda7dba11a0d0c7bdcf7db559ffaa7b721f51b1 | PrasamsaNeelam/CSPP1 | /cspp1-practice/m15/Inheritance-Exercise on genPrimes/gen_primes.py | 532 | 3.890625 | 4 | #define the gen_primes function here
def genPrimes(a):
n = 2
c = 0
while c < a:
cnt = 0
for i in range(1, n):
if n%i == 0:
cnt += 1
if cnt == 1:
yield n
c += 1
n += 1
def main():
data = input()
l = data.split()
... |
4c12fbbc8e546e548032ed08962ec4990426b6ec | PrasamsaNeelam/CSPP1 | /cspp1-practice/cspp1-assignments/m10/p1/assignment1.py | 749 | 4.09375 | 4 | '''
Author: Prasamsa
Date: 9 august 2018
'''
def get_available_letters(letters_guessed):
'''
:param letters_guessed: list, what letters have been guessed so far
returns: string, comprised of letters that represents what letters have not
yet been guessed.
'''
string = "abcdefghijklmnopqrstuvwx... |
38c69d67618eeae97c7d570456a0d33d447b6031 | PrasamsaNeelam/CSPP1 | /cspp1-practice/m8/power using Iteration/power_iter.py | 456 | 4.0625 | 4 | '''
Author: Prasamsa
Date: 7 august 2018
'''
def iter_power(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
result = 1
while exp > 0:
result = result*base
exp -= 1
return result
def main():
'''enter values of base and exponent''... |
d83b18c4c806da3643e172d58d2196f56a3b1076 | PrasamsaNeelam/CSPP1 | /cspp1-practice/m3/sum_1_end.py | 72 | 3.65625 | 4 | i=1
j=int(input("Enter a number"))
s=0
while(i<=j):
s+=i
i+=1
print(s) |
034e647d687a68f41ebc3a1fdd0cc339ea421787 | PrasamsaNeelam/CSPP1 | /cspp1-practice/cspp1-assignments/m5/p3/square_root_bisection.py | 537 | 4 | 4 | '''
Author: Prasamsa
Date: 6 august 2018
'''
def main():
'''input the value to find square root'''
square_input = int(input())
epsilon = 0.01
low_value = 0.0
high_value = square_input
ans_value = (high_value + low_value)/2.0
while abs(ans_value**2 - square_input) >= epsilon:
if ans_... |
78a72262835712fa282d53d119bd254fe03a6a96 | davidgoldcode/cs-guided-project-problem-solving | /src/demonstration_06.py | 668 | 4 | 4 | """
Challenge #6:
Return the number (count) of vowels in the given string.
We will consider `a, e, i, o, u as vowels for this challenge (but not y).
The input string will only consist of lower case letters and/or spaces.
"""
# def get_count(input_str: str) -> int:
# vowels = ['a', 'e', 'i', 'o', 'u']
# cou... |
78ff3905c2631ed72dba21cc4b87d36f98b7658b | kumastry/atcoder | /arc/035/035a.py | 206 | 3.671875 | 4 | s = input()
n = len(s)
f = True
for i in range(n):
if(s[i] != s[n - i - 1]):
if(s[i] != '*' and s[n-1-i] != '*'):
f = False
if(f):
print("YES")
else:
print("NO")
|
a42a64d9ba79053f065fc8d6101002588f1103d3 | kumastry/atcoder | /arc/017/017a.py | 104 | 3.5625 | 4 | n = int(input())
i = 2
while(i*i <= n):
if(n%i==0):
print("YES")
exit()
print("NO") |
27a73a63433263089cfc2052b4c612a118f23da5 | kumastry/atcoder | /arc/032/032a.py | 262 | 3.90625 | 4 | n = int(input())
def is_prime(n):
if(n < 2):
return False
i = 2
while(i*i <= n):
if(n%i == 0):
return False
i = i + 1
return True
if(is_prime(n*(n+1)/2)):
print('WANWAN')
else:
print("BOWWOW")
|
765268171d032764005fa92961bde60654112c0a | natkam/adventofcode | /2020/03_toboggan_trajectory.py | 901 | 3.703125 | 4 | import functools
import operator
def count_trees(step_right: int, step_down: int = 1) -> int:
trees_count = 0
x = 0
for line in FOREST_MAP[::step_down]:
if line[x] == "#":
trees_count += 1
x = (x + step_right) % LINE_LEN
return trees_count
def solve_part_one():
# mov... |
798c512c90f79301de32177a888c2099adde8e74 | natkam/adventofcode | /2020/12_ferry.py | 2,156 | 3.71875 | 4 | from typing import List, Tuple
FULL_ANGLE = 360
def solve_part_one(instructions: List[Tuple[str, int]]) -> int:
angles = {0: "N", 90: "E", 180: "S", 270: "W"}
position = {"x": 0, "y": 0}
angle = 90
for action, val in instructions:
if action == "L":
angle = (angle - val) % FULL_AN... |
f995d153d6a0bce34873d8f96f6aeae3cf2606a0 | natkam/adventofcode | /2017/aoc_05_jumps_2.py | 735 | 3.65625 | 4 | """
Now, the jumps are even stranger: after each jump, if the offset was three or
more, instead decrease it by 1. Otherwise, increase it by 1 as before.
"""
with open('05_input.txt', 'r') as f:
data = f.read()
offsets = [int(offset) for offset in data.splitlines()]
def jump(offsets):
position = 0
jump_co... |
c754e0c11d2528bb1f0fc7e3d3bff8be3958a275 | marlonjames71/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,701 | 4.28125 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort( arr ):
print(f"Start: {arr}")
# loop through n-1 elements
for i in range(0, len(arr) - 1):
# print(f"Index: {i}, Array = {arr}")
# cur_index = i
smallest_index = i
# TO-DO: find next smallest element
... |
324020667b0d4f7a5f57bc4c6505b2f28cd95206 | Amapolita/MITx--6.00.1x- | /W2/L3/problem9.py | 693 | 3.90625 | 4 | # L3 PROBLEM 9
# Francisco Javier Pena Sanchez
lo, hi, status = 0, 100, True
mid = (hi + lo)/2
print 'Please think of a number between 0 and 100!'
while status == True:
print ("Is your number " + str(mid) + "?")
guess_number = raw_input( "Enter 'h' to indicate the guess is too high. Enter 'l' to indicate... |
07aaf5542a630d5260cdc5c5d69e311d743b9d28 | connor-prinster/python-scripts | /MultiAgent/roomba/obstacles/animal.py | 2,464 | 3.546875 | 4 | import random
from enums.directions import Direction
class Animal:
direction = Direction.UP
def __init__(self, x, y, walls, dropOffs):
self.x = x
self.y = y
self.walls = walls
self.dropOffs = dropOffs
def getPos(self):
return {'x': self.x, 'y': self.y}
de... |
1b8f57660309009c4386dd58e9399512de3eb44f | connor-prinster/python-scripts | /AdvancedAlgorithms/Assn2/findXAssn2.py | 335 | 3.75 | 4 | arr1 = [1, 2, 3, 4, 5]
arr2 = [6, 7, 8, 9, 10]
value = 11
while arr1 and arr2:
if arr1[0] + arr2[-1] == value:
print("found value", value, ". First value:", arr1[0], " Second value:", arr2[-1])
quit()
elif arr1[0] + arr2[-1] > value:
del arr2[-1]
elif arr1[0] + arr2[-1] < value:
del arr1[-1]
print("not th... |
83c0945c7faa7e3ff5817e12b46d3e381983716b | kadensungbincho/Online_Lectures | /Coursera/Introduction_to_apache_spark_and_aws/_59ace373ac7c38094270689be415e205_week-1-resources/primes/primes_1-6.py | 1,561 | 4 | 4 | # based on tutorial on https://districtdatalabs.silvrback.com/getting-started-with-spark-in-python
# for more info: https://spark.apache.org/docs/1.6.3/programming-guide.html
from pyspark import SparkContext, SparkConf
from math import sqrt
def isprime(n):
""" check if integer n is a prime """
# mak... |
aba0a4ade5ad94f580324226b415782f55087761 | hoperose/info206_exercises_Yu | /meeting7/wrapped_Yu.py | 706 | 4.0625 | 4 |
def sum_digits(n): #Define a function which takes an int and returns the sum of its (positive value) digits
'''Returns the sum of all digits (positive value) in the integer'''
n = abs(n)
s = 0
while n:
s += n % 10
n //= 10
return s
def diff_sum_digits(n): #Define a functon that "... |
816b5aaeb7c2925b64b7a1fa549941b8c40a1d22 | hoperose/info206_exercises_Yu | /meeting8/alpha-order_Yu.py | 253 | 4.15625 | 4 | #create a loop to search for the common letter between two string entries
w1 = input("Please enter the first word: ")
w2 = input("Please enter the second word: ")
cl = list(set(w1) & set(w2))
scl = ''.join(sorted(cl))
print("Letters in common: ", scl)
|
267d019dffc84178315082288adae6e4235c6b4d | hoperose/info206_exercises_Yu | /meeting6/exhaustivesearch_Yu.py | 828 | 4.21875 | 4 | #!/usr/bin/python3
x = float(input("enter a number: "))
epsilon = 0.1
num_guesses = 0
ans = 0.0 # ans stands for the guess answer
while ans * ans <= x:
ans += epsilon
num_guesses += 1
print("number of guesses =", num_guesses)
print(ans, "is close to square root of", x)
# the results of entering 10 ... |
4816d5fbfe04bb7fa65b5507c73079514fd8cda7 | ariki4160/vivo_gold | /simpleblog/dblog/models.py | 2,387 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""Django model classes for a simple Blog site
This example shows a one-to-many relationship between a
Blog and its Comments and various computed fields.
"""
from django.db import models
class Blog(models.Model):
"""The class representing an entry in the blog"""
"""The title ... |
0c69d669e7575cb208e0126ef2505d1690d964fd | AdityaPutraS/Tubes-Stima-1 | /scorer.py | 592 | 3.59375 | 4 | def score(string):
try:
score = (abs(24 - int(eval(string) + 0.01))) * (-1) #Epsilon 1/100
except (ZeroDivisionError, SyntaxError):
score = -10
lastPar = False
for char in string:
if char == '+':
score += 5
elif char == '-':
score += 4... |
c4e7e3ddc02dff5d49ad86e3bcdf31c080e3e367 | bbekgit/Python-Tutorial | /pyTutorial7/Programming.py | 270 | 4.03125 | 4 | # here our programming basics starts
a, b = 0, 1
while a < 10:
print(a)
a, b = b, a+b
# the sum of two elements defines the next: Fibonacci series
i = 256*256
print('The value of i is', i)
a, b = 0, 1
while a < 1000:
print(a, end=',')
a, b = b, a+b
|
fb32694d55b56dcedf1d88258ebdaebb940f3639 | IamFer/Adivina_Numero | /AdivinaNumero.py | 2,128 | 3.609375 | 4 | # Reto 01 - Adivina en que numero estoy pensando - Martínez Cruz Fernando Amador
import random, time, os
from Colores import Color
from Sonidos import Reproducir
intervalo = [1, 100]
historial = []
numero_pensado = random.randint(intervalo[0], intervalo[1])
Reproducir.INICIO.play()
print(Color.AZUL + "==============... |
fa7e3ef6d6469e5d2750d3952472be4cccf77cb8 | PhilipCastiglione/SIT215_PBL4 | /src/medical_cost.py | 562 | 3.5625 | 4 | import pandas as pd
# our data is a set of medical insurance costs for individuals
# each individual is recorded with the following data (features):
#
# - age (years, discrete value)
# - sex (binary)
# - bmi (continuous value)
# - children (number, discrete value)
# - smoker (binary)
# - region (categorica... |
b953339212885afd30986d844ae4aacd01e95f3e | nhendry05/python | /_python/for_loop_basic1.py | 672 | 3.609375 | 4 | #Nicole Hendry
#Loops: Basic I
#Basic
for basic in range(0, 151, 1):
print(basic)
#Multiples of five
for multiples in range (5, 1001, 5):
print(multiples)
#Counting, the Dojo Way
for dojo in range (1, 101, 1):
if dojo%10 == 0:
print("Coding Dojo")
elif dojo%5 == 0:
print("Coding")
... |
70178dd72b0db08ecc05a0ada8d2cb027a56620a | msam04/PyPr | /SimpleQuiz.py | 2,171 | 3.875 | 4 |
# coding: utf-8
# In[2]:
import random
continue_flag = True
while (continue_flag):
try:
difficulty = input("Please choose the level of difficulty (easy(1), intermediate(2), hard(3)): ")
difficulty = int(difficulty)
if(int(difficulty) != 1 and int(difficulty) != 2 and int(difficulty) !=... |
de0c435302b936cb8c64a51b9189ba02958e45a9 | kylefeng28/dragonfly-scripts | /utils/formatting.py | 929 | 3.71875 | 4 | # snake_case
def format_snake(dictation):
""" snake <dictation> """
words = str(dictation).split(" ")
return "_".join(words)
# camelCase
def format_camel(dictation):
""" camel <dictation> """
words = str(dictation).split(" ")
return words[0] + "".join(w.capitalize() for w in words[1:])
# PascalCase (StudleyCaps... |
fa96b358d47ffb099de81c56c1e198207e7a0751 | Heiss/volumio_websocket | /volumio_websocket/api2websocket.py | 967 | 3.5625 | 4 | """Transforms any http api request to a websocket call."""
from .websocket import Websocket
from functools import wraps
from asyncio import sleep
def api2websocket(method, params):
"""Transform method and params from api to websocket calls."""
if method == "commands":
method = params["cmd"]
... |
d65b83bf6e654eee8acea7c437ab7e2d07151c18 | poojamohanty/tic-tac-toe | /Tic_Tac_Toe_Env.py | 3,269 | 3.5 | 4 | # from gym import spaces
import numpy as np
import random
from itertools import groupby
from itertools import product
class TicTacToe():
def __init__(self):
"""initialise the board"""
# initialise state as an array
self.state = [np.nan for _ in range(9)] # initialises the board position,... |
ce08fd228ce3f353e0a13e09da7f1285740f3907 | WialmySales/redes | /REDE/camadas.py | 4,055 | 3.8125 | 4 | #!/usr/bin/python3
# coding: utf-8
""" Classes das camadas TCP/IP """
class CdAplicacao():
def __init__(self, camada):
self.camada = camada
# print("Camada TCP/IP: Aplicação")
def desencapsular(self):
return self.camada
def responsabilidade(self):
return "Responsável pel... |
a1ff2ae8935c2280362458c1c0f7b3b9457e16d9 | ctmackay/cryptography | /alpha.py | 771 | 3.6875 | 4 | import string
# build an alphabet dictionary
def giveAlphabet(case):
alphabet = dict()
if case.upper() == 'U':
for i in range (0,26):
letter = string.ascii_uppercase[i]
alphabet[letter] = i
return alphabet
else:
for i in range (0,26):
letter = st... |
26270eccea20ab1ddef4492adb233327efbfd89a | Shmood00/File-Sorting | /file_sorting.py | 1,066 | 3.640625 | 4 | #!/usr/bin/python3.6
import argparse
import os
def get_files(path):
return os.listdir(path)
def get_extensions(path, file):
file_name, file_ex = os.path.splitext(path+file)
return file_name,file_ex
def make_directories(path, extension):
try:
os.mkdir(path+extension[1:])
except:
... |
80405ccbb3181b2cc30efe06a7d2f8c682009f31 | Tommas10/Scan-directory-and-Rename-Files | /ScanDirectory&RenameFilesv1.1.py | 1,043 | 3.59375 | 4 | #!/usr/bin/env python
#This is small auto Python script file to scan directory and rename files. Under macOS.
#Created by Tommas Huang
#Created date: 2019-07-23
import os
#The OS module in Python provides a way of using operating system dependent functionality.
#The functions that the OS module provides allows you... |
c1e6a7621de7c9ec0ec5acf6a702300e85b32163 | connor9/advent-of-code | /2019/day5a.py | 7,888 | 3.703125 | 4 | # --- Day 5: Sunny with a Chance of Asteroids ---
#
# You're starting to sweat as the ship makes its way toward Mercury. The Elves suggest that you get the air
# conditioner working by upgrading your ship computer to support the Thermal Environment Supervision Terminal.
#
# The Thermal Environment Supervision Terminal ... |
129bbc6a8edd2acb41e65945c797ab7bd7a81220 | connor9/advent-of-code | /2019/day4b.py | 1,756 | 3.734375 | 4 | # --- Part Two ---
#
# An Elf just remembered one more important detail: the two adjacent matching digits are not part of a larger group of matching digits.
#
# Given this additional criterion, but still ignoring the range rule, the following are now true:
#
# 112233 meets these criteria because the digits never de... |
50e7e808dcc6269b361856fd49b3c7e024fd5d5e | laashub-sua/demo-pywinauto | /picker/picker.py | 784 | 3.5625 | 4 | import threading
from pynput import keyboard
from pynput import mouse
"""
monitor the mouse: x, y
paint the x, y, w, h box with red color
monitor the ctrl-keyboard
generate the position index value
"""
def on_move(x, y):
# print('Pointer moved to {0}'.format(
# (x, y)))
pass
def on_activat... |
50f631fbc1b51a9de947a6d20a3b51647aad6a64 | lannwal/exercises | /MAT209/binsearch.py | 229 | 3.96875 | 4 |
def binsearch(x,y,n):
mid = int((x+y)/2)
if n == mid:
print('the value is:', n)
else:
if n > mid:
binsearch(mid,y,n)
else:
binsearch(x,mid,n)
binsearch(1,100,4)
|
e54a337e91fc5933b4dc8bd22e6e9fe144471f6a | lelinrashed/30-Days-of-Python | /iteration_loops/loop.py | 546 | 3.71875 | 4 | my_list = [1, 2, 3, 4, 5, 6]
# for value in my_list:
# print(value)
# print(value)
# for i in range(1, 50):
# print(i)
# for x in 10:
# print(x)
user_1 = {'username': 'rashed', 'id': 1, 'email': 'lelin.rashed784@gmail.com'}
user_2 = {'username': 'lelin', 'id': 2}
my_users = [user_1, user_2]
# for u... |
67f98ac4af723ae6d13b1bf1f3a9985b92c25982 | mfinkel/create_input_file_git | /main.py | 1,699 | 3.515625 | 4 | import load_data
class main(object):
def __init__(self):
print "Started program to create a the input file for the elastic constant calculator"
self.select_inst()
def select_inst(self):
while True:
print "Select Instrument:\n" \
" -->(P)OLDI\n" \
... |
1eb71f7b83c6537750cd358f7c764d417ea95cdb | DarinZhang/lpthw | /ex1/add1.1.py | 474 | 3.53125 | 4 | # -*- coding: utf-8 -*-
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print 'Yay! Printing.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
print "添加一行 你好,世界" #中文乱码。因为用来显示的控制台使用gbk编码。参考:https://www.cnblogs.com/baihuitestsoftware/articles/5230351.html
... |
2aee94b7f70211821ecf9c236f3e9c4c5c0c2e52 | DarinZhang/lpthw | /ex33/add33.py | 735 | 3.828125 | 4 | # -*- coding: utf-8 -*-
def GetNumberList(beginNum, endNum, step):
if (endNum - beginNum) * step <= 0:
return u"警告:您输入的参数无效,无法产生出列表!"
elementsList = []
element = beginNum
if step > 0:
while element < endNum:
elementsList.append(element)
element += step
else:
while element > endNum:
elementsList... |
2459205705fbd2e812d278ec4bad39fbfc4a4527 | DarinZhang/lpthw | /ex28/ex28.py | 973 | 3.515625 | 4 | # -*- coding: utf-8 -*-
print True and True # True
print False and True # False
print 1 == 1 and 2 == 1 # False
print "test" == "test" # True
print 1 == 1 or 2 != 1 # True
print True and 1 == 1 # True
print False and 0 != 0 # False
print True or 1 == 1 # True
print "test" == "testing" # False
print 1 != 0 and 2 == 1 ... |
0269cc4d7db97ee4d29ee55b88f39a8269c764df | nadavWeisler/IntroToCS | /IntroToCS_ex9/game.py | 4,939 | 4 | 4 | import helper
import car
import board
import sys
import os.path
class Game:
"""
Add class description here
"""
def __init__(self, board):
"""
Initialize a new Game object.
:param board: An object of type board
"""
# You may assume board follows the API
... |
e7fd0592815ffc490b006f8b242516858bb2d108 | nadavWeisler/IntroToCS | /IntroToCS_ex3/ex3.py | 3,131 | 3.96875 | 4 | #############################################################
# FILE : ex3.py
# WRITER : Nadav Weisler , weisler , 316493758
# EXERCISE : intro2cs ex3 2019
# DESCRIPTION: Ex3 exercise, contain 9 functions:
# input_list, concat_list, maximum, cyclic,
# seven_boom, histogram, prime_factors,
# cartesian, pairs
#####... |
93156ef3b363753edff2e3be46e557da07360285 | wiltonsg/validador-cpf-cnpj | /cpf-cnpj.py | 3,420 | 3.703125 | 4 | # Este código é um Fork de Pedro Lucas, GitHub: https://github.com/DoisLucas/
# O projeto original está no seguinte endereço: https://github.com/DoisLucas/ValidacaoCPF-CNPJ-Python
#!/usr/bin/env python3
# encoding: <UTF-8>
print("Este script irá verificar se o CPF/CNPJ são válidos ou não.")
documento = input("Digite ... |
182af080d055ec293a04c678b5ff380bbb886fc6 | sruthy-github/sruthy-python-files | /exam q5.py | 98 | 3.984375 | 4 | a=input("Enter string")
if(a==a[::-1]):
print("palindrome")
else:
print("Not palindrome")
|
b819613199ceb20bf28767e9157a70872aca3e41 | sruthy-github/sruthy-python-files | /oop/2.py | 224 | 3.578125 | 4 | class Vehicle:
def print(self,name,nooftyre):
self.name=name
self.nooftyre=nooftyre
print("THE VEHICLES ARE\n ",self.name,self.nooftyre)
v=Vehicle()
v.print("Car",4)
a=Vehicle()
a.print("Bus",6)
|
0b7d55f561e8fca892db1de98ddbc5d9ed74ad39 | sruthy-github/sruthy-python-files | /oop/11.py | 644 | 3.734375 | 4 | class Person: #parent class/base class/super class
def details(self,name,age,gender):
self.name=name
self.age=age
self.gender=gender
def printdetails(self):
print(self.name)
print(self.age)
print(self.gender)
class Student(Person): #child class/derived ... |
73b9f11f2957e1ce62718233e9d949da935b45b8 | sruthy-github/sruthy-python-files | /collections/list/union.py | 200 | 3.71875 | 4 | st1={1,2,3,4,5,6,7,8,9,10}
st2={5,6,7,8,9,10,11,12,13,14,15}
#union
#st3=st1.union(st2)
#print(st3)
#intersection
#st3=st1.intersection(st2)
#print(st3)
#difference
st3=st1.difference(st2)
print(st3) |
f5346def7add9033de3055f82664feb7953be9b9 | sruthy-github/sruthy-python-files | /functions/string5.py | 105 | 3.6875 | 4 | s=input("Enter string")
a=""
for i in s:
if(i!="!@#$%^&*():;{}[]|\+=<>?/,."):
a=s+i
print(a)
|
870307aed018461e6eeaca4cfee077280d24de20 | sruthy-github/sruthy-python-files | /oop/17.py | 778 | 3.859375 | 4 | class Person:
def d1(self,name,age,gender):
self.name=name
self.age=age
self.gender=gender
print("Name:",self.name)
print("Age:",self.age)
print("Gender:",self.gender)
class Parent(Person):
def d2(self,job,salary):
self.job=job
self.salary=salary
... |
d4c538d821c8580d4bd4c2b57b65a6bd5d075925 | sruthy-github/sruthy-python-files | /collections/dictionary/employee.py | 232 | 3.796875 | 4 | employee={"id":"1000","name":"manu","designation":"Manager","salary":30000}
print(employee["name"])
print("company" in employee)
employee["company"]="luminar"
employee["salary"]+=5000
for i in employee:
print(i,":",employee[i])
|
662b678493e03e287262f1b6227b011a0fad3cdf | sruthy-github/sruthy-python-files | /file/numbersread.py | 132 | 3.515625 | 4 | f=open("numbers","r")
lst=[]
sum=0
for numbers in f:
lst.append(int(numbers))
print(lst)
for i in lst:
sum=sum+i
print(sum)
|
ffe08b8dbfd7fb7c86376eb746de1324aeeb40aa | rohitdhull/resume | /tuple.py | 145 | 3.515625 | 4 | x = ['who', 'are', 'you', 'my', 'friend']
print(x)
print(x[1:3])
print(x[4])
print(type(x))
y = ['i', 'am', 'vinay', 'brother']
print(x[1]+y[1])
|
44a0c5a3242e12f19091ca504c1b34091eaa6910 | jddelia/think-python | /Section3/functions.py | 711 | 3.546875 | 4 |
def print_lyrics():
print("I'm a lumberjack and I'm okay")
print("I sleep all night and I work all day")
print()
def repeat_lyrics():
print_lyrics()
print_lyrics()
repeat_lyrics()
print()
def print_twice(yo):
print(yo)
print(yo)
print_twice("Nifty!")
print()
name = input... |
78547498ae12e00879d38d59cba2da9e8fb12e8a | jddelia/think-python | /Section11/dictionary.py | 194 | 3.703125 | 4 | # Program testing the uses of dictionaries.
import pprint
def histogram(n):
d = dict()
for i in n:
d[i] = d.get(i, 0)
d[i] += 1
print(d)
histogram("brontasaurus")
|
13f2b3cff871ccf383086a244b2d20737c518b09 | jddelia/think-python | /Section15/turtle_rect.py | 572 | 4.34375 | 4 | # This program creates a turtle with an OOP rectangle.
import turtle
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Rectangle:
def __init__(self, corner, height, width):
self.corner = corner
self.height = height
self.width = width
corner_1 = Point... |
070e8fe1bb759715aadadb3d900ce5ef7e48b960 | jddelia/think-python | /Section5/conditionals2.py | 513 | 4.09375 | 4 | #Conditionals Ex. 2
import math
print("This program verifies Fermat's Last Theorem.\n\n Select four variables.")
print()
a = int(input("Select the first variable a: "))
b = int(input("Select the second variable b: "))
c = int(input("Select the third variable c: "))
n = int(input("Select the fourth variable n: "))
de... |
b7f9845ce667797d0de8157ff655b17d06e26467 | jddelia/think-python | /Section5/conditionals3.py | 294 | 4.125 | 4 | #Conditionals Exercise 3
def is_triangle():
a = int(input("Select first number: "))
b = int(input("Select second number: "))
c = int(input("Select third number: "))
if (a > b + c) or (b > c + a) or (c > a + b):
print("No")
else:
print("Yes")
is_triangle()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.