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 |
|---|---|---|---|---|---|---|
1426dfb22dc5166aa8ba57adee8b94ed586a03ed | Sat0shi/Cp1404_Pracs | /Prac 5/colour_names.py | 649 | 4.40625 | 4 | colours = {'rebeccapurple': '#663399', 'darkorange': '#ff8c00', 'cyan2': '#00eeee',
'cornflowerblue': '#6495ed', 'darkseagreen': '#8fbc8f', 'deeppink1': '#ff1493',
'darkslateblue': '#483d8b', 'dodgerblue1': '#1e90ff', 'goldenrod': '#daa520',
'lightslateblue': '#8470ff'}
colour_name = inpu... |
47097ab6612e30df6d93ebf52fa0caa14d2d7110 | brittany-morris/Bootcamp-Python-and-Bash-Scripts | /python fullstackVM/lines_lines_lines.py | 259 | 3.65625 | 4 | #!/usr/bin/env python3
import sys
def main():
input_file = sys.argv[1]
output = ''
with open(input_file, 'r') as f:
for line in f:
text = line.strip()
if len(text) > 0:
output += text + ' '
print(output)
if __name__ == '__main__':
main()
|
c4b40b5611a14f302ef0fe9993526cbdecaf2f90 | AMGitsKriss/GWI | /src/preprocess.py | 1,824 | 3.609375 | 4 | import pandas as pd
import numpy as np
# Loading the file. If not csv, assumes hdf
def load_data(filename):
if filename.endswith('.csv'):
return pd.read_csv(filename, index_col=0)
else:
return pd.read_hdf(filename, key='df')
# Load the specified file as a series (squeeze), then name it q3 so i... |
70908d4b96b50f04a2e0df5a6ed4e1158b6e8936 | vpetrigo/courses | /programming/adaptive-python/group_2_1/check_graph_matrix.py | 523 | 3.8125 | 4 | #!/usr/bin/env python3
# coding=utf-8
import sys
def naive_adj_matrix_check(matrix):
n = len(matrix)
for i in range(n):
for j in range(n):
if matrix[i][j] != matrix[j][i]:
return False
else:
return True
def main():
reader = (tuple(map(int, line.split())... |
d27869c33e6ba5a175e74d01c120815a914317cb | Training-and-Learning-Skills/alien_invasion | /ship.py | 1,543 | 3.8125 | 4 | import pygame
class Ship():
def __init__(self, screen, ai_settings):
"""Initializes the spaceship and set your starting position."""
self.screen = screen
self.ai_settings = ai_settings
#load the image of the spaceship and get you rect
self.image = pygame.image.load('images/s... |
8c9ddb9b05a08989c45b160d2a2e325ce750c9e7 | PeterPanonGit/ir_group_project | /preprocessing/_test.py | 843 | 3.53125 | 4 | import calendar
#set firstweekday=0
cal= calendar.Calendar(firstweekday=0)
# for x in cal.iterweekdays():
# print(x)
data_week = []
#for year in range(2004,2009):
# for month in range(1,12):
# year = 2004
# month = 1
# for week in cal.monthdayscalendar(2004, 1):
# for (weekday,monthday) in enumerate(week):
... |
5c999338ad00f46b88246da44db9aeab4a327df2 | AyoKun/CodeKata | /Great.py | 227 | 3.984375 | 4 | n1 = int(input("Enter the first number : "))
n2 = int(input("Enter the second number : "))
n3 = int(input("Enter the third number : "))
grt = n1
if(n2>grt):
grt = n2
if(n3>grt):
grt = n3
print("The Greatest number : ",grt)
|
43c1a57c017425e7039918dd253272253712841b | ColinFendrick/cleaning-data-in-python | /exploring-data/loading-viewing-data.py | 334 | 3.5 | 4 | import pandas as pd
# Read the file into a DataFrame: df
df = pd.read_csv('../_datasets/dob_job_application_filings_subset.csv')
# Print the head of df
print(df.head())
# Print the tail of df
print(df.tail())
# Print the shape of df
print(df.shape)
# Print the columns of df
print(df.columns)
print(df.info)
print(d... |
4de15391ad0a0c7d9cdb4f8906d748fee9efc8a0 | anubhav-shukla/Learnpyhton | /dunc_as_arg.py | 616 | 4.25 | 4 | # sorry not dunc
# it is function
# def square(a):
# return a**2
# map
l=[1,2,3,4]
sq=map(lambda a:a**2,l)
print(list(sq)) #you get the output
# today make a function that take as a input a function\\
def my_map(func,l):
new_list=[]
for item in l:
new_list.append(func(item))
r... |
a9b7014aaeefabb5c62012d7f8e21637592abfdd | TetianaSob/Python-Projects | /access_value_list.py | 877 | 4 | 4 | # Indexes
friends = ["Ashley", "Matt", "Michael"]
print(friends[0]) # Ashley
print(friends[1]) # Matt
print(friends[2]) # Michael
print("\n")
colors = ["purple", "teal", "orange"]
print(colors[0]) # purple
print(colors[1]) # teal
print(colors[2]) # orange
print("\n")
the_best = colors[0]
print(the_bes... |
4c86b589c25f013ae5f1f06bb2d7a75e079322e1 | gwavre/ML_project1 | /scripts/preprocessing.py | 18,365 | 3.875 | 4 | import numpy as np
import matplotlib.pyplot as plt
"""Implements functions that can modify data in any way.
In particular, "utility functions" will help with sampling, shuffling, splitting
without actually pre-processing the data.
"Pre-processing" functions will be able to modify or add features, filter... |
a8c968c0963c6a8e1ccba182dd5ddb6285aab422 | MPI-IS/CityGraph | /city_graph/utils.py | 3,456 | 3.984375 | 4 | """
Utils
=====
Module with different utilities needed for the package.
"""
import collections
import string
import time
from math import sin, cos, sqrt, atan2, radians
from numpy.random import RandomState
# Mean Earth radius in meters.
EARTH_RADIUS_METERS = 6.371 * 1e6
def get_current_time_in_ms():
"""
Re... |
6b8111971500612b1c6010ae73c49d35e24a3ba9 | donyu/euler_project | /p12.py | 307 | 3.890625 | 4 | def factors_count(x):
count = 0
for i in xrange(1, x + 1):
if x % i == 0:
count += 1
return count
def max_divisible_num(max):
tri_num = 1
i = 2
while factors_count(tri_num) < max:
tri_num += i
i += 1
return tri_num
if __name__ == "__main__":
print max_divisible_num(500)
|
bbef15db3e9d0a69178bbe75bce99b0e5215adad | Environmental-Informatics/building-more-complex-programs-with-python-gargeyavunnava | /program_4.2.py | 3,205 | 4.78125 | 5 |
"""
Created on Fri Jan 24 13:50:40 2020
Purdue account name: vvunnava
Github account name: gargeyavunnava
Exercise 4.2, thinkpython 2e
Program description:
Multiple functions are defined to make it easy to draw the three flowers
as shown in fig 4.1, thinkpython 2e
As discussed in the chapter, a 'polyline' funtio... |
a02ec46140ef6cf6ebc0b5bae91959eaf473c102 | Joshuabhad/mypackage | /mypackage/recursion.py | 1,699 | 4.65625 | 5 | def sum_array(array):
"""
Calculate the sum of a list of arrays
Args:
(array): Numbers in a list to be added together
Returns:
int: sum of all numbers in a array added together
Examples:
>>> sum_array([1,2,3,4,5])
15
>> sum_array([1,5,7,3,4])
20
... |
7758810b8fefce67062fd14ed34f41871dda2ea0 | chill1495/RandomCode | /String List Editor/string_list_editor.py | 2,057 | 3.875 | 4 | def string_list_editor(strings):
start_chars = count_chars(strings)
arranged = []
for string in strings: #sort the input list to find median
arranged.append(len(string))
sorted(arranged)
if len(arranged) % 2 == 0: #calculate median
median = (arranged[len(arranged)/2] + arranged[(len(arranged)/2) - 1]) / ... |
97e8f98f5dbc2ab5109a57d452179b96bbc3b7ec | leedale1981/compsci | /insertion_sort/python/insertion_sort.py | 513 | 4.21875 | 4 | def insertion_sort(array):
for j in range(2, len(array)):
i = j - 1;
key = array[j];
while (i > -1 and array[i] > key):
array[i + 1] = array[i];
i = i -1;
array[i + 1] = key;
return array;
unsorted_array = [9, 5, 3, 8, 2, 1, 4, 7, 6, 13, 10, 12, 11];
... |
86a8dc74a19b7d6ec74ee97dbba1d5268d32f556 | achenachena/leetcode | /jianzhi/jump_floor.py | 686 | 3.75 | 4 | """
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法
(先后次序不同算不同的结果)。
"""
# -*- coding:utf-8 -*-
# 递归法
# class Solution:
# def jumpFloor(self, number):
# # write code here
# if number == 1:
# return 1
# if number == 0:
# return 0
# return self.jumpFloor(number ... |
788e304bfe3dccdd75e95cad83d058b57aa921bc | alexandraback/datacollection | /solutions_2463486_1/Python/sealion/Fair-and-Square.py | 588 | 3.515625 | 4 | import math
import sys
def is_palindrome(n):
s = str(n)
l = list(s)
l.reverse()
return list(s) == l
def find_numbers(A, B):
ns = range(int(math.ceil(math.sqrt(A))), int(math.floor(math.sqrt(B))) + 1)
for n in ns:
n2 = n * n
if is_palindrome(n) and is_palindrome(n2):
... |
bd9e8658c2a7d7928516d8b1de0b7d77ea16aa18 | jbhennes/CSCI-220-Programming-1 | /Chapter 5 Strings/readNumericData.py | 2,836 | 4.28125 | 4 | # readNumericData.py
# illustrates how to retrieve numeric data from a file
def main():
#reading data from a file for calculations - fine for integer values
## infileName = "data.txt"
## infileName = "dataWithFloat.txt"
## infile = open(infileName,"r")
## print ("\n*** Integer values ***")
... |
53934f1b1645d147841985e09f7ee40c80d2cf94 | vedadeepta/Tic-Tac-Toe | /LookAhead.py | 1,857 | 3.734375 | 4 | from random import randint
pos = -1
def checkWin(board):
i=0
while i < len(board):
if(board[i] != 'n' and board[i] == board[i+1] and board[i] == board[i+2] and board[i+1] == board[i+2]):
return True
i = i + 3
#columns
i=0
while i < 3:
if(board[i] != 'n' and board[i] == board[i+3] and board[i... |
b54caf2497f920125388e5e8ab64f74255934687 | karan2808/Python-Data-Structures-and-Algorithms | /DFS/MatchSticksToSquare.py | 3,004 | 3.625 | 4 | class Solution:
def makesquare(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
# If there are no matchsticks, then we can't form any square.
if not nums:
return False
# Number of matchsticks
L = len(nums)
# Possible perim... |
ec7836f977187b10a21c36c3c0f9461e8f39f7ff | dujiaojingyu/Personal-programming-exercises | /编程/1月/1.24/斐波那契.py | 136 | 3.609375 | 4 |
def fib(max):
n,a,b = 0,0,1
while n < max:
print(b)
a,b = b,a+b
n += 1
return 'lalalalal'
fib(6) |
aae3fb42325e5ec655c6599832589a00b36139fe | hitesh789/datasharing | /Chp-4 Representing Data and Engineering Features.py | 6,660 | 3.8125 | 4 | %cd C:\Users\bama6012\Desktop\Python My study\data
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# The file has no headers naming the columns, so we pass header=None
# and provide the column names explicitly in "names"
data=pd.read_csv('adult.csv',header=None, index_col=False,
names=... |
376a454f428fb553b51d4685682c5565672c9837 | python-amazon-mws/python-amazon-mws | /mws/utils/collections.py | 4,288 | 3.515625 | 4 | """Data structure utilities."""
from collections.abc import Iterable, Mapping
def unique_list_order_preserved(seq):
"""Returns a unique list of items from the sequence
while preserving original ordering.
The first occurrence of an item is returned in the new sequence:
any subsequent occurrences of th... |
326b36f411a82c8084722aef705757cdbd72aa70 | samskhan/User-Interface-Engineering | /TextEditor.py | 1,621 | 3.5625 | 4 | '''Author: Sams KHan
Class: User Interface Engineering
References: https://www.youtube.com/watch?v=xqDonHEYPgA
https://www.instructables.com/id/Create-a-Simple-Python-Text-Editor/
'''
import sys
from tkinter import *
import tkinter.filedialog as fd
root = Tk()
#Adding text widget
text = Text(root)
text... |
4d86b7416c2e7e3ed010de1535596835b8617974 | aCoffeeYin/pyreco | /repoData/samuel-squawk/allPythonContent.py | 21,221 | 3.546875 | 4 | __FILENAME__ = aggregates
from __future__ import division
"""
An aggregate class is expected to accept two values at
instantiation: 'column' and 'name', and the class
must have two methods 'update(self, row)' and 'value(self)'.
The 'update' method is called for each row, and the 'value'
must return the final... |
9a46d3fdd0076d9eee95fab47466cbe8b52919c8 | gyandhanee/fsdse-python-assignment-8 | /even_numbers.py | 78 | 3.53125 | 4 | def get_even_numbers(num):
return [i for i in range(1,num+1) if i%2 == 0]
|
bcf1e10a8a03c7a1e9aa218f911d08fc79acd01f | vik-tort/hillel | /Homework_/Task_26.py | 282 | 4.03125 | 4 | lst= [2,2,2,3,3]
def sum_diff (lst):
sum_of_even=0
sum_of_odd=0
for i in lst:
if i%2==0:
sum_of_even+=i
else:
sum_of_odd+=i
sum_different=sum_of_even-sum_of_odd
return sum_different
print("Sum different =",sum_diff(lst)) |
29a3092eb99281be431ffea8f6cb5f1d69dc03d5 | rathijeetbhave/dynamicProgramming | /lis.py | 1,256 | 4.03125 | 4 | # The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence
# such that all elements of the subsequence are sorted in increasing order.
# For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}.
# Here w... |
78f94e40efdc38576a200d2289740e2d2170164d | Bobbyb6/PythonProject | /Log_In_Project.py | 994 | 4.03125 | 4 | # Password/username project
def get_attempted_username():
return input('Enter Username: ')
def get_attempted_password():
return input('Enter Password: ')
def get_stored_password():
try:
return data[attempted_username]
except KeyError:
print('This Username is not recognised Enter a ... |
e3d71ee58d969700f507872a2accce2673cb4815 | kunalj101/flask-blog | /sql.py | 602 | 3.9375 | 4 | #sql.py databse connections
#import sqlite
import sqlite3
#create new database, if it does not exist
with sqlite3.connect("blog.db") as connection:
#Get cursor object to execute the SQL commands
c = connection.cursor()
#create the table
c.execute("""CREATE TABLE posts
(title TEXT, post TEXT)""")
#insert dummy ... |
8c0f7fa937fcbe3170d07f25c3fd2c0657279574 | 9bason/pp2 | /TSIS3/1_4.py | 129 | 3.71875 | 4 | arr = list(input().split())
for i in arr:
if i != '0': print(i, end = " ")
for i in arr:
if i == '0': print(i, end = " ") |
ada92058c1960bd4aa2962a851faa20e866e34e4 | GledsonLScruz/Learning-Python | /exercicio2.py | 284 | 4.03125 | 4 | reta1 = float(input('Digite um valor: '))
reta2 = float(input('Digite outro valor: '))
reta3 = float(input('Digite outro valor: '))
if reta1 > abs(reta2 - reta3) and reta1 < reta2 + reta3:
print('Pode formar um tringulo')
else:
print('Não pode formar um triangulo')
|
656462b54463197990029794c16cb30caad8eb7c | cmumman/calculator | /calculator/GUI/counter.py | 412 | 3.8125 | 4 | import Tkinter as tk
counter = 0
def count_label(label):
def count():
global counter
counter += 1
label.config(text=str(counter))
label.after(1000, count)
count()
loop = tk.Tk()
loop.title("counting seconds")
label = tk.Label(loop, fg="red")
label.pack()
count_label(label)
b... |
fe7e7a6244ed78042a73778d3e88a10ccdc16e1b | konradbondu/CodeWars-solutions | /vovel_code.py | 1,141 | 4.40625 | 4 | # Step 1: Create a function called encode() to replace all the lowercase vowels in a given string with numbers
# according to the following pattern:
#
# a -> 1
# e -> 2
# i -> 3
# o -> 4
# u -> 5
# For example, encode("hello") would return "h2ll4". There is no need to worry about uppercase vowels in this kata.
#
# Step... |
e856b91c026eeda8d434810787c682eb8e65c259 | pabb2002/Computer-Science-Labs | /CS1/Python/MoreStringsNotes.py | 1,283 | 4.15625 | 4 | # Strings loops and find/rfind methods
# Why do we use loops with string?
# to go index by index through the string
# this way is long
s = "first"
print s[0]
print s[1]
print s[2]
print s[3]
print s[4]
# but with a loop:
s = "first"
for x in range(len(s)): #range => start to stop, does range run at t... |
f7c605ce3acde6627adbeba7b33e95140952b86b | q737645224/python3 | /python基础/python笔记/day09/exercise/myadd.py | 328 | 3.84375 | 4 | # 练习:
# 写一个函数 myadd, 此函数可以计算两个数的和,也可
# 以计算三个数的和
# def myadd(......):
# ....
# print(myadd(10, 20)) # 30
# print(myadd(100, 200, 300)) # 600
def myadd(a, b, c=0):
return a + b + c
print(myadd(10, 20)) # 30
print(myadd(100, 200, 300)) # 600
|
3b42206a8ab151047c67fb6c0a7e04c55efc9f9a | bpa/advent-of-code | /lib/python/aoc/point.py | 7,799 | 4.1875 | 4 | class Point:
"""A point in 2D space"""
def __init__(self, grid, x, y):
self.grid = grid
self.x = x
self.y = y
def get(self):
return self.grid.data[self.y][self.x]
def set(self, value):
self.grid.data[self.y][self.x] = value
def neighbor(self, x, y):
... |
114419bd8757bb8eb4bd1d47b1de9ffc87af099a | mkebrahimpour/DataStructures_Python | /GeeksForGeeks/Binary Trees/expression_tree.py | 1,054 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 18 18:01:39 2019
@author: sbk
"""
# Python program to insert element in binary tree
class Tree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# A utility function to do inorder traversal
def inorder(t... |
a03d14de6f654e8b17b7c9f91e823a6ab286b7b8 | acoltelli/Algorithms-DataStructures | /Fibonacci.py | 905 | 3.84375 | 4 | from timeit import *
#recursive
def nthFibonacci(n):
if n == 0 or n == 1:
return n
else:
return nthFibonacci(n-1) + nthFibonacci(n-2)
#memoization
def nthFibonacci_(n, memo ={0:0,1:1}):
if n not in memo:
memo[n] = nthFibonacci_(n-1) + nthFibonacci_(n-2) #compute recursively if val not already saved... |
b86f386c4901285b7680e38975f5cd6c3611ca56 | bmckelv30/python-challenge | /PyPoll/main.py | 2,004 | 3.921875 | 4 | # Import modules
import os
import csv
# Read in csv file
csvpath = os.path.join('Resources', 'election_data.csv')
with open(csvpath, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
header=next(csvreader)
# print(f"Header: {header}")
votes = []
candidate = []
total=0
f... |
c458b1633c4dd3ae039a8f25f58073686d15ecb2 | 3dmikec/python | /credit-card-validator.py | 944 | 4.15625 | 4 | '''
CHECKS IF A CREDIT CARD NUMBER IS VALID USING THE LUHN ALGORITHM
'''
def cc_checker():
# Input a credit card number
cc = input("Enter your credit card number: ")
# Begin with a total of zero
total = 0
# Get every second digit starting from the right-most digit and double the value
def double... |
bfb49daf7f7eee2ca1e964c61d5d3ce2edd4c022 | AjithCGeorge/PythonAssignment | /set3/qn1.py | 946 | 4.0625 | 4 | # Qn1
import datetime
day=datetime.date.today().day
month=datetime.date.today().month
year=datetime.date.today().year
# print(datetime.date.today())
# print(day.value)
months31=[0,1,3,5,7,8,10,12]
print('today is : ',datetime.date(year,month,day) )
try:
tomorrow=datetime.date(year,month,day+1)
except... |
db9e2bddf7ccb7d0ebd6e17a22d86f4b704ae9c0 | kimathi-chris/christopher | /Sum.py | 177 | 4.03125 | 4 | num1 =input ('Enter the first number:')
num2 =input ('Enter the second number:')
sum= float(num1) + float(num2)
print('the sum of {0} and {1} is {2}'.format(num1, num2, sum))
|
4ff1e29e1e2e88a8615773dfc7e093157b904ce3 | casanas10/practice_python | /HashTable/ContactList.py | 1,092 | 4.40625 | 4 | '''
Design a hashable class that represents contacts
- Assume each contact is a string and must be in a list
- Possible that contacts are duplicates.
'''
class ContactList:
def __init__(self, names):
'''
list of strings
:param names:
'''
self.names = names
def __hash__(... |
e6f82dc39636bd069f823010da550959757313c4 | kongziqing/Python-2lever | /实战篇/第15章-并发编程/15.4多线程编程/15.4.1thread实现多线程.py | 2,088 | 3.96875 | 4 | """
threading实现多线程
threading 是Python提供的新的线程开发模块,除了支持基本的线程处理外,也提供了大量的工具类,本课程使用此模块讲解了多线程的实现以及线程
相关信息的获取
threading是一个最新的多线程实现模块,拥有更加方便的线程控制以及线程同步支持,在此模块中提供了一个Thread类实现线程的相关
处理操作,Thread类的常用方法如表
threading.Thread 类常用方法
def __init__(self,group=None,target=None,name=None,args=(),kwargs=None,*,daemon=None)
构建一个线程对象,参数... |
570c8d8fd4d94da4e86523921a2766ec545495bf | Calvonator/30-Days-of-Python | /Exercises/day-25-exercises.py | 215 | 4.0625 | 4 | def greet():
name = input("Hello, what is your name?").strip()
name = "".join(name.split())
if name is None:
print("Greetings World!")
else:
print(f"Greetings {name}!")
greet()
|
6c911134627ee02735567e30bb0216a502f98761 | stys/y-test-ranknet | /lib/la.py | 3,326 | 4.4375 | 4 | """
Linear algebra functions
========================
Notation
--------
Integers: i, j, k, m, n, q
Scalars: a, b, c, d, e, g, h
Vectors: s, t, u, v, w, x, y, z
Matrices: A, B, C, D, G, H
Column-wise matrix representation
---------------------------------
Matrix are stored column-wise, i.e A[j] gets the j-th column o... |
727b0c62d37ef4e844da8851adfb1e43e91cc261 | Max6411/Python_ | /Matplotlib-14-second axis.py | 425 | 3.890625 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1*y1
fig, ax1 = plt.subplots() # 返回初始窗口fig, 和分好的窗口
ax2 = ax1.twinx() # 生成如同镜面效果后的ax2
ax1.plot(x, y1, color='green')
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='green')
ax2.plot(x, y2, color='... |
6a7bd9cd2d5a9a653d1c115b24ce24d333f6a5f8 | Indiana3/python_exercises | /wb_chapter7/exercise162.py | 1,542 | 4.3125 | 4 | ##
# Compute the proportion of each alphabetic letter in a list of words
#
# Create an empty dict with letter as keys and occurences as values
letter_occurences = {}
# All the 26 letters of tha alphabet
alphabet = "abcdefghijklmnopqrstuvwxyz"
# Open the file with the list of words
fl = open("words.txt", "r", encodin... |
b98695a590266acfb5bade4c9160d667effc428a | idobarkan/my-code | /interviews/qsort.py | 1,564 | 3.5 | 4 | def q_sort_all(array):
q_sort(array, 0, len(array) - 1)
def q_sort(array, i, k):
if i < k:
pivot = partition(array, i, k)
q_sort(array, i, pivot-1)
q_sort(array, pivot+1, k)
def partition(array, left, right):
pivot_index = choose_pivot(left, right)
pivot_value = array[pivot_i... |
3301d44d7f2f51daba458833916bceacf12a2690 | SixMJ/Page-Myanmar | /4_string/1_example/6_string_functions.py | 448 | 4.03125 | 4 | #does not affect original str , retuen new str
str1 = "hello"
print('capitalize - ' + str1.capitalize())
str1 = "Hello"
print('casefold - ' + str1.casefold())
print('center - ' + str1.center(20,'*'))
print('count - ' + str(str1.count('l')))
print('find - ' + str(str1.find('o')))
print('endswith - ' + str(str1... |
d034b94dbc20316237fbf91759a6976a17afa5fa | vedpprakash/vedpprakash | /luhn algo.py | 1,110 | 3.59375 | 4 | def cal(num):
sum=0
while(num>0):
rem=num%10
sum=sum+rem
num=num//10
return sum
def split(xl):
return [char for char in xl]
def validate_credit_card_number(card_number):
sum=0
lst=[]
lst1=[]
lst2=[]
templ=[]
final1=[]
x=str(card_number... |
230c05ed1492a6bbde6330998447822bde08ed1b | Persimmonboy/Automate_the_boring_stuff | /regexp_3.py | 390 | 3.5 | 4 | import re
phoneRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
resume = 'some random resume with lot of phone numbers'
phoneRegex.search(resume) # Return the first match
phoneRegex.findall(resume) # Return list of matches as string
lyrics = '12 drummers drumming, 11 pipes piping, 10 lords a leaping, 9 ladies dancing'... |
1fec13b0cf879fa0cbbeb610e0bb6d4a6dbf67e5 | thiagofb84jp/python-exercises | /pythonBook/chapter05/exercise5-20.py | 431 | 3.609375 | 4 | '''
5.20. Calcula poupança (2)
'''
deposito = float(input("Depósito inicial: "))
taxa = float(input("Taxa de juros (Ex.: 3 para 3%): "))
investimento = float(input("Depósito mensal: "))
mes = 1
saldo = deposito
while mes <= 24:
saldo = saldo + (saldo * taxa / 100) + investimento
print(f"Saldo do mês {mes} é ... |
73c674b756b5b95dfe94bd346e33f3dc93780167 | cainingning/leetcode | /tree_101.py | 992 | 4 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return ... |
d7ca974a1569c5a6d57380c549507e18701a4438 | versachin/chapter-4 | /Chapter 4 Problem 9.py | 510 | 4.21875 | 4 | #Write a void function to draw a star,
#where the length of each side is 100 units.
#(Hint: You should turn the turtle by 144 degrees at each point.)
import turtle
wn=turtle.Screen()
wn.bgcolor("lightgreen")
alex=turtle.Turtle()
alex.color("hotpink")
alex.pensize(3)
def draw_star():
alex.right(216)
for i in ran... |
946c7f852c7bfbf4abace94bd02c2c99b06c1687 | rlpmeredith/cn-python-programming | /labs/03_more_datatypes/2_lists/04_11_split.py | 448 | 4.4375 | 4 | '''
Write a script that takes in a string from the user. Using the split() method,
create a list of all the words in the string and print the word with the most
occurrences.
'''
# Tested 19-7-19 -> not entirely happy with how it actually works!
my_string = input("Please input a list of words separated by spaces: ")
my... |
bc9c3bef916403a1e2eee1696f74d9faad64c469 | er-aditi/Learning-Python | /For_Practice/Factorial.py | 249 | 3.515625 | 4 | current_user = ['aditi', 'robb', 'stark', 'nedd']
new_users = ['aditi', 'thaons', 'thor', 'robb']
for new_user in new_users:
if new_user in current_user:
print(new_user + " Invited ")
else:
print(new_user + " Not Invited")
|
1db4afefac043ea4ecf4f84c07d687def774028f | martakedzior/python-course | /02-instructions/if_zadanie5.py | 722 | 4.03125 | 4 | # Stwórz zmienną password. Hasło powinno składać z liter i cyfr, zwierać conajmniej 1 dużą literę i mieć długość conajmniej 8 znaków.
# Poinformuj użytkownika, jeśli wpisane hasło jest nie poprawne. Wyświetl różne komunikaty w zależności od rodzaju błędu.
password = (input('Please provide your password: '))
if len(pa... |
91476d8c964d9264a022af840e1a19586641dd1c | danielggc/python | /ejersiciosDiarios/parentesis.py | 2,027 | 3.609375 | 4 | class permutacionParentesis():
def __init__(self,_numeroParentesis:int,_diferencia):
self.parentesisabiertos=_diferencia
self.numeroParentesis:int=_numeroParentesis
def primeraCapa(self,_cantidadParentesis:int)->int:
self.cantidadParentesis=_cantidadParentesis
self.respaldontidad... |
76bb2838cea5784b861f334f3f782be9c8661570 | alejaksoto/JavaScript | /Poo/python/excersice/nombres.py | 356 | 3.765625 | 4 |
man1 =input('Cual es tu nombre')
edad1 = int(input('cual es tu edad'))
man2 = input('cual es tu nombre')
edad2 = int(input('cual es tu edad'))
if edad1 > edad2:
print(f'{man1} es mayor que {man2} por {edad1 - edad2} años')
elif edad2 > edad1:
print(f'{man2} es mayor que {man1} por {edad2 - edad1} años')
else... |
05b959c4689ca63461804d3cf08998e5eda1cc76 | TheAragont97/Python | /Actividades/Relacion 1/Relacion de ejercicios - Bucles/ejercicio 2/ejercicio_2.py | 118 | 3.75 | 4 | edad = int(input("¿Cuántos años tienes? "))
for i in range(edad):
print("Has cumplido " + str(i+1) + " años")
|
4cabee1eadcc5b881ec24539c188d72e63914072 | Fifi1996/learn_py | /nature.py | 1,282 | 4.40625 | 4 | '''
实例属性和类属性
由于python是u动态语言,根据类创建的实例可以任意绑定属性
给实例绑定属性的方法是通过实例变量,或者通过self变量
'''
class Student(object):
def __init__(self,name):
self.name=name
s=Student('Bob')
s.score=90
#如果Student类本身需要绑定一个属性呢
#可以在class中定义属性,这种属性是类属性,归Student类所有
class Student(object):
name='Student'
#当我们定义了一个类属性后,类的所有实例都可以访问到
s=Student()... |
6eae44913a58c23f0ca86b624be7ab071ca80f43 | cuyi/pylearn | /introduction/strings_toyi.py | 728 | 4.25 | 4 | #! /usr/bin/env python2.7
# -*- coding: utf8 -*-
mstr = 'hello qianjie'
print mstr
mmstr = 'hello piaoliang\n\
what r u nong sa li?'
print mmstr
hello = '''This is a rather long
string containing several lines of text.'''
print hello
hello1 = """This is a rather long
string containing several lines of text.... |
e146b2ba07b0a1556ee330944e2b867209add8cd | spnow/XECryption | /XECrypt.py | 1,411 | 4.03125 | 4 | """
Simple number crunching/ASCII converting script to solve hackthissite.org's
Realistic Mission #6. Adds triplets of numbers together to get a valid ASCII value,
then subtracts the total ASCII value of the pass phrase to get the desired message.
Numbers are delimited by periods. Newlines are removed before processin... |
9758932f9f5ff8b7fd148cd62983aa083b14e434 | mihaivalentistoica/Python-Fundamentals | /Curs4/Exercitii_singuri.py | 1,805 | 3.578125 | 4 | '''
1. Creati clasa Animal cu 2 atribute private(mangled): nume si varsta. La initiere se dau valori default.
Sa se creeze getteri si setteri pentru ambele campuri.
Creati cel putin 2 obiecte si testati proprietatile create.
'''
class Animal:
def __init__(self):
self.__nume = None
self.__varsta = ... |
c60fc98d3d1c5e9b855b68bc497e6acd35ed00b3 | Rakshita-Shetty/Scrapy-Workflow | /pipelines.py | 1,053 | 3.671875 | 4 | import sqlite3
class BooksPipeline(object):
def __init__(self):
self.create_connection()
self.create_table()
def create_connection(self):
self.conn = sqlite3.connect("books.db")
self.curr = self.conn.cursor()
def create_table(self):
self.curr.execute(""... |
d7482fb55a2549fe25d911edfbdf8195dce00b7f | tsubauaaa/SpiralBookPython | /Part2/3-5.py | 734 | 3.859375 | 4 | def bubble_sort(A, N):
flag = True
i = 0
while flag:
flag = False
for j in reversed(range(N)):
if j == i:
break
if A[j][1] < A[j - 1][1]:
A[j], A[j - 1] = A[j - 1], A[j]
flag = True
i += 1
return A
def sele... |
c5eb05c6d1a9239661ada80c87897121cb7fc3bc | CodingEZ/Scrabble-AI | /helper.py | 874 | 3.953125 | 4 | def areValidLetters(letters):
for letter in letters:
if len(letter) != 1 and (letter not in 'qwertyuiopasdfghjklzxcvbnm'):
return False
return True
def areValidLocations(spaces):
for space in spaces:
try:
location = int(space)
except ValueError:
... |
e65f169e08e6f78fe150cdd10c5ffe23915f6768 | YasinLiu/Data-structure | /example/timing1.py | 1,051 | 4 | 4 | """
File: timing1.py
Prints the running times for problem sizes that double,
using a single loop
"""
import time
problemSize = 100
iterations = 0
def work1(problemSize):
work = 1
for _ in range(problemSize):
global iterations
iterations += 1
work += 1
work -= 1
def wo... |
5fdc2af8a3995e17c8c5518e12a4ff4674fd30fa | BioGeek/euler | /problem030.py | 887 | 3.953125 | 4 | # Surprisingly there are only three numbers that can be written as the sum of
# fourth powers of their digits:
#
# 1634 = 1^4 + 6^4 + 3^4 + 4^4
# 8208 = 8^4 + 2^4 + 0^4 + 8^4
# 9474 = 9^4 + 4^4 + 7^4 + 4^4
#
# As 1 = 1^4 is not a sum it is not included.
#
# The sum of these numbers is 1634 + 8208 + 9474 = 193... |
fa11f79d15661ea4e93d272fe577fdf0d7ae32c3 | MadisonStevens98/Python-Pyramid-Practice-Project | /Pyramid Practice.py | 877 | 4.21875 | 4 | def print_pyramid(type): ##required method
if type == "left": #selection statement for left
print("# \n## \n### \n#### \n##### \n###### \n#######") #left pyramid
elif type == "right": #selection for right
print(" #\n ##\n ###\n ####\n #####\n ######\n #######")#right pyramid
elif type =... |
55094820e2faf29bb12b938721b5d1bc8a0b819b | Jasmined26/JCalc | /JCalc.py | 8,764 | 3.859375 | 4 | # Import modules
import tkinter
import tkinter.font as tkFont
from tkinter import *
# Class to create a button that changes color when hovered over
# Inherits from tkinter Button class
class HoverButton1(tkinter.Button):
def __init__(self, **kw):
tkinter.Button.__init__(self, **kw)
self['bd'] = 1
... |
de11d111ad16b1cca3b43af4be2ccc4145faf4eb | rakiasomai/holbertonschool-higher_level_programming | /0x05-python-exceptions/2-safe_print_list_integers.py | 333 | 3.609375 | 4 | #!/usr/bin/python3
def safe_print_list_integers(my_list=[], x=0):
try:
z = 0
for y in range(x):
if isinstance(my_list[y], int):
z += 1
print("{:d}".format(my_list[y]), end="")
except TypeError as err:
print(err)
else:
print("")
... |
d154192d969a63c1803ec25e947c3822b2e06c5a | yhasansenyurt/PythonAssignments-PythonOdevleri | /problem sets/problem1/matrix.py | 4,426 | 4.125 | 4 | #########################################################################################
# QUESTION IV
# Description: This program operates matrices in different ways and analyzes maximum
# value of matrix.
#########################################################################################
print("SOLUTION O... |
02fa8f5552fe61ded4562647aa2fe64605d1e7f8 | NipunGarg01/Python | /Python Debugger.py | 231 | 3.59375 | 4 | import pdb;pdb.set_trace()
x=[1,2,3]
y=3
z=9
sum=y+z
pdb.set_trace() # Set the trace to where you see issue is....then we will reach at python debugger.
sum1=x+y
print(sum)
print(sum1)
|
9182e8aae119937443c5ea4b4c96809aceaf5613 | eminkartci/HistorySimulation | /src/Community.py | 2,848 | 4.0625 | 4 | # import os library
import os
class Community:
# construction
def __init__(self,id,title,location,population,religion):
self.id = id
self.title = title
self.location = location
self.population = population # Population Amount
self.people = ... |
5e877a0c47970af4cb1b8cc71a76b9e7d1234c67 | namekun/pythonStudy | /ch03_For_Set/집합.py | 719 | 3.609375 | 4 | # 집합(set)은 리스트와 같이 정보를 여러개 넣어서 보관할 수 있는 파이썬의 기능이다.
# 다만 집합 하나에는 같은 자료가 중복되어 들어가지 않고, 자료의 순서도 의미가 없다는 점이 리스트와 다르다.
s = set()
s.add(1)
s.add(2)
s.add(2) # 이미 있는 값이기에 중복되서 들어가지 않는다.
print(s)
len(s)
# len(x) : 집합의 길이를 구하는 방법
# add(x) : 집합에 자료 x를 추가합니다.
# discard(x) : 집합에 자료 x가 들어 있다면 삭제합니다. 없다면 변화없음
# clear() : 집합의 모든 ... |
89ea1af39768fd3c0f7ea63b36fa507b67d66233 | tapans/Algorithms-Puzzles-Challenges | /CTCI_6e/8.1_triple_step.py | 1,001 | 4.125 | 4 | #!/usr/bin/python
import unittest
def triple_step(n, memo={}):
'''
Returns Count of how many possible ways the child can run up the stairs
Context: Child is running up a stairacase with n steps
and can hop either 1 step, 2 steps or 3 steps at a time
Time Complexity: O(n)
Space Complexity: O(n)
... |
74d6140d60bc8b68a714b541070a31853e5e82bf | lludu/100DaysOfCode-Python | /Day 02 - Tip Calculator/Exercise 3.py | 425 | 3.6875 | 4 | #This is day 2, understanding data types and string Manipulation
#Exercise 3 - Your Life in weeks:
age = 90 - int(age)
months= age*12
weeks= age*52
days= age*365
# F STRINGS ARE AWESOME!
print(f'You have {days} days, {weeks} weeks, and {months} months left.')
#link to exercise
# https://replit.com/@Lludu/day-2-... |
3827f6116cb68c34aae886051b5dc99f02466206 | Gabriel-Mbugua/Coding-Questions | /Python/SumOfOddNumbers/solution.py | 271 | 3.765625 | 4 | #my solution
def row_sum_odd_numbers(n):
lst = []
for i in range(n*(n-1), n * (n + 2)):
if len(lst) < n and i % 2 != 0 :
lst.append(i)
return sum(lst)
row_sum_odd_numbers(3)
#actual solution
def row_sum_odd_numbers(n):
return n ** 3 |
8cc1ec9fd86341dc0e29d2594738e83b7f228e7e | Iqrar99/Project-Euler | /problem39.py | 689 | 3.5625 | 4 | """
To make the computation faster, we need to do arithmetic approach first.
- a^2 + b^2 = c^2 (1)
- a + b + c = p (2)
we can rewrite them as
c = p - a - b
a^2 + b^2 = (p - a - b)^2 = p^2 +a^2 + b^2 - 2pa -2pb -2ab
b = p(p - 2a) / 2(p - a)
"""
def main():
result = 0
answer = 0
for p in range(2, 100... |
eee0e6f11b89398c591d536cb9d011df480884b7 | yifange/leetcode | /remove_duplicates_from_sorted_list.py | 1,054 | 3.625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def deleteDuplicates(self, head):
if not head:
return head
fake_head = ListNode(head.val -... |
2518b6486c596d60f6e9e631a03a9d140471bdcb | heyyitzaashi02/JISAssasins | /Untitled11.py | 211 | 3.859375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# program to accept a sentence from the user and reverse
msg="you are a good girl"
words=msg.split(" ")
words.reverse()
print(' '.join(words))
# In[ ]:
|
a261a039383a8bfa9d09b47841a4d071e1449d5c | Natumeme/Leetcode | /easy/20_isvalid.py | 805 | 3.9375 | 4 | #!usr/bin/env python
#-*- coding:utf-8 -*-
'''
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
'''
class Solution:
def isValid(self,s):
sta=[None]
dic={")":"(","}":"{","]":"["}
for t in s:
if(t in dic and dic[t]==sta[len(sta)-1]):
sta.pop()
else:
... |
d513ffd2a10041f42fc9f983ffd537860e63a45f | LiseIL/SDDproject-G1 | /Queue.py | 2,147 | 4.0625 | 4 | ################
# Python 3.5 File
# Group 1
# created oct. 24th 2018
# last modif oct. 24th 2018
# Queue.py
################
#Une file est une liste où les insertions se font d'un
#côté et les suppressions se font de l'autre côté
#[Lise]
#1- Est-ce qu'on est sûre que les valeurs stockées dans notre queue
# doivent o... |
df77d9c94a8993ed14edb483ef33785491224d26 | mosot624/ProgrammingChallenges | /RecursiveChallegen.py | 668 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 10:15:33 2019
@author: Michael
"""
#http://www1.udel.edu/CIS/181/pconrad/05S/examples/recursion/recursion.problems
def changetoString(var,n,counter):
if n == 1:
var = int(var[0])
return var
elif counter == len(var):
var... |
22d7a123b034a3b8c8e117be179bcfde85d479fb | DudekKonrad/Python2020 | /Lab2/2.15.py | 165 | 3.703125 | 4 | numbers_list = [5, 23, 654, 26, 45875, 12, 3, 56, 3]
result = ""
for number in numbers_list:
str_number = str(number)
result += str_number
print("Result:", result) |
d1d7d831531bae6f182d8d4d56369cbdf68dab92 | Wenzurk-Ma/Python-Crash-Course | /Chapter 04/foods.py | 436 | 3.609375 | 4 | # Title : TODO
# Objective : TODO
# Created by: Wenzurk
# Created on: 2018/2/5
my_foods = ['pizza', 'falafel', 'carrot cake']
# 这样行不通
# friend_foods = my_foods
friend_foods =my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
for my_food in my_foods:
print(... |
90885d5dd5dba2ef4ef093b4b94cbe3826e9e211 | eudaemonic-one/Lifelong-Learning | /LeetCode/Python3/unique-binary-search-trees-ii.py | 770 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
def dfs(start, end):
if start >= end:
return [None... |
2a950a911ecf66bcdeb9438a01c3336564d11018 | mglerner/MathematicalPhysics | /WavesOnStrings/both_waves_with_sum.py | 1,365 | 3.875 | 4 | #!/usr/bin/env python
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
outerlim, innerlim = 4, 2
v1, v2 = 0.01, -0.013453456
fig = plt.figure()
ax = plt.axes(xlim=(-outerlim, ... |
d415ed990d000664bd5bfd4ed652088f4839365e | madelgi/learning | /books/think_stats/ch1.py | 1,933 | 4.3125 | 4 | import survey
"""
Exercise 1.3
In this exercise, we will explore the data in the Pregnancies
table
"""
def ex13():
table = survey.Pregnancies()
table.ReadRecords()
print 'Number of pregnancies', len(table.records)
# Part 2 of ex13. This function iterates through Pregnancies and counts
# the numb... |
613c4ff4124869c98dee20deca33ac160d8edbe6 | dials/dials | /src/dials/algorithms/scaling/reflection_selection.py | 16,547 | 3.953125 | 4 | """
Algorithm to select a well connected subset of reflections for scaling.
Description of reflection selection algorithm. To get the best 'connectedness',
we want to select groups of reflections which belong to more than one class.
A class in this case is a volume of reciprocal space (e.g 12 areas on the
surface of a... |
8443c8be3aa1b0be20d3755901e55f098d2c8370 | green-fox-academy/judashgriff | /Week 3/Day 3/line_play_quarters.py | 1,336 | 3.59375 | 4 | from tkinter import *
root = Tk()
canvas = Canvas(root, width='300', height='300')
canvas.pack()
# divide the canvas into 4 equal parts
# and repeat this pattern in each quarter:
# [https://github.com/greenfox-academy/teaching-materials/blob/master/workshop/drawing/line-play/r1.png]
def make_colorful_lines():
f... |
49926b528cc201dab20b03b51d5475075b80d936 | noahbjohnson/FileTypeCounter | /filecount.py | 4,307 | 3.734375 | 4 | import os
def changedirectory():
cwd = os.getcwd()
print("The current directory is:", cwd)
loop = True
while loop:
changeboolian = input("Would you like to change the working directory? (Y/N)")
if changeboolian == "Y" or changeboolian == "N":
loop = False
else:
... |
c89e1b8f2975b7d16913269d085b0388b489f21d | btatkerson/CIS110 | /Excercises/Ch2/ch2ex06.py | 454 | 3.953125 | 4 | def main():
print("This program calculates the future value of an investment.")
print()
principal=eval(input("Enter the initial principal: "))
apr=eval(input("Enter the annual interest rate(APR): "))
years=eval(input("How many years are you investing? "))
for i in range(years):
prin... |
dc3601bc9863866a0a2768e4380c9f5d5521b010 | JoaoFiorelli/ExerciciosCV | /Ex069.py | 759 | 3.640625 | 4 | totalmaioridade = totalhomem = totalmulhernova = 0
while True:
idade = int(input("Qual a idade da pessoa cadastrada? "))
sexo = " "
while sexo not in "MF":
sexo = input("Qual o sexo da pessoa cadastrada [M/F]? ").strip().upper()[0]
if idade > 18:
totalmaioridade += 1
if sexo == "... |
1ca4c758cd0de961041b90833d7a8337749f5e5a | Wytzepakito/Rosalind | /Expected_offsprings.py | 533 | 3.640625 | 4 | #! /usr/bin/python37
"""
Author: Wytze Gelderloos
Date: 29-7-2019
Calculating expected offspring.
This script calculates the expected number of offspring having the dominant
phenotype. Looking to Mendel's diagrams will give the proper answer for this
question.
"""
string= "18852 19128 19528 18742 17855 19195"
numbe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.