blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
d3d0dabc882f6021df69bebe4a00e4b97c6878bf | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 9/Heap/Problems/Heap Sort.py | 2,223 | 4.3125 | 4 | Heap Sort
Given an array of size N. The task is to sort the array elements by completing functions heapify() and buildHeap() which are used to implement Heap Sort.
Example 1:
Input:
N = 5
arr[] = {4,1,3,9,7}
Output:
1 3 4 7 9
Explanation:
After sorting elements
using heap sort, elements will be
in order as 1,3,4,7,... |
c20adc3426ff4c377f33168f86efaa052e34b40b | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 2/Searching and Sorting/Binary Search.py | 1,316 | 3.96875 | 4 | Binary Search
Binary Search
Given a sorted array of size N and an integer K, find the position at which K is present in the array using binary search.
Example 1:
Input:
N = 5
arr[] = {1 2 3 4 5}
K = 4
Output: 3
Explanation: 4 appears at index 3.
Example 2:
Input:
N = 5
arr[] = {11 22 33 44 55} ... |
25da6eb5b7dac467baf32501b8cfe686b93fe884 | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week_11/Dynamic Programming/Knapsack Problem.py | 2,587 | 4.0625 | 4 | Knapsack Problem
You are given weights and values of N items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that we have only one quantity of each item.
In other words, given two integer arrays val[0..N-1] and wt[0..N-1] which represent values and weights associated w... |
0bb5128f7e3bbd1ee480e189c182cb7933143ae1 | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 3/Strings/Problems/Isomorphic Strings.py | 2,802 | 4.4375 | 4 | Isomorphic Strings
Given two strings 'str1' and 'str2', check if these two strings are isomorphic to each other.
Two strings str1 and str2 are called isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2 while preserving the order.
Note: All occurrences of eve... |
55626df32d3baabd15b9e4375f61a28a562f51be | PacktPublishing/Modern-Python-Cookbook-Second-Edition | /Chapter_08/ch08_r03.py | 1,397 | 3.9375 | 4 | """Python Cookbook 2nd ed.
Chapter 8, recipe 3, Leveraging Python's duck typing
"""
import random
from typing import Tuple, Optional, List, Iterator, Type
class Dice1:
def __init__(self, seed=None) -> None:
self._rng = random.Random(seed)
self.roll()
def roll(self) -> Tuple[int, ...]:
... |
cff8fb9d2a989af88e7a2c5279e9fe215fb802b2 | PacktPublishing/Modern-Python-Cookbook-Second-Edition | /Chapter_07/ch07_r02.py | 1,859 | 4.03125 | 4 | """Python Cookbook 2nd ed.
Chapter 7, recipe 2, Essential type hints for class definitions
"""
import random
from typing import Set, List
class Dice:
RNG = random.Random()
def __init__(self, n: int, sides: int = 6) -> None:
self.n_dice = n
self.sides = sides
self.faces: List[int]
... |
65242429eae7c363046bfecf17ea820e543437eb | CodeForFun-r/Competitive-Programming | /codechef/flow016.py | 241 | 3.515625 | 4 | from math import gcd
for t in range(int(input())):
a, b = map(int, input().split(' '))
g = gcd(a, b)
if g == 1:
l = a * b
else:
x, y = a // g, b // g
l = x * y * g
print(g, l)
|
74b7dfa9308a4b419b34c9f915a3ffc8e4e5275a | Rashi1997/Assignments | /5.py | 475 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
5) create a main python script(for example main.py), create a config script
(config.py). In config.py define four variables(name, age(int), email, company).
import this config script from main.py and print these four variables.
Assume main.py is your starting script.
"""
import con... |
3e94842cb52db76a1eb0552711813d9017ef1f41 | gbolahanO/techcrunch_crawler | /techcrunch.py | 1,507 | 3.765625 | 4 | from bs4 import BeautifulSoup
import requests
def techcrunch(url):
# make requests to web page url
response = requests.get(url)
# read the content of the server's response
content = response.text
# parse the web page to BeautifulSoup which represents the document as a nested data structure
sou... |
bebc52f340030977c8f22fe5a4a1f1cbbb97bcbd | AKBoles/Tweet-Livestream-Attempt | /send_input_tweet.py | 704 | 3.75 | 4 | # given a user input, send a tweet
# for hashtags, type "\" before
# import statements
from twython import Twython
import sys
# variables from auth.py
from auth import(
consumer_key,
consumer_secret,
access_token,
access_token_secret
)
# make connection with the Twitter API using the imported variables
... |
9f97f627ba6c377df8d6ee6e5d50dc5d9399490b | yuxian0908/chainReactionGameAI | /Board.py | 1,252 | 3.59375 | 4 | from ChessPiece import ChessPiece
class Board:
def __init__(self, row, col):
self.row = row
self.col = col
self.table = []
# initialize board table
for i in range(row):
r = []
for j in range(col):
if( (i==0 and j==0) or (i==0 and j==... |
95a056ff0069451521e473af2ef6379d45ea922d | gustavocastag/geradornumtel | /geradornumt.py | 6,697 | 3.796875 | 4 |
Num=('1','2','3','4','5','6','7','8','9','0')
print ('#'*10)
print ('\033[41mATENÇÃO\033[m: Qualquer alteração podera ser feita no script.')
print (' ')
print ('#'*10)
print (' ')
print ('Selecione o tipo de formatação dos numeros')
print (' ')
print ('---------------------------------------------------------')
print... |
d4f69ecbac042942b1fda0dec3a418f9c8590e8d | Technicoryx/python_strings_inbuilt_functions | /string_14.py | 241 | 3.75 | 4 | """Below Python Programme demonstrate isdecimal
functions in a string"""
s = "28212"
print(s.isdecimal())
# contains alphabets
s = "32ladk3"
print(s.isdecimal())
# contains alphabets and spaces
s = "Mo3 nicaG el l22er"
print(s.isdecimal())
|
261cfa1feb28124e9113c400707c5dedf9e30249 | Technicoryx/python_strings_inbuilt_functions | /string_08.py | 609 | 4.40625 | 4 | """Below Python Programme demonstrate expandtabs
functions in a string"""
#Case1 : With no Argument
str = 'xyz\t12345\tabc'
# no argument is passed
# default tabsize is 8
result = str.expandtabs()
print(result)
#Case 2:Different Argument
str = "xyz\t12345\tabc"
print('Original String:', str)
# tabsize is set to 2
p... |
cf11c056ca6697454d3c585e6fa6eea6a153deae | Technicoryx/python_strings_inbuilt_functions | /string_06.py | 204 | 4.125 | 4 | """Below Python Programme demonstrate count
functions in a string"""
string = "Python is awesome, isn't it?"
substring = "is"
count = string.count(substring)
# print count
print("The count is:", count)
|
6a2f8d11b44b64dc6d5e9a81ef3f5b33c17dbeb2 | Technicoryx/python_strings_inbuilt_functions | /string_21.py | 300 | 4 | 4 | """Below Python Programme demonstrate isupper
functions in a string"""
# example string
string = "THIS IS GOOD!"
print (string.isupper());
# numbers in place of alphabets
string = "THIS IS ALSO G00D!"
print (string.isupper());
# lowercase string
string = "THIS IS not GOOD!"
print(string.isupper());
|
da915e308927c3e5ed8eb0f96937f10fd320c8ab | Technicoryx/python_strings_inbuilt_functions | /string_23.py | 360 | 4.46875 | 4 | """Below Python Programme demonstrate ljust
functions in a string"""
#Example:
# example string
string = 'cat'
width = 5
# print right justified string
print(string.rjust(width))
#Right justify string and fill the remaining spaces
# example string
string = 'cat'
width = 5
fillchar = '*'
# print right justified stri... |
41ef3ccc05f924bb64d2e60bce8e4087ae139604 | JingyiJia/08-Exam1-201920 | /src/problem4.py | 3,984 | 3.765625 | 4 | """
Exam 1, problem 4.
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Mark Hays, Amanda Stouder, Aaron Wilkin, their colleagues,
and Jingyi. Jia.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
import rosegraphics as rg
def main():
""" Calls the TEST functions in this ... |
6f9f9b75143a2e70002f12295402bab005ea28ab | ki4070ma/sort-algorithm | /insertion_sort.py | 985 | 3.9375 | 4 |
def insertion_sort_RTL(l):
length = len(l)
for i in range(1, length): # idx for target
print('round start')
for j in range(i-1, -1, -1): # idx to replace with target
if l[i] > l[j]: # Could find insertion position
# print('Found insertion pos')
val... |
d328e177003603e1b13803177af2d722e31f513e | michoricardo/MichiganUniversityPythonMicho | /quizHRS_RATE.py | 238 | 3.8125 | 4 | hrs = input("Enter Hours:")
h = float(hrs)
rate = input('Enter rate:')
r= float(rate)
#Si horas mayor a 40, entonces
if h> 40:
extras=h-40
normal=40
extra_rate=r*1.5
pay=((normal*r)+(extras*extra_rate))
print(pay)
|
e963d6d73caf5ece21bd3f9c24d9153c5914b275 | vilmantas/advent-of-code-2019 | /day-10.py | 3,269 | 3.5625 | 4 | from dataclasses import dataclass
@dataclass
class Tile(object):
name: str
x: int
y: int
isasteroid: bool
isvalid = True
visible_asteroids = 0
blocked_by = ''
def __repr__(self):
if not self.isvalid:
return 'B' + self.blocked_by
if self.isasteroid:
... |
c21eb6d9cb89d64e5d4c9c477d8f02eaa845a074 | SebastianG343/80-Ejercicios | /Ejercicio 31.py | 105 | 3.8125 | 4 | n=int(input("Digite un numero"))
if n>=10:
n2=n**3
print(n2)
else:
n3=n/4
print(n3)
|
3ed55c7cbb0c2d765c39f2d007b4f4ad09653463 | SebastianG343/80-Ejercicios | /Ejercicio 33.py | 150 | 3.828125 | 4 | n1=int(input("Digite un numero")
n2=int(input("Digite un numero")
if n1>n2:
print(n1,"Es mayor a:",n2)
else:
print(n2,"Es mayor a:",n1)
|
d21dd0d7cfe21679e72b5bfbb9ab59d5459923da | SebastianG343/80-Ejercicios | /Ejercicio 17.py | 86 | 3.6875 | 4 | a=int(input("Digite la aceleración"))
m=int(input("Digite el peso"))
f=m*a
print(f)
|
f93e1688254335858f814cee16270163c22783e8 | SebastianG343/80-Ejercicios | /Ejercicio 7.py | 302 | 3.71875 | 4 | a=float(input("Digite nota 1"))
b=float(input("Digite nota 2"))
c=float(input("Digite nota 3"))
d=float(input("Digite nota 4"))
e=float(input("Digite nota 5"))
lal=a*0.15
lel=b*0.20
lil=c*0.15
lol=d*0.30
lul=e*0.20
nota_final=lal+lel+lil+lol+lul
print("La nota final del estudiante es:",nota_final)
|
4a847de243c0431de33af164c2b1db41a55079db | SebastianG343/80-Ejercicios | /Ejercicio 9.py | 169 | 3.953125 | 4 | n=int(float(input("Digite el diametro de la circurferencia")))
perimetro=n*3.1416
xd=n/2
area=(xd*xd)*3.1416
print("El perimetro es:",perimetro,"y el area es:",area)
|
74b25300aff1b244f41022e40e47e9158d33119d | alieidi1st/Python-Class--Exercise | /Ex10_1_AliEidi.py | 356 | 3.6875 | 4 | import numpy as np
import matplotlib.pyplot as plt
x = 2
y = pow (2,3)
print ('pow (2 , 3 = ', y)
teta = 3
print ('sin teta = ', np.sin(teta))
print ('cos teta= ', np.cos(teta))
meshPoints = np.linspace (-1 , 1 , 500)
print ('the 53th element of meshPoints is: ', meshPoints [53])
plt.plot(meshPoints , np.sin(... |
14537cb72308f46cbea425947ac545e7ac2e8e7f | alieidi1st/Python-Class--Exercise | /Ex6_AliEidi.py | 2,080 | 3.90625 | 4 | #045
"""total = 0
while total <= 50:
num = int (input('Plase enter a number: '))
total += num
print ('The total is: ', total)
"""
#046
"""num = 0
while num < 5:
num = int(input('Please enter a number: '))
print ('The last number you entered was: ', num)
"""
#047
"""n1 = int (input('Please... |
1dca63c8958ff10346f5b1221fc5d88a17bd3bb1 | Sitych/wednesday18_00 | /lesson5/3.py | 765 | 3.546875 | 4 | class SchoolClass:
def __init__(self, students, name):
self.stds = students
self.name = name
def math_mark(self, marks):
self.mark = marks
def sort_by_marks(self):
for i in range(len(self.stds)):
for f in range(len(self.stds) - 1):
... |
603a0d6a08a7f8a55ed29d4ccf34dfa4058c4228 | ianlaiky/SITUniPython1002 | /test1.py | 1,582 | 3.84375 | 4 | # def say(message, times = 2):
# print(message * times)
#
# say('Hello')
# say('World', 5)
#
# def func(a, b=5, c=10):
# print('a is', a, 'and b is', b, 'and c is', c)
#
# func(3, 7)
# func(25, c = 24)
# func(c = 50, a = 100)
#
# def func(a, b, names):
# a = a+10
# b = b+20
# names[0] = 12
# nam... |
746431baf697da208ce677e32a2b696c6a786ac1 | ianlaiky/SITUniPython1002 | /Lab3/Task1/calculator.py | 546 | 3.734375 | 4 | import sys
from myMath import *
a = ""
try:
a = str(sys.argv[1])
except:
print "Your input is invalid!"
noList = a.split(",")
newList = []
# print noList
for i in noList:
newList.append(int(i))
print "The difference is:" + str(subtraction(maximum(newList), minumum(newList))) +" The summation is:"+... |
5f2248e274f658189962bf89273997b7f8a714fc | ianlaiky/SITUniPython1002 | /Lab4/Task3/elfish.py | 505 | 3.765625 | 4 | import sys
a = str(sys.argv[1])
def elfish(x):
if str(x) == "":
return x
else:
# print x
if x[0] == "e":
return elfish(x[1:]) + x[0]
if x[0] == "l":
return elfish(x[1:]) + x[0]
if x[0] == "f":
return elfish(x[1:]) + x[0]
els... |
8a61bfaf6344722edfa6b4d91212abf69883ea5a | SnowStorm-L/Learn_Python | /Code/BasicDataType/str.py | 6,896 | 3.9375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/4/9 PM3:12
# @Author : L
# @Email : L862608263@163.com
# @File : str.py
# @Software: PyCharm
newStr = 'python python'
print(newStr[:7])
print(newStr[1])
# 不能被修改
# TypeError: 'str' object does not support item assignment
# newStr[0] = 'd'
newStr = 'jjJJjj' + newStr[6:... |
15cb50682eb4900de9262ed3650bc102a6e2fa67 | SnowStorm-L/Learn_Python | /Code/def.py | 6,262 | 3.515625 | 4 | #!/usr/local/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2018/4/10 PM4:37
# @Author : L
# @Email : L862608263@163.com
# @File : def.py
# @Software: PyCharm
import logging
# 定义
# def 定义函数的关键字
# 默认参数 num2
def add(num1, num2=5):
"""函数说明"""
return num1 + num2
# 调用
print(add(5, 6))
# 函数说明
print(ad... |
ab0cf9969f99a972d1f1cd707006c81dfb31b1aa | SnowStorm-L/Learn_Python | /Code/recursive.py | 3,050 | 3.859375 | 4 | #!/usr/local/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2018/4/19 PM3:05
# @Author : L
# @Email : L862608263@163.com
# @File : recursive.py
# @Software: PyCharm
import sys
# from functools import reduce
# 设置递归最大深度
sys.setrecursionlimit(10000)
# 递归
def recursion():
return recursion()
# 死循环
# Recu... |
0aa8632c85f434bd245e9f1fecafdf3339f967e5 | matveynikon/mlstuff_by_matt | /ml2.py | 3,635 | 3.546875 | 4 | #First, include following libraries:
# Importing all necessary libraries
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
#Here, the train... |
11aecb5dcd9044138c33648801889fdb8589deda | harigowtham/C-programs | /python/ds/tree.py | 1,038 | 4 | 4 | class node:
def __init__(self,data):
self.head=data
self.left=None
self.right=None
class tree:
def __init__(self,data):
self.head=None
self.left=None
self.right=None
def inorder(self):
if(self.head):
self.inorder(self.left)
pr... |
b235ce6efda4db04b4ead4ed2b568671c822919c | harigowtham/C-programs | /python/ds/linked_list.py | 853 | 3.890625 | 4 | class node:
def __init__(self, data):
self.head=data
self.next=None
class llist:
def __init__(self):
self.head=None
def printl(self):
temp = self.head
while(temp):
print temp.head
temp = temp.next
def insertatend(self,data):
newN... |
d352e1155040ab2ad735fdd8091f90b2d5cbe2e6 | gresendiz/Python | /Area_Triangulo.py | 213 | 3.78125 | 4 | #calcular area de un triangulo
b = float(input("Ingresa el valor de base: "))
a = float(input("Ingresa el valor de altura: "))
z = (b * a) / 2
w = "{0:.2f}".format(z)
print("El valor de area es:", w) |
1fe84444ac10a6a11944304adfaa4b498b3460f5 | gresendiz/Python | /cubo.py | 166 | 3.84375 | 4 | #Funciones
#Escibir el cubo de un numero
def cubo(x):
y= x * x * x
return y
a = int(input("Ingresa el valor: "))
b = cubo(a)
print("el cubo es: ", b) |
6b791a22ada68ea192ea2cd57f6f80b04aec36b1 | kyb3r/hardwork | /Sudoku/sudoku.py | 2,081 | 3.921875 | 4 | class Sudoku:
'''
Class that solves a sudoku grid recursively
'''
def __init__(self, grid):
self.grid = grid
self.seen = set()
def __str__(self):
ret = ''
for row in self.grid:
fmt = ' '.join(str(i) for i in row)
ret += fmt + '\n'
retu... |
68285e9fdf5413e817851744d716596c0ff2c926 | anton515/Stack-ADT-and-Trees | /queueStackADT.py | 2,893 | 4.25 | 4 |
from dataStructures import Queue
import check
# Implementation of the Stack ADT using a single Queue.
class Stack:
'''
Stack ADT
'''
## Stack () produces an empty stack.
## __init__: None -> Stack
def __init__(self):
self.stack = Queue ()
## isEmpty(self) returns True if the... |
ce6d86586bb5d7030312ade00c8fc3ca7a0d2273 | vamsi-kavuru/AWS-CF1 | /Atari-2.py | 1,182 | 4.28125 | 4 | from __future__ import print_function
print ("welcome to my atari adventure game! the directions to move in are defined as left, right, up, and down. Enjoy.")
x = 6
y = -2
#move = str(input('Make your move! Type in either "Left", "Right", "Up", "Down" or type "Exit" to exit the game:')).lower()
def game():
globa... |
c0dda8f82525f0bf3a4f352d6478e17c33206021 | YinPierce/python_work | /random_walk/random_walk.py | 1,106 | 3.75 | 4 | #! /usr/bin/env python3.7
# -*- coding: utf-8 -*-
'''模拟随机漫步'''
from random import choice
class RandomWalk():
def __init__(self, num_points=5000):
self.num_points = num_points
#起始点从(0,0)开始
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
'''计算并存储随机漫步的点'''
... |
fb20247b15fd09e8b3331aee9a410882f5bb4a66 | lixiang2017/fluent-python | /test/1-1.py | 1,590 | 3.859375 | 4 | import collections
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suits
... |
e29f4bd48bdb90db7839ef474269fe26e458bbd1 | loofe/MachineLearningAlgorithm | /LeanerRegression/singleVariable.py | 636 | 3.6875 | 4 | import numpy as np
import matplotlib.pyplot as plt
x_array = [1.0, 2.0, 3.0, 4.0, 5.0]
# y = 2x + 3
y_array = [5.0, 7.0, 9.0, 11.0, 13.0]
loss_array = []
num = len(x_array)
learning_rate = 0.01
iter = 100
w = 2.0
b = 1.0
for i in range(iter):
w_grad = 0.0
b_grad = 0.0
loss = 0.0
for j in range(num):... |
daf695d99268e6a94c53fdc837274a2d20ede3fe | Issue-03/Data-Structures-and-Algorithms | /Greedy Algorithm/Largest number with given sum.py | 868 | 3.921875 | 4 | '''A boy lost the password of his super locker.
He remembers the number of digits N as well as the sum S of all the digits of his password.
He know that his password is the largest number of N digits that can be possible with given sum S.
As he is busy doing his homework, help him retrieving his password.'''
def lar... |
298754de9ce7d9503bd6583dae93472add57f056 | AmbyMbayi/CODE_py | /Pandas/Movie_DataAnalysis/Question3.py | 224 | 3.796875 | 4 | """Write a pandas program to get the details of the third movie of the data frame"""
import pandas as pd
df= pd.read_csv('movies_metadata.csv')
third_movie = df.iloc[2]
print("details of the third movie")
print(third_movie) |
c4ea4ffadb9fd14b95bdb589c73edcbb439eb6bc | AmbyMbayi/CODE_py | /Pandas/Excel_DataAnalysis/Question3.py | 201 | 3.8125 | 4 | """write a pandas program to read specific columns form a given excel file"""
import pandas as pd
import numpy as np
cols = [0,1,2,4]
df = pd.read_excel('coalpublic2013.xls', usecols=cols)
print(df) |
206a6dcfb0973cd114d950ca19e5cdffa599f364 | AmbyMbayi/CODE_py | /Pandas/Movie_DataAnalysis/Question14.py | 345 | 3.90625 | 4 | """write a pandas program to get the longest runtime and shortest runtime
"""
import pandas as pd
df = pd.read_csv('movies_metadata.csv')
small_df = df[['title', 'runtime']]
run_time = small_df['runtime']
print(small_df)
print("===================")
print("Longest runtime")
print(run_time.max())
print("Shortest runtim... |
562c78526d055d1ca782cc39096decf79a585bb6 | AmbyMbayi/CODE_py | /Pandas/Pandas_PivotTable/Question1.py | 310 | 4.125 | 4 | """write a pandas program to create a pivot table with multiple indexes from a given excel sheet
"""
import pandas as pd
import numpy as np
df = pd.read_excel('SaleData.xlsx')
print(df)
print("the pivot table is shown as: ")
pivot_result = pd.pivot_table(df, index=["Region", "SalesMan"])
print(pivot_result) |
36da0fc5dd9965c07b54ef30e5b9d61c9eb41ad6 | AmbyMbayi/CODE_py | /Pandas/Titanic_DataAnalysis/Question13.py | 279 | 3.734375 | 4 | """write a pandas program to create a pivot table and compute suvival totals of all
classes along each group
"""
import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table('survived', index='sex', columns='class', margins=True)
print(result) |
e2a49df0b466b9f1db32da4e024403ed15fe3e94 | AmbyMbayi/CODE_py | /Pandas/Titanic_DataAnalysis/Question5.py | 249 | 3.546875 | 4 | """write a pandas program tocreate a pivot table and find survival rate by gender age wise of various classes
"""
import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.groupby('sex')[['survived']].mean()
print(result) |
4df514a30dc4f82b93d72baf9807f4d7caa83d1e | AmbyMbayi/CODE_py | /WebScraping/Question6.py | 387 | 3.703125 | 4 | """write a python program to extract and display all the headers tags from en.wikipedia.org/wiki/Main_Page
"""
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('https://en.wikipedia.org/wiki/Main_Page')
bs = BeautifulSoup(html, "html.parser")
titles = bs.find_all(['h1','h2','h3', 'h4', '... |
c04b0345edd87cd0c4d1bfdf92d583872ca40db5 | AmbyMbayi/CODE_py | /Pandas/DataFrames/Question2.py | 407 | 4.0625 | 4 | """write a python program to create and display a DataFrame from a specified dictionary data which has the index labels"""
import pandas as pd
import numpy as np
exam_data = {'name': ['Amby', 'Odhiambo', 'Moses'],
'score':[10,12,21],
'attempts':[1,3,4],
'qualify':['yes', 'no',... |
d7bbbffd621fc897c444ce8c3df2b9d0151edc4b | AmbyMbayi/CODE_py | /Pandas/Titanic_DataAnalysis/Question11.py | 288 | 3.8125 | 4 | """write a pandas program to create a pivot table and calculate number of women and men were in
a particular cabin class
"""
import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table(index=['sex'], columns=['pclass'], aggfunc='count')
print(result) |
46d99aeed14c9b78bfd589dd868d349fc274cc3a | AmbyMbayi/CODE_py | /Pandas/Pandas_PivotTable/Question11.py | 247 | 3.71875 | 4 | """Write a pandas program tocreate a pivot table and find the maximum sale value of the items
"""
import pandas as pd
import numpy as np
df = pd.read_excel('SaleData.xlsx')
table = pd.pivot_table(df, index='Item', values='Sale_amt')
print(table) |
16e1a288f8866c3c82b6bba997753cab5ff085c2 | harshitmanek/savc | /index.py | 1,083 | 4.1875 | 4 |
def main():
print "**************MENU*******************"
print "1]VOLUME OF CUBE"
print "2]SURFACE AREA OF CUBE"
print "3]VOLUME OF CUBOID"
print "4]SURFACE AREA OF CUBOID"
e=int(raw_input("\n\t\tenter your choice:"))
if(e==1):
cube_volume()
elif(e==2):
cube_surface_ar... |
0074fb78a4d1816806a9734947f7d8ae453defb4 | z2labplus/algorithm-python | /algorithm/adt/adt_string.py | 795 | 3.875 | 4 | from abc import ABC, abstractmethod
class ADTString(ABC):
"""
串 - 零个或多个字符组成的有限序列
"""
def __init__(self, s):
pass
@abstractmethod
def copy(self):
pass
@abstractmethod
def is_empty(self):
pass
@abstractmethod
def clear(self):
pass
@abstrac... |
02ee60cd5e0eee27860dfb99376933a215ad2988 | daviz888/python_works | /rollercoater.py | 220 | 4.0625 | 4 | import screen
screen.clear()
height = int(input("How tall are you, in inches? "))
if height >= 36:
print("\nYour're tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a littler older.")
|
82a4567a8110758e9d3de75cbd6e79ef144975da | daviz888/python_works | /usernames.py | 544 | 3.9375 | 4 | import screen
screen.clear()
# Check Username
current_users = ['daffy', 'jhon', 'mike', 'admin', 'john']
new_users = ['admin', 'daffy', 'kathlyn', 'lorna']
# convert element in the list to upper case
current_users =[element.upper() for element in current_users]
print("Username Exerise\n==============\n")
for user i... |
598e226c7c8a22cc8a665dec31068d22da1750fa | daviz888/python_works | /pets.py | 321 | 3.6875 | 4 | import screen
screen.clear()
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print("Currents list of pets:")
print(f' {pets} \n')
def remove_pets(pet_name):
while pet_name in pets:
pets.remove(pet_name)
remove_pets(pet_name = 'cat')
print("List of pets after removal:")
print(f'{pets}\n')... |
6f9206570acded8c3ec3b304643c321509f7deb1 | MerinovN7/pe_lab_4 | /task2.py | 264 | 3.5 | 4 | import csv
import operator
with open('students.csv',newline='') as csvfile:
spamreader = csv.DictReader(csvfile, delimiter=";")
sortedlist = sorted(spamreader, key=lambda row:(row['ФИО']), reverse=False)
for row in sortedlist:
print(row)
|
e867f240d26e01c129094cdfa9a1b2204fbb315d | s276842/Computational-Linear-Algebra | /matrix.py | 3,591 | 3.734375 | 4 | import numpy as np
def transpose(mat):
(r, c) = mat.shape
ret = np.zeros((c, r))
for i in range(0, r):
ret[:, i] = mat[i, :]
return ret
def is_square(A):
return A.shape[0] == A.shape[1]
def is_triangular(A):
''' A matrix is lower/upper triangular when all the entries below/above ... |
084926e35a3a3978e5a14d3ba60ec868276aba80 | MedardBaran/swmansion | /task1.py | 1,125 | 3.875 | 4 | import math
def short_function(a, b):
from sympy import isprime
from collections import Counter
return [i for i in a if not isprime(Counter(b)[i])]
def _my_is_prime(n) -> bool:
if n <= 3:
return n > 1
if n % 2 == 0:
return False
last_to_check = int(math.sqrt(n))
for i i... |
27aea434d597d0333bc8755fd35b04340a6c47d5 | apiphidayatal/simple-py | /2.py | 78 | 3.96875 | 4 | str = 'Hallo' #initial string
reversed=''.join(reversed(str))
print(reversed)
|
8b0716fd554604776390c6f6ab40619d19fc5e12 | KWinston/PythonMazeSolver | /main.py | 2,559 | 4.5 | 4 | # CMPT 200 Lab 2 Maze Solver
#
# Author: Winston Kouch
#
#
# Date: September 30, 2014
#
# Description: Asks user for file with maze data. Stores maze in list of lists
# Runs backtracking recursive function to find path to goal.
# Saves the output to file, mazeSol.txt. If no file given, it wil... |
1cf09e774b52cc8958207c4a343a032ec79b64ae | kharlamov-git/echo | /test.py | 178 | 3.71875 | 4 | print('Сложение двух чисел.')
a = int(input('Введите первое число: '))
b = int(input('Введите второе число: '))
print (a + b) |
9e0dedbac15039fbb48e1a6db4f4e5e201e6b4af | Daggron/Hacktober-fest | /python/N-Queens.py | 1,291 | 3.6875 | 4 | def isValidMove(board, col, row):
c = 1
for i in range(col-1, -1, -1):
if board[i] == row:
return False #Rooks Move
if board[i] == row - c:
return False #above knights move
if board[i] == row + c:
return False ... |
728f05b445719a96e421c94cd3863a01c8fe79c8 | vishalvb/practice | /python_practice/functions.py | 352 | 3.671875 | 4 | #functions
def hello():
return 'World'
print(hello().upper())
def greet(greet, name = 'blank'):
return '{},{} hello'.format(greet, name)
print(greet('vishal', 'noname'))
def info(*arg, **args):
print(arg)
print(args)
courses = [1,2,3]
info1 = {'name':'abc','age':5}
info(1,2,3, name = 'vishal')
info(courses... |
3a7a0507f8fd18fed3462a2d2d829f6345de7aa4 | vishalvb/practice | /python_practice/file_operations.py | 640 | 3.78125 | 4 | #file operations
with open('test.txt', 'r') as f:
#print('file contents using f.read()', f.read())
#print('file contencts using f.readlines()', f.readlines())
#print('file read 1 line using f.readline', f.readline())
print('read line by line, so that there is no memeory issue')
for line in f:
print(line, end = ... |
dba85c579fc14bfbc69823b5c002e9c97c2c8450 | vishalvb/practice | /python_practice/generators.py | 247 | 3.890625 | 4 | #Generators
def square(nums):
for i in nums:
yield (i*i)
my_list = square([1,2,3,4])
print(my_list)
for i in my_list:
print(i)
my_list = (x * x for x in [1,3,5])
print(type(my_list))
print('generator',my_list)
for i in my_list:
print(i)
|
cc7dca48dbf0dc74f263b0e397058cac89ed925e | Niteshsuresh/python-learning | /nitesh/calculator.py | 477 | 3.96875 | 4 |
def add(x, y): #"Adds two numbers"
total = x+y
return total;
def sub(x, y): #"sub two numbers"
return x-y
print("choose option")
print("1-Add")
print("2-Add")
choice = int(input("Enter the choice"));
num1 = int(input("Enter num1"));
num2 = int(input("Enter num2"));
if choice == 1:
print("addition of ",num1,... |
23a85b1f00f276e4484012722b2cb9af16076c33 | maximino-dev/Compilateur | /Expressions_booleennes/parser.py | 2,510 | 3.515625 | 4 | ########################
#
# parser.py
# ----------
#
# Analyseur syntaxique d'expression booleenne
#
# BOGADO GARCIA Maximino
# L3 Informatique
#
########################
'''
Grammaire :
T: {VRAI,FAUX,OU,ET,NON,(,)}
N: {Exp,Teme,Rste,Reste2,Facteur,Valeur}
S: Exp
P: Exp -> TermeReste
Terme -> FacteurReste2
R... |
0607033368949d617402bcaa748381b65bb70c70 | Nerucius/1415.datastrucgame | /adt/CircularLinkedList.py | 1,417 | 3.921875 | 4 | from adt.LinkedList import *
class CircularLinkedList(LinkedList):
def __init__(self):
LinkedList.__init__(self)
def insert(self, index, item):
LinkedList.insert(self, index, item)
# Link queue
self.get_node(len(self)-1).set_next(self._head)
def remove(self, item):
... |
199d60dad3363ee3282760640deea5dbc46f7189 | varghesetom/PyLox | /Parser.py | 22,972 | 4.40625 | 4 | #!/usr/bin/env python
'''
WHERE WE ARE
We can now encapsulate our logic into units that can be re-used: functions. The chapter goes in the unusual way of
defining a Function Call first and then explaining what a Function Declaration/Object is. In this file, we can organize
the new additions with respect to Function ... |
82aadddcc3df8f223ba46334432bfad518072048 | Taeheon-Lee/Python_bootcamp | /day01/ex04/eval.py | 1,474 | 3.953125 | 4 | class Evaluator:
@staticmethod
def zip_evaluate(coefs, words):
if not isinstance(words, list):
raise TypeError("Words should be list.")
for elem in words:
if not isinstance(elem, str):
raise ValueError("Elements of list should be string")
if not is... |
ebdc151614d5bdd9ea3023c88094e57f2b9466bb | Taeheon-Lee/Python_bootcamp | /day01/ex05/the_bank.py | 4,802 | 3.6875 | 4 | class Account(object):
ID_COUNT = 1
def __init__(self, name, **kwargs):
self.id = self.ID_COUNT
self.name = name
self.__dict__.update(kwargs)
if not hasattr(self, 'value'):
self.value = 0
Account.ID_COUNT += 1
def transfer(self, amount):
self.va... |
e10877b45b5b73fd815482aafb208025db86e3f7 | alexiaaa718/gwc | /scaffold_1.py | 1,125 | 4 | 4 | import pygame
import random
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
GREY = (127, 127, 127)
pygame.init()
# Setting the width and height of the screen [width, height]
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
screen... |
ebc40003ba1769b13c6143aa453b885fc5dcb9a5 | sdudenhofer/PyEugene-automate | /automate-csv.py | 164 | 3.546875 | 4 | import pandas as pd
file = input("Enter File Name/Location:")
data = pd.read_csv(file)
output = input("Enter Excel Filename:")
data.to_excel(output, index=False)
|
77e7b829d2d2840597c7f323142724bc8fb58456 | AaronLi/BlackjackVM | /virtual_desktop/window.py | 875 | 3.84375 | 4 | from pygame import *
class Window:
"""
Window on a desktop
"""
def __init__(self, window_surface: Surface) -> None:
super().__init__()
self.screen = window_surface
def mouse_click(self, mx, my) -> None:
"""
Where the user clicked the screen
:param mx: x cli... |
da229ebe4ee93a63d3fb269287716bb5888df0b5 | sejalbandil/Python-Practice- | /hangman/hangman.py | 1,506 | 3.96875 | 4 | def found_list():
index=0
found=0
for letter in word_list:
if input_letter== letter:
found=1
guess_list[index]= letter
index= index+1
return found
import random
data= open("sowpods.txt").readlines()
word = random.choice(data)
print("")
print("Welcome to Hangman... |
58965da70f4f647c8d83eba6a23e315945953973 | abbelini/Lab1 | /AI_Lab1/source/Network.py | 843 | 3.515625 | 4 | '''
Created on 22 jan. 2018
@author: Albert
'''
from source.Layer import layer
from source.Neuron import NN
class network(object):
'''
classdocs
'''
'''Add the 3 layers, '''
def __init__(self, num_input,num_hidden,num_output):
'''
Constructor
'''
self.inputLayer =... |
b18e8de01bb044ba7c6b0c9430d7a097923c8c23 | dgleba/flaskplayground | /29radiofield/radio2.py | 2,185 | 3.6875 | 4 | ''' small-Example: cartype was a select field widget. Create or edit a car record to try it. David Gleba.
http://stackoverflow.com/questions/14591202/how-to-make-a-radiofield-in-flask
'''
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import flask_admin as admin
from flask_admin.contrib import sqla
fro... |
ec5d09577c2594d099eca1a9b57d317e6f23b4fa | tarekbrahmi/PyFreeCodeCamp | /arithmetic_arranger/arithmetic_arranger.py | 1,906 | 3.515625 | 4 | import re
p = r"(?P<op1>\d+)\s(?P<opi>[+-])\s(?P<op2>\d+)"
def arithmetic_arranger(problems: list, calc=False):
def is_digit(s: str):
is_d = False
m = re.search(r'\d+', s)
if m:
return True
return is_d
def eq4(t: str):
return len(t) == 4
def show(l: l... |
b3582851fc855f7e6c4f277f5673e0ec6e7e0fbe | LeonardoADS84/Curso-de-python | /Herança.py | 1,653 | 3.59375 | 4 | class NPC: # classe pai
def __init__(self, nome, time, forca, municao): # consttutor com parametro de entrada
self.nome = nome
self.time = time
self.forca = forca
self.municao = municao
self.vivo = True # criado está proprietade porem não passado como parametro
... |
e7f40fa10c4a5c8b9160d1f1bc0599d5d29769bf | 98philips/GeoLocator | /find_sellers.py | 1,537 | 3.546875 | 4 | from connect import getConnection
from math import cos, asin, radians, degrees
def getPoints(lat, lon, radius):
mydb = getConnection()
cursor = mydb.cursor()
R = 6371; # earth's mean radius, km
max_lat = lat + degrees(radius/R);
min_lat = lat - degrees(radius/R);
max_lon = lon + degrees(asin... |
cb78c3bcc8365eb80b7c57d3fa922fd1934dc9b1 | momijizen/boilerplate-sea-level-predictor | /sea_level_predictor.py | 1,191 | 3.5 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import linregress
import numpy as np
def draw_plot():
# Read data from file
df = pd.read_csv('epa-sea-level.csv', index_col=0)
# Create scatter plot
plt.figure(figsize=(14,6))
plt.scatter(df.index, df['CSIRO Adjusted Sea Level'],... |
15b1c2b61c7c1ef2158a9de2407713c04a0284ca | baidongbin/python | /疯狂Python讲义/codes/11/11.6/Dialog_test.py | 2,182 | 3.640625 | 4 | from tkinter import *
# 导入 ttk
from tkinter import ttk
# 导入 simpledialog
from tkinter import simpledialog
# 导入 dialog
from tkinter import dialog
class App:
def __init__(self, master):
self.master = master
self.initWidgets()
def initWidgets(self):
self.msg = '《疯狂 Java 讲义》历时十年沉淀,现已升级到第 ... |
cbf2f246f208023c942f7c788c9452454fe127e4 | baidongbin/python | /疯狂Python讲义/codes/03/3.1/index_test.py | 233 | 3.78125 | 4 | a_tuple = ('crazyit', 20, 5.6, 'fkit', -17)
print(a_tuple)
# 访问第1个元素
print(a_tuple[0])
# 访问第2个元素
print(a_tuple[1])
# 访问倒数第1个元素
print(a_tuple[-1])
# 访问倒数第2个元素
print(a_tuple[-2])
|
032e6b4d74c97f7904577f243dc5aa4b113c57c4 | baidongbin/python | /疯狂Python讲义/codes/02/2.6/compare_opterator_test.py | 581 | 3.515625 | 4 | print("5是否大于4:", 5 > 4)
print("3的4次方是否大于或等于90.0:", 3 ** 4 >= 90)
print("20是否大于或等于20.0:", 20 >= 20.0)
print("5和5.0是否相等:", 5 == 5.0)
print("True和False是否相等:", True == False)
print("1和True是否相等:", 1 == True)
print("0和False是否相等:", 0 == False)
print(True + False)
print(False - True)
import time
# 获取当前时间
a = time.gmtime()
b =... |
ab57436eeb15ff9fbd16e50d900c91deaa3cef36 | baidongbin/python | /疯狂Python讲义/codes/06/6.1/Person.py | 1,747 | 4.09375 | 4 | class Person:
'这是学习Python定义的一个Person类'
# 下面定义了一个类变量
hair = 'black'
def __init__(self, name='Charlie', age=8):
# 下面为Person对象增加两个实例变量
self.name = name
self.age = age
# 下面定义了一个say方法
def say(self, content):
print(content)
# 调用Person类的构造方法,返回一个Person对象
# 将该Person对象... |
befc9334605cc72c88e92066e5e06aa68a8421c6 | baidongbin/python | /疯狂Python讲义/codes/08/8.4/send_test.py | 831 | 3.71875 | 4 | def square_gen(val):
i = 0
out_val = None
while True:
# 使用yield语句生成值,使用out_val接受send()方法发送的参数值
out_val = (yield out_val ** 2) if out_val is not None else (yield i ** 2)
# 如果程序使用send()方法获取下一个值,out_val会获取send()方法的返回值
if out_val is not None: print("====%d" % out_val)
i +... |
a61de764b4c8806092ff9933ca4aa4e10a4f4928 | baidongbin/python | /疯狂Python讲义/codes/03/3.3/delete_test.py | 690 | 3.875 | 4 | a_list = ['crazyit', 20, -2.4, (3, 4), 'fkit']
print(a_list)
# 删除第3个元素
del a_list[2]
print(a_list)
# 删除第2个到第4个(不包含)元素
del a_list[1:3]
print(a_list)
b_list = list(range(1, 10))
print(b_list)
# 删除第3个到倒数第2个(不包含)元素,间隔2
del b_list[2:-2:2]
print(b_list)
# 删除第3个到第5个(不包含)元素
del b_list[2:4]
print(b_list)
name = 'crazyit'
print(... |
796c56ca76a3ff790b61d03fa617eb70dcb11bed | baidongbin/python | /疯狂Python讲义/codes/02/2.3/complex_test.py | 249 | 3.640625 | 4 | ac1 = 3 + 0.2j
print(ac1)
# 输出复数类型
print(type(ac1))
ac2 = 4 - 01.j
print(ac2)
# 复数运行
print(ac1 + ac2)
# 导入cmatch模块
import cmath
# sqrt()是cmatch模块下的函数,用于计算平方根
ac3 = cmath.sqrt(-1)
print(ac3)
|
daad22194d09a8d5066cc394c02761fb5bf5edfe | baidongbin/python | /疯狂Python讲义/codes/05/5.2/varargs4.py | 818 | 3.71875 | 4 | def test(name, message):
print('用户是:', name)
print('欢迎消息:', message)
my_list = ['孙悟空', '欢迎来疯狂软件']
test(*my_list)
def foo(name, *nums):
print('name参数:', name)
print('nums参数:', nums)
my_tuple = (1, 2, 3)
foo('fkit', *my_tuple)
# 使用逆向收集,将my_tuple元组的第一个元素传给name参数,剩下的元素传递给nums参数
foo(*my_tuple)
# 不使用逆向收... |
9cc60875871a746227e909c9b2915603844e53df | baidongbin/python | /疯狂Python讲义/codes/03/3.3/tuple_test.py | 336 | 3.796875 | 4 | a_list = ['crazyit', 20, -1.2]
# 将列表转换成元组
a_tuple = tuple(a_list)
print(a_tuple)
# 使用range()函数创建区间(range)对象
a_range = range(1, 5)
print(a_range)
# 将区间转换成元组
b_tuple = tuple(a_range)
print(b_tuple)
# 创建区间时还指定了步长
c_tuple = tuple(range(4, 20, 3))
print(c_tuple)
|
961cc26729281f013409614ad41160edb6caace8 | baidongbin/python | /疯狂Python讲义/codes/10/10.8/dict_vs_defaultdict.py | 244 | 3.625 | 4 | from collections import defaultdict
my_dict = {}
# 使用 int 作为 defaultdict 的 default_factory
# 当 key 不存在时,将会返回 int 函数的返回值
my_defaultdict = defaultdict(int)
print(my_defaultdict['a'])
print(my_dict['a'])
|
18d512aa57315a533b110627e5e561602bf2ab9e | baidongbin/python | /疯狂Python讲义/codes/10/10.8/Counter_test2.py | 979 | 3.78125 | 4 | from collections import Counter
# 创建 Counter 对象
cnt = Counter()
# 访问并不存在的 key,将输出该 key 的次数为 0
print(cnt['Python'])
for word in ['Swift', 'Python', 'Kotlin', 'Kotlin', 'Swift', 'Go']:
cnt[word] += 1
print(cnt)
# 只访问 Counter 对象的元素
print(list(cnt.elements()))
# 将字符串(迭代器)转换成 Counter
chr_cnt = Counter('abracadabra')
# ... |
1b5c9affee0cc285894e01ce9dcd797d96efb660 | baidongbin/python | /疯狂Python讲义/codes/13/13.2/create_func.py | 730 | 3.5625 | 4 | # 导入访问 SQLite 的模块
import sqlite3
# 先定义一个普通函数,准备注册为 SQL 中的自定义函数
def reverse_ext(st):
# 对字符串反转,前后加方括号
return '[' + st[::-1] + ']'
# ①、打开或创建数据库
# 也可以使用特殊名::memory: 代表创建内存中的数据库
conn = sqlite3.connect('first.db')
# 调用 create_function 注册自定义函数:enc
conn.create_function('enc', 1, reverse_ext)
# ②、获取游标
c = conn.curso... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.